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
", ans);
36     }
37 }
View Code
原文地址:https://www.cnblogs.com/zhanzhao/p/4761477.html