跳到正文

题解

题解:P13270 【模板】最小表示法

Fine_Dust_Z约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年7月13日
收录
2026年8月20日
更新
2026年11月14日
篇幅
约 4 分钟
题目
P13270

版本

  1. v1当前

循环同构

在了解最小表示法前,我们需要知道什么是循环同构。

所谓循环同构就是指当字符串 SS 满足使 SS 分为前后两部分: AA、BB 如果 B+A=TB+A=T 则称 SS 和 TT 为循环同构。

最小表示法

最小表示法就是字符串 SS 循环同构的所有字符串中字典序最小的字符串。

思路

这道题首先考虑到的是 simple 但本题给出的数据↓

对于全部数据,1≤n≤1071\le n\le10 7,字符串 ss 仅包含小写英文字母(ASCII 97∼122)。

我们便可以放弃 O(N2)O(N^2) 的算法,此时我们便要写一个正经的 最小表达式 ,时间复杂度为 O(N)O(N) 过此题又是有惊无险。

原理

(其实 oiwiki 上有)

定义 date.first=1date.first=1、date.second=2date.second=2、k=0k=0 。

通过不断比对以 date.firstdate.first 为首的字符串和以 date.seconddate.second 为首的字符串。

如果前 kk 位相同便让 date.first=date.first+k+1date.first=date.first+k+1

注意:当 date.first=date.seconddate.first=date.second 时,使 date.first=date.first+1date.first=date.first+1,且最终选取两者之中较小的一个作为结果。

详细代码

C++
#include"bits/stdc++.h"
#define ll long long
using namespace std;
template<typename T>inline void read(T&x) {
	char c;
	int sign = 1;
	x = 0;
	do {
		c = getchar();
		if (c == '-') sign = -1;
	} while (!isdigit(c));
	do {
		x = x * 10 + c - '0';
		c = getchar();
	} while (isdigit(c));
	x *= sign;
}
// 快读
const int N = 1e7 + 5;
// N代表题目中n的范围
char a[N << 1];
// 建立N的两倍的a数组
ll n;
int main() {
	read(n);
	for (int i = 1; i <= n; i++) {
		a[i] = getchar();// 读入
		a[i + n] = a[i];// 预处理
	}
	ll date_first = 1, date_second = 2, k = 0;
	while (date_first <= n && date_second <= n && k <= n) {
		if (a[date_first + k] == a[date_second + k])
			k++;
		else {
			if (a[date_first + k] > a[date_second + k])
				date_first += k + 1;
			else
				date_second += k + 1;
			if (date_first == date_second)
				date_second++;
			k = 0;
		}
	}
// 以上再【原理】中有解释
	int vis;
	if (date_first < date_second)
		vis = date_first;
	else vis = date_second;
// 选择两者之中较小的一位
	for (int i = 0; i < n; i++)
		cout << a[vis + i];
//输出
	return 0;
}
原文