HDU - 1358 Period

题目:

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. 

InputThe 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. 
OutputFor 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

题意:
求每个前缀的循环节重复次数。
做法:
利用next数组,前i个字符的循环节长度=i-next[i](从0开始)如果next[i]!=0&&循环节长度可以整除i,那么就是循环成立,循环次数等于=i/循环节长度.
代码:
#include<iostream>
using namespace std;
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long LL;
struct ansdata{
	int l,c;
	bool operator<(const ansdata& pt)const{
		if (this->c!=pt.c)
		return this->c<pt.c;
		else
		return this->l<pt.l; 
	}
};
struct anstype{
	ansdata ans[1100000];
	int num;
	void init(){
		num=0;
	}
	void insert(int l,int c){
		ans[num].l=l;ans[num].c=c;num++;
	}
	void out(){
		//sort(ans,ans+num);
		for (int i=0;i<num;i++) printf("%d %d\n",ans[i].l,ans[i].c);
	}
};
anstype zans;
char s[1100000];
int nextp[1100000];
int ii;
void getnext(char s[],int nextp[],int n){
	nextp[0]=nextp[1]=0;
	for (int i=1;i<=n;i++){
		int tmp=i-nextp[i];
		int c=0;
		//printf("%d %d\n",i,nextp[i]);
		if (tmp!=i&&i%tmp==0&&s[i-1]==s[nextp[i]-1]) c=i/tmp;
		if (c>1){
			zans.insert(i,c);
		}
		if (i==n) break;
		int j=i;
		while(j>0) {
		j=nextp[j];
		if (s[i]==s[j]) break;  
		}
		if (s[j]==s[i]) nextp[i+1]=j+1;
		else nextp[i+1]=j; 
	}
}
int jx=1;
void deal(){
	ii++;
	int n;
	if (scanf("%d",&n)==EOF||!n){
		jx=0;return;
	} 
	zans.init();
	scanf("%s",s);
	getnext(s,nextp,n);
	printf("Test case #%d\n",ii);
	zans.out();
	printf("\n");
}
int main(){
	ii=0;
	while(jx) deal();
	return 0;
}

  

posted @ 2017-10-21 10:24  晓风微微  阅读(155)  评论(0编辑  收藏  举报