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;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章