Time Limit: 1000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
Description
Input
Output
Sample Input
3 aaa 12 aabaabaabaab 0
Sample Output
Test case #1 2 2 3 3 Test case #2 2 2 6 2 9 3 12 4
Source
kmp求周期,简单题:
//本题的输入排除了周期i/k=1的情况
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1000000+10;
int next[maxn];
char s[maxn];
int n;
void getnext(char *s)//kmp不仅出现在kmp函数,在其他函数也都用到了kmp
{
int j=-1,i=0;
next[0]=-1;
while(i<n)
{
if(j==-1||s[i]==s[j])
{
i++,j++;
next[i]=j;//next[i]表示i位置的上一个位置(即i-1位置)的部分匹配值
}
//else j=-1;//还是这句简洁高效,错!
else j=next[j];//为了防止出错,用这句更保险(需要字符串自身匹配,只能用这句,不能用楼上)
}
}
int main()
{
int i,t=0;
while(scanf("%d",&n)&&n!=0)
{
t++;
scanf("%s",s);
getnext(s);
printf("Test case #%d\n",t);
if(n==2) printf("2 2\n\n");//严格按照题意,这里要加上这句话,否则当n=2,只输出Test case #t。而题意是允许n=2的。但本题不写这句也可以AC
else
{
for(i=2;i<=n;i++)
{
int k=i-next[i];//题目要求周期i/k>1
if(i/k>1&&i%k==0) printf("%d %d\n",i,i/k);
}
printf("\n");
}
}
return 0;
}