又是KMP中next数组的应用。
还是判断最大相同前后缀,然后不停的向前跳转,直到next数组为0为止。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int N=1e6+5;
char str[N];
int nextt[N];
int ans[N];
void makenextt(char str[],int len)
{
nextt[0]=0;
for(int i=1,k=0;i<len;i++)
{
while(k>0&&str[i]!=str[k])
k=nextt[k-1];
if(str[i]==str[k])
k++;
nextt[i]=k;
}
}
int main()
{
int n;
int ca=1;
scanf("%d",&n);
while(n--)
{
scanf("%s",str);
int len=strlen(str);
makenextt(str,len);
ans[1]=nextt[len-1];
int k=nextt[len-1]-1;
int tot=1;
while(1)
{
if(nextt[k]==0)
break;
ans[++tot]=nextt[k];
k=nextt[k]-1;
}
if(nextt[len-1]!=0)
ans[++tot]=0;
sort(ans+1,ans+tot,greater<int>() );
printf("Case #%d: %d\n",ca++,tot);
for(int i=1;i<=tot;i++)
{
if(i==tot)
printf("%d\n",len-ans[i]);
else
printf("%d ",len-ans[i]);
}
}
return 0;
}
Problem 1901 Period II
Accept: 614 Submit: 1608
Time Limit: 1000 mSec Memory Limit : 32768 KB
Problem Description
For each prefix with length P of a given string S,if
S[i]=S[i+P] for i in [0..SIZE(S)-p-1],
then the prefix is a “period” of S. We want to all the periodic prefixs.
Input
Input contains multiple cases.
The first line contains an integer T representing the number of cases. Then following T cases.
Each test case contains a string S (1 <= SIZE(S) <= 1000000),represents the title.S consists of lowercase ,uppercase letter.
Output
For each test case, first output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the number of periodic prefixs.Then output the lengths of the periodic prefixs in ascending order.
Sample Input
4oooacmacmacmacmacmafzufzufzufstostootssto
Sample Output
Case #1: 31 2 3Case #2: 63 6 9 12 15 16Case #3: 43 6 9 10Case #4: 29 12