[Baltic2009]Radio Transmission
Description
给你一个字符串,它是由某个字符串不断自我连接形成的。 但是这个字符串是不确定的,现在只想知道它的最短长度是多少.
Input
第一行给出字符串的长度,1 < L ≤ 1,000,000. 第二行给出一个字符串,全由小写字母组成.
Output
输出最短的长度
Sample Input
8
cabcabca
Sample Output
3
HINT
对于样例,我们可以利用”abc”不断自我连接得到”abcabcabc”,读入的cabcabca,是它的子串
Source
Solution :
假设一个串是一个小串循环得到的,那么这个串从第二个循环节开始到结束的这个后缀一定是和开头的前缀匹配的。
所以答案是n-fail[n]
Code :
#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/hash_policy.hpp>
#include <ext/pb_ds/priority_queue.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
#define rep(i, l, r) for (int i = (l); i <= (r); i++)
#define per(i, r, l) for (int i = (r); i >= (l); i--)
#define fst first
#define sec second
#define MS(_) memset(_, 0, sizeof(_))
#define PB push_back
#define MP make_pair
template<typename _T> inline void read(_T &x){
x = 0; bool f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = 0; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - '0'; ch = getchar();}
x = f ? x : -x;
}
int len;
char st[1111111];
int fail[1111111];
int main(){
read(len);
scanf("%s", st+1);
for(int i = 2, j = 0; i <= len; i++){
while (st[j + 1] != st[i] && j) j = fail[j];
if (st[j + 1] == st[i]) j++;
fail[i] = j;
}
printf("%d\n", len - fail[len]);
return 0;
}