POJ 2752 Seek the Name, Seek the Fame(KMP中next陣列的運用)
題目連結
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
題意:給出一個字串,求出該字串所有相同前後綴的長度。
題解:這個題就是next陣列的簡單運用,next陣列,例如:第i位儲存的是陣列前i個字元中最長的相同前後綴長度,len為輸入字串的長度,next[len]為整個字串的最長相同前後綴長度。後面一直遞迴到公共長度為0時的所有值都是該字串的相同前後綴的長度,若是不懂可以參考這篇部落格。傳送門
#include <iostream> #include<cstring> #include<cstdio> #include<algorithm> #include<map> #include<queue> #include<set> #include<cmath> #include<stack> #include<string> const int maxn=4e5+10; const int mod=10007; const int inf=1e8; #define me(a,b) memset(a,b,sizeof(a)) #define lowbit(x) x&(-x) typedef long long ll; using namespace std; char str[maxn]; int nex[maxn]; int main() { while(scanf("%s",str)!=EOF) { int len=strlen(str); nex[0]=nex[1]=0; for(int i=1; i<len; i++)///求next陣列 { int k=nex[i]; while(k&&str[i]!=str[k]) k=nex[k]; nex[i+1]=str[i]==str[k]?++k:0; } int ans[maxn],l=0,temp=len; while(nex[temp])///求所有相同前後綴長度 { ans[l++]=nex[temp]; temp=nex[temp]; } for(int i=l-1;i>=0;i--) printf("%d ",ans[i]); printf("%d\n",len); } return 0; }