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不能等于循环节
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1000005;
int next[maxn];
void get(char *s) {
int l = strlen(s);
int j = 0, k = -1;
next[0] = -1;
while(j < l) {
if(k == -1 || s[j] == s[k]) {
next[++j] = ++k;
} else {
k = next[k];
}
}
}
char s[maxn];
int main() {
while(gets(s) ) {
if(strcmp(s,".") == 0) {
break;
}
get(s);
int ans = 1;
int l = strlen(s);
if(l % (l - next[l]) == 0) {
ans = l / (l - next[l]);
}
printf("%d\n", ans);
}
}