Description
给你一个字符串,它是由某个字符串不断自我连接形成的。 但是这个字符串是不确定的,现在只想知道它的最短长度是多少.
Input
第一行给出字符串的长度,1 < L ≤ 1,000,000. 第二行给出一个字符串,全由小写字母组成.
Output
输出最短的长度
Sample Input
8
cabcabca
Sample Output
3
HINT
对于样例,我们可以利用”abc”不断自我连接得到”abcabcabc”,读入的cabcabca,是它的子串
Source
主要想练一下kmp…
答案是n-nxt[n],n-nxt[n]表示循环节
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int SZ = 1000010;
int nxt[SZ];
void getnxt(char s[])
{
int n = strlen(s);
nxt[0] = 0; nxt[1] = 0;
for(int i = 1;i < n;i ++)
{
int j = nxt[i];
while(j && s[i] != s[j]) j = nxt[j];
nxt[i + 1] = s[i] == s[j] ? j + 1 : 0;
}
}
char s[SZ];
int main()
{
int n;
scanf("%d",&n);
scanf("%s",s);
getnxt(s);
printf("%d",n - nxt[n]);
return 0;
}