POJ 2406 Power Strings (KMP 循環節個數)

題目鏈接

題意:問最小的循環節個數。

分析:和循環節那題差不多,same=m-next[m]爲最短循環節長度,如果正好除盡,輸出 m/same,否則 都是 1

#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
#define PI acos(-1)
using namespace std;
typedef long long ll;
typedef pair<string, string> P;
const int mod=1e9+7;
const int maxn=1e6+10;


int nx[maxn];
int m;
void getnx(string x){
	//int m=x.size();
	int i,j;
	j=nx[0]=-1;
	i=0;
	while (i<m){
		if (j==-1 || x[i]==x[j]){
			i++,j++;
			nx[i]=j;
		}
		else j=nx[j];
	}
}
string s;
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0); 
    while (cin>>s){
    	if (s[0]=='.') break;
    	m=s.size();
    	for (int i=0; i<=m; i++) nx[i]=0;
    	getnx(s);
    	int same=m-nx[m];
    	if (m%same==0) cout<<m/same<<endl;
    	else cout<<"1"<<endl;
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章