POJ_1961_Period_KMP

最近高中母校试点开大学课程,一群人在人人上吵来吵去看着也是醉了。


题意:


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

朴素遍历肯定超时,用KMP完成这个过程的话(就是说不是使用KMP算法,而是算法过程和KMP极其相似)就可以把复杂度降到O(N+M)级别。

调用KMP算法寻找失配函数的过程,就可以找到这个字符串向最少右移多少位可以一直匹配到现在这一位,由于寻找失配函数这一过程的性质,只要当前位匹配上了之前的某一位,而且这个循环节可以整除当前的串长,那么之前的每一位一定都可以匹配,因为可以整除这一条件导致之前有几个完整的循环节长度的串,然后字符串右移可以匹配的话自然前面都是匹配的。

一开始加了一个变量记录当前点的循环位置一样到之前的哪个点,但是后来发现有反例。因为失配函数匹配的条件是右移最小位数匹配,无视多余的前缀和没遍历到的后缀,所以有可能之前的点可以和后面的匹配长度一样却过早的匹配了。好吧,我说的不是人话,上数据:15 aabaaaabaaaabaa。


代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
#define mxn 1000010
int fail[mxn];
int rec[mxn];
char a[mxn];
int n;
void set(){
	fail[0]=rec[0]=-1;
	for(int i=0;i<n;++i){
		int j=fail[i];
		while(j!=-1&&a[i+1]!=a[j+1])	j=fail[j];
		fail[i+1] = a[i+1]==a[j+1] ? j+1 : -1;
		rec[i+1]=i+1-fail[i+1];
		if(fail[i+1]==-1)	rec[i+1]=-1;
	}
}
void solve(){
	for(int i=2;i<=n;++i)	if(rec[i-1]!=-1&&i%rec[i-1]==0)
		printf("%d %d\n",i,i/rec[i-1]);
}
int main(){
	int cs=0;
	while(scanf("%d",&n)!=EOF&&n){
		scanf("%s",a);
		printf("Test case #%d\n",++cs);
		set();
		solve();
		puts("");
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值