poj 2406 Power Strings

Sample Input
abcd
aaaa
ababab
.
Sample Output
1
4
3

解题思路:需要用到周期串这个东西,周期 period=l - nxt[l-1], 其余的就是kmp了,大佬教的kmp和网上大多不一样,可以对比看看。

Code:

#include<iostream>
#include<vector>
#include<cstdio> 
#include<cstring>

using namespace std;
char s[1000005];

vector<int>cal_nxt(string s){//kmp模板 
	int n=s.length();
	vector<int>nxt(n);
	for(int i=1;i<n;i++){
		int j=nxt[i-1];
		while(s[i]!=s[j]&&j>0) j=nxt[j-1];
		if(s[i]==s[j]) nxt[i]=++j;
	}
	return nxt;
}

int main(){
//	string s;
	while(~scanf("%s",s)){
		//关闭同步流 
		ios::sync_with_stdio(false);
		cin.tie(0);
		cout.tie(0);
		//
		if(strcmp(s,".")==0) break;//没用strcmp导致wa了好久,用string也是wa,很无奈 
		int n=strlen(s);
		vector<int>nxt=cal_nxt(s);
		int unit=n-nxt[n-1];//求周期 
		if(n%unit==0)
		cout<<n/unit<<endl;
//			printf("%d\n",n/unit);
		else cout<<1<<endl;
	}
	
	return 0;
} 
posted @ 2019-08-16 21:02  voids5  阅读(76)  评论(0)    收藏  举报