fzu 1901 Problem 1901 Period II(KMP next数组应用)
http://acm.fzu.edu.cn/problem.php?pid=1901
#include <stdio.h>
#include <string.h>
#define MAXN 1000005
char str[MAXN];
int next[MAXN],ans[MAXN];
void getNext(int len)
{
int j=0,k=-1;
next[0]=-1;
while(j < len)
{
if( k == -1 || str[j] == str[k] )
{
++j;
++k;
next[j]=k;
}
else k=next[k];
}
}
int main()
{
int T,cas,len,i,j;
scanf("%d",&T);
for(cas=1; cas<=T; cas++)
{
scanf("%s",str);
len=strlen(str);
getNext(len);
for( i=0,j = len; next[j] >= 0; j=next[j] ) ans[i++] = len - next[j];
printf("Case #%d: %d\n",cas,i);
for(j=0; j<i; j++)
{
if(!j) printf("%d",ans[j]);
else printf(" %d",ans[j]);
}
printf("\n");
}
return 0;
}
浙公网安备 33010602011771号