There is a string A. The length of A is less than 1,000,000. I rewrite it again and again. Then I got a new string: AAAAAA...... Now I cut it from two different position and get a new string B. Then, give you the string B, can you tell me the length of the shortest possible string A.
For example, A="abcdefg". I got abcd efgabcdefgabcdefgabcdefg.... Then I cut the red part: efgabcdefgabcde as string B. From B, you should find out the shortest A.
Input
Multiply Test Cases.
For each line there is a string B which contains only lowercase and uppercase charactors.
The length of B is no more than 1,000,000.
Output
For each line, output an integer, as described above.
Sample Input
bcabcab efgabcdefgabcde
Sample Output
3 7
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<stdio.h>
#include<string.h>
#include<algorithm>
//KMP-性质
//本题利用KMP算法中求Next[]数组的性质可以解决;
//即如果一个字符串为循环串时,(例如adcabcabc)
//那么它的next[]数组满足下面性质:
//1、len%(len-p[len])==0;
//2、len/(len-p[len])就是循环的次数;
//这里len是字符串的长度,p[]是next[]数组;
//刚开始,想的有点挫每次都执行一次Getp函数 ,结果果断超时,最后发现其实一次GetP函数后;只需判断该题中
//字符串前缀能否满足上述两个条件即可;还有就是循环次数不可能为一次;这一点需要注意;(所以就需在判断
//满足条件1后在判断是否len/(len-p[len])=1;等于说明此时的前缀不是周期串;否则就是;直接打印输出即可。
#include<stdio.h>
#include <iostream>
#include<string.h>
#include<math.h>
int p[1000010];
char str[1000010];
void getp(int len) //getp函数,求字符串的next[]数组值
{
//这里我把next[]该成了p[];其实一样。
int i=0,j=-1;
p[i]=j;
while(i<len)
{
if(j==-1||str[i]==str[j])
{
i++;
j++;
p[i]=j;
}
else
j=p[j];
}
}
int main()
{
int n,i,j,ca=1;
while(scanf("%s",str))
{
n=strlen(str);
getp(n);
int len=n-p[n];
//if(n%len==0)
printf("%d\n",len);
}
return 0;
}