题目大意:给定一段字符串,问在首和尾至少添加多少个字符,才能使该字符串形成两段循环
next[i]:前i个字符的最长的前缀和后缀的匹配长度
字符串的长度是len,则一个循环节的长度就为len - next[len];
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 100010;
int next[maxn];
char p[maxn];
int len;
void getnext(int m)
{
int i = 0, j = -1;
next[0] = -1;
while(i < m)
{
if(j==-1 || p[i]==p[j])
{
++i;
++j;
next[i] = j;
}
else j = next[j];
}
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%s", p);
len = strlen(p);
getnext(len);
int cc = len - next[len];//循环节长度
if(cc==len)
{
printf("%d\n", len);
continue;
}
if(len%cc == 0) printf("0\n");
else printf("%d\n", cc - len % cc);
}
return 0;
}