【POJ - 2752】Seek the Name, Seek the Fame (KMP,公共前缀后缀长度及个数)
題干:
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 aaaaaSample Output
2 4 9 18 1 2 3 4 5題目大意:
給一個字符串S,找一個 S 的“前綴-后綴串”作為新生兒的名字(“前綴-后綴串”的定義是 既是S的前綴,又是S的后綴)?
比如:S = 'alala'。S的 “前綴-后綴串” 是{'a','ala','alala'}。給定字符串S,讓你計算S的可能? “前綴-后綴串”? 的長度。
解題報告:
? 求到最后一個字符的next數(shù)組,然后每次跳轉(zhuǎn)到next,,最后倒序輸出 就可以得到答案了
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<stack> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long #define pb push_back #define pm make_pair #define fi first #define se second using namespace std; const int MAX = 2e6 + 5; char s[MAX]; int Next[MAX],len,ans[MAX]; void getnext() {Next[0] = -1;int k = -1,j = 0;int len = strlen(s);while(j < len) {if(k == -1 || s[k] == s[j]) {k++,j++;Next[j] = k;} else k = Next[k];} } int main() {int n;while(~scanf("%s",s)) {getnext();int j = strlen(s),tot = 0;while(j) ans[++tot] = j,j = Next[j];for(int i = tot; i>=1; i--) {printf("%d%c",ans[i], i == 1 ? '\n' : ' ');}}return 0; }總結(jié):
? 這也告訴我們next數(shù)組中只有next[0] 才= -1;其他的就算是沒有,也是=0;;;main函數(shù)中這個while(j)就可以證明這一點、、、
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的【POJ - 2752】Seek the Name, Seek the Fame (KMP,公共前缀后缀长度及个数)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 申请信用卡被拒后多久可以申请 间隔时间越
- 下一篇: 信用卡申请可以撤销吗 电话取消态度要强硬