For each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, inclusive), we want to know whether the prefix is a periodic string. That is, for each i (2 <= i <= N) we want to know the largest K > 1 (if there is one) such that the prefix of S with length i can be written as A K , that is A concatenated K times, for some string A. Of course, we also want to know the period K.
Input
The input file consists of several test cases. Each test case consists of two lines. The first one contains N (2 <= N <= 1 000 000) – the size of the string S. The second line contains the string S. The input file ends with a line, having the number zero on it.
Output
For each test case, output “Test case #” and the consecutive test case number on a single line; then, for each prefix with length i that has a period K > 1, output the prefix size i and the period K separated by a single space; the prefix sizes must be in increasing order. Print a blank line after each test case.
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
思路 :
求区间[0...i-1]中是否存在循环节,并且循环的次数大于1,所以我们直接从字符串中第二个数字开始遍历至n,通过next数组判断当前字串中是否存在循环次数大于1的循环节。
AC代码
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
#include<string>
#define INF 0x3f3f3f3f
#define rep(i,a,n) for(int i=a;i<n;i++)
#define per(i,a,n) for(int i=n-1;i>=a;i--)
#define fori(x) for(int i=0;i<x;i++)
#define forj(x) for(int j=0;j<x;j++)
#define memset(x,y) memset(x,y,sizeof(x))
#define memcpy(x,y) memcpy(x,y,sizeof(x))
#define sca(x) scanf("%d", &x)
#define sca2(x,y) scanf("%d%d",&x,&y)
#define sca3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define scl(x) scanf("%lld",&x);
#define scl2(x,y) scanf("%lld%lld",&x,&y);
#define scl3(x,y,z) scanf("%lld%lld%lld",&x,&y,&z);
#define pri(x) printf("%d\n",x);
#define pri2(x,y) printf("%d %d\n",x,y);
#define prl(x) printf("%lld\n",x);
//#include <bits/stdc++.h>
typedef long long ll;
const int maxn=1e6+7;
const int mod=1e9+7;
const double eps=1e-8;
using namespace std;
char s[maxn];
int nextval[maxn];
void getnext(char *s, int len)
{
int i = 0, j = -1;
nextval[0] = -1;
while(i != len)
{
if(j == -1 || s[i] == s[j])
nextval[++i] = ++j;
else
j = nextval[j];
}
}
int main()
{
int n;
int cnt = 1;
while(sca(n) && n)
{
scanf("%s",s);
getnext(s,n);
printf("Test case #%d\n",cnt++);
rep(i,2,n+1)
{
if(i%(i - nextval[i]) == 0 && i!=(i - nextval[i]))
{
pri2(i,i/(i - nextval[i]));
}
}
printf("\n");
}
return 0;
}