1. 程式人生 > >poj 1961 Period (KMP+最小迴圈節)

poj 1961 Period (KMP+最小迴圈節)

Period

Time Limit: 3000MS   Memory Limit: 30000K
Total Submissions: 20563   Accepted: 10022

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

Sample Input

3
aaa
12
aabaabaabaab
0

Sample Output

Test case #1
2 2
3 3

Test case #2
2 2
6 2
9 3
12 4

Source

Southeastern Europe 2004

演算法分析:

題意:

給定一個長度為n的字串s,求它的每個字首的最短迴圈節。換句話說,對於每個i(2<=i<=n),求一個最大的整數K>1(如果K存在),使得S的前i個字元組成的字首是某個字串重複K次得到的。輸出所有存在K的i和對應的K。

比如對於字串aabaabaabaab, 只有當i=2,6,9,12時K存在,且分別為2,2,3,4

分析:

 

這裡就需要我們知道next陣列的含義:next[i]=k表示s[1...i-1]最大字首與字尾匹配數(相當於最大字首的末位置),如果next[i]>0則i-next[i]為字串匹配的時候移動的位數,

畫出圖如下

我們發現,如果1後面和4前面的字串能夠均分,且長度相同,這四段字串兩兩相等。所以,滿足i%(i-next[i])==0,即可。

所以可以推出一個重要的性質len-next[i]為此字串s[1...i]的最小迴圈節(i為字串的結尾),另外如果len%(len-next[i])==0,此字串的最小週期就為len/(len-next[i]);

#include<cstdio>
#include<iostream>
#include<fstream>
#include<algorithm>
#include<functional>
#include<cstring>
#include<string>
#include<cstdlib>
#include<iomanip>
#include<numeric>
#include<cctype>
#include<cmath>
#include<ctime>
#include<queue>
#include<stack>
#include<list>
#include<set>
#include<map>
using namespace std;
 
const int N = 1000002;
int nxt[N];
char  T[N];
int  tlen;
 
void getNext()
{
    int j, k;
    j = 0; k = -1;
	nxt[0] = -1;
    while(j < tlen)
        if(k == -1 || T[j] == T[k])
           {
           	nxt[++j] = ++k;
           	if (T[j] != T[k]) //優化
				nxt[j] = k; 
           } 
        else
            k = nxt[k];
 
}


int main()
{
 
    int TT;
	
	int kase=1;
    while(scanf("%d",&tlen)!=-1)
    {
    	if(tlen==0) break;
        scanf("%s",&T);
        printf("Test case #%d\n",kase++);
		getNext();
       for(int i=2;i<=tlen;i++)
	   {
	   
	   	if(nxt[i]>0&&(i)%(i-nxt[i])==0)
       	printf("%d %d\n",i,i/(i-nxt[i]));
	   }
	   cout<<endl;
       	 
    }
    return 0;
}