題意:
在一段字元串的所有字首中,找出有循環節的那些字首,并分别求這些字首的最大循環節數量。
解題思路:
用一下公式 循環節數=(i+1)/(i+1-next[i])(當(i+1)%(i+1-next[i])==0時)即可
代碼:
#include <cstdio>
#include <iostream>
using namespace std;
const int maxn=1e6+5;
char str[maxn];
int nex[maxn];
void getnext(int n)
{
int i, k=0;
nex[0]=0;
for(i=1; i<n; i++)
{
while(k>0 && str[k]!=str[i])k=nex[k-1];
if(str[k]==str[i])k++;
nex[i]=k;
}
return;
}
int main()
{
int n;
int e=1;
while(~scanf("%d", &n))
{
if(n==0)break;
int i;
scanf("%s", str);
getnext(n);
printf("Test case #%d\n", e++);
for(i=0; i<n; i++)
{
if(nex[i] && (i+1)%(i+1-nex[i])==0)
{
printf("%d %d\n", i+1, (i+1)/(i+1-nex[i]));
}
}
printf("\n");
}
}