標籤:des style blog color os io for art
kmp對我真無奈,我對kmp真苦惱。就是個演算法嘛,我以為憑我脖子上的東西可以搞定,現在好了--搞得我頭都大了。要我寫個啥next的值,五個字:那都不是事。一到啥實際應用吧,我意識不行了,搞不清next到底有什麼作用,能幹什麼。就好比見到了二分啊--
此題的意思呢,我弄了很久,其實是找相同串,比如ACMACMACMACMACMA,從後往前看next就行了,比如最後一個next[15] = 13,代表前13個字串和後13位相同,直接用總長16 - 13 = 3,為一個解,接下來看next[13]了,一直這樣找出結果,輸出時一定注意格式,我交了4次全錯在這裡。
For each prefix with length P of a given string S,if
S[i]=S[i+P] for i in [0..SIZE(S)-p-1],
then the prefix is a “period” of S. We want to all the periodic prefixs.
Input
Input contains multiple cases.
The first line contains an integer T representing the number of cases. Then following T cases.
Each test case contains a string S (1 <= SIZE(S) <= 1000000),represents the title.S consists of lowercase ,uppercase letter.
Output
For each test case, first output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the number of periodic prefixs.Then output the lengths of the periodic prefixs in ascending order.
Sample Input
4oooacmacmacmacmacmafzufzufzufstostootssto
Sample Output
Case #1: 31 2 3Case #2: 63 6 9 12 15 16Case #3: 43 6 9 10Case #4: 29 12
#include <iostream>#include<cstring>using namespace std;int a[1000100],next[1000100];int m;char s[1000100];void getNext(){ int j; next[0] = 0; next[1] = 0; for(int i = 1;i < m;i++) { j = next[i]; while(j && s[i]!=s[j]) { j = next[j]; } next[i+1] = s[i] == s[j]?j+1:0; }}int main(){ int n,count,where = 1; cin >> n; while(n--) { cin >> s; m = strlen(s); // cout<< m; count = 0; int t = m; getNext(); while(next[m]) { a[count++] = t - next[m]; m = next[m]; } cout << "Case #" << where <<": " << count+1 << endl; where++; for(int i = 0;i < count ;i++) { cout << a[i] << " "; } cout <<t << endl; } return 0;}