题意
求再加几个字符,才能使原字符串构成循环
样例
Sample Input
3
aaa
abca
abcde
Sample Output
0
2
5
AC代码
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
char P[100009];
//int answer[100];
void GetNext(char* p,int* next)
{
int pLen = strlen(p);
next[0] = -1;
int k = -1;
int j = 0;
while (j < pLen )
{
if (k == -1 || p[j] == p[k])
{
k++;
j++;
next[j] = k;
}
else
{
k = next[k];
}
}
/*
cout<<"next数组:";
for(int i=0;i<=pLen;i++)
cout<<next[i]<<" ";
cout<<endl<<endl;
*/
}
int main()
{
int next[100009];
int n,ciclelen,length,ins,times;
cin>>n;
while(n--)
{
scanf("%s",P);
length=strlen(P);
GetNext(P,next);
ciclelen=length-next[length]; //循环部分的长度
//times = length/ciclelen; //循环部分出现的次数。但不要在这里出现,因为在这里出现会浪费程序时间,在下面的else里做这个除法
//故:循环部分占用的总字节数=clclelen*times
if(length!=ciclelen && length%ciclelen==0)
//循环多次的情况,但要注意:不能是循环一次,因为只循环一的话就是length==ciclelen,但这种情况ins不能是0,而应该是length
ins=0;
else if(ciclelen==length)
ins=ciclelen;
else
{
times = length/ciclelen;
ins=ciclelen-(length-ciclelen*times);
}
cout<<ins<<endl;
}
return 0;
}
// abcabca,正确答案是2
题源:acm.hdu.edu.cn/showproblem…