1. 程式人生 > >poj 2752 Seek the Name, Seek the Fame (KMP前後綴相同)

poj 2752 Seek the Name, Seek the Fame (KMP前後綴相同)

Seek the Name, Seek the Fame

Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 24954   Accepted: 13001

Description

The little cat is so famous, that many couples tramp over hill and dale to Byteland, and asked the little cat to give names to their newly-born babies. They seek the name, and at the same time seek the fame. In order to escape from such boring job, the innovative little cat works out an easy but fantastic algorithm: 

Step1. Connect the father's name and the mother's name, to a new string S. 
Step2. Find a proper prefix-suffix string of S (which is not only the prefix, but also the suffix of S). 

Example: Father='ala', Mother='la', we have S = 'ala'+'la' = 'alala'. Potential prefix-suffix strings of S are {'a', 'ala', 'alala'}. Given the string S, could you help the little cat to write a program to calculate the length of possible prefix-suffix strings of S? (He might thank you by giving your baby a name:) 

Input

The input contains a number of test cases. Each test case occupies a single line that contains the string S described above. 

Restrictions: Only lowercase letters may appear in the input. 1 <= Length of S <= 400000. 

Output

For each test case, output a single line with integer numbers in increasing order, denoting the possible length of the new baby's name.

Sample Input

ababcababababcabab
aaaaa

Sample Output

2 4 9 18
1 2 3 4 5

Source

POJ Monthly--2006.01.22,Zeyuan Zhu

題意:

給你一串字元找出的所有字首和字尾相同的部分,輸出長度。

分析:

字首和字尾相同,一看就是KMP,但next[i]陣列是求最大字首和字尾的怎麼辦?

其實看下圖:

假如abbaabbabb

我們實現這個字串自身匹配過程

第一個過程:

a b b|a b b a b b|

        |a b b a b b|a b b

| |之間字元長度為6

第二個過程:

a b ba b b |a b b|

                  |a b b |a b b a b b

| |之間字元長度為3

3 6  9(本身)  就是答案

這個匹配過程就相當於遞迴k=nxt[k]

程式碼:

#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];
string S,T,T1;
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()
{
 
	
    while(cin>>T)
    {
    	tlen= T.length();
		getNext();
		
		vector<int> ans;
		ans.push_back(tlen);  
		
		int k=nxt[tlen];
		while(k>0)
		{
			ans.push_back(k);
			k=nxt[k];
		}
		
		for(int i=ans.size()-1;i>=0;i--)
		{
			printf("%d ",ans[i]);
		}
		cout<<endl;
    }
    return 0;
}