首页 > 其他 > 详细

Period

时间:2014-04-05 22:05:26      阅读:483      评论:0      收藏:0      [点我收藏+]

Period

Time Limit : 6000/3000ms (Java/Other)   Memory Limit : 60000/30000K (Java/Other)
Total Submission(s) : 16   Accepted Submission(s) : 3
Problem Description
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 AK ,that is A concatenated K times, for some string A. Of course, we also want to know the period K.
 

Input
The input 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
 
求出next[]发现:
  前缀为i的串 的 周期=i-next[i]    循环次数=i/周期,   (i % 周期 != 0,不存在周期)。

代码如下:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int next[1000005];
char s[1000005];
int n , m ;
void get_next()
{
	int j ;
	next[1]=next[0]= 0;
	for(int i = 1; i < m; i ++)
	{
		j = next[i];
		while(j && s[i] != s[j]) j = next[j];
		next[i + 1] = s[i] == s[j] ? j + 1 : 0;
	}
	printf("Test case #%d\n",n++);
	for(int i = 1; i <= m; i ++)
	{
		if(next[i] > 0 && i % (i - next[i])== 0)
		     printf("%d %d\n",i,i/(i - next[i]));
	}
	printf("\n");
}
int main()
{
	n = 1;
	while(scanf("%d",&m),m)
	{
		scanf("%s",s);
		get_next();
	}
	return 0;
}


Period,布布扣,bubuko.com

Period

原文:http://blog.csdn.net/wuhuajunbao/article/details/22990793

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!