poj2406(kmp next數組)


大意:給出一個字符串 問它最多由多少相同的字串組成 

如  abababab由4個ab組成

 

分析:

kmp中的next數組求最小循環節的應用

例如 

ababab  next[6] = 4; 即

 

ababab

   ababab

1~4位  與2~6位是相同的

 

 

那么前兩位

就等於3、4位

3、4位就等於5、6位

……

所以 如果 能整除  也就循環到最后了

 

如果不能整除  

就最后余下的幾位不在循環內

 

例如

1212121

  1212121

最后剩余1不能等於循環節

 

代碼:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 
 6 const int maxn = 1000005;
 7 
 8 int next[maxn];
 9 
10 void get(char *s) {
11     int l = strlen(s);
12     int j = 0, k = -1;
13     next[0] = -1;
14     while(j < l) {
15         if(k == -1 || s[j] == s[k]) {
16             next[++j] = ++k;
17         } else {
18             k = next[k];
19         }
20     }
21 }
22 char s[maxn];
23 
24 int main() {
25     while(gets(s) ) {
26         if(strcmp(s,".") == 0) {
27             break;
28         }
29         get(s);
30         int ans = 1;
31         int l = strlen(s);
32         if(l % (l - next[l]) == 0) {
33             ans = l / (l - next[l]);
34         }
35         printf("%d\n", ans);
36     }
37 }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM