1. 程式人生 > >KMP_next陣列應用_最小迴圈元_POJ1961_Period

KMP_next陣列應用_最小迴圈元_POJ1961_Period

點此開啟題目頁面

思路分析:

    在本人之前的博文中詳細討論過字串迴圈元與next陣列的關係, 直接應用相關結論即可, 下面給出AC程式碼:

//POJ1961_Period
#include <iostream>
#include <cstdio>
using namespace std;
const int MAX = 1e6 + 5;
char s[MAX]; int len;
int nex[MAX];
int main(){
	int sn = 0;
	while(++sn, scanf("%d", &len), len){
		scanf("%s", s + 1), cout << "Test case #" << sn << endl;
		//計算next陣列
		nex[1] = 0;
		for(int i = 2; i <= len; ++i){
			int t = nex[i - 1]; while(t && s[t + 1] != s[i]) t = nex[t];
			if(t > 0) nex[i] = t + 1; 
			else if(s[1] == s[i]) nex[i] = 1; else nex[i] = 0;	
			if(nex[i] > 0 && i % (i - nex[i]) == 0) cout << i << " " << i / (i - nex[i]) << endl;
		} 
		cout << endl;
	}	
	return 0;
}