POJ Power Strings(KMP)

来源:互联网 发布:阿里云虚拟主机伪静态 编辑:程序博客网 时间:2024/06/07 19:57

题目链接:http://poj.org/problem?id=2406

KMP求最小循环节个数。最小循环节= n - next[n];

代码:

#include <stdio.h>#include <string.h>#define INF 0x3f3f3f3fconst int N = 1000005;char s[N];int next[N], n;void get_next(char *seq, int m) {next[0] = -1;int j = next[0];for (int i = 1; i < m; i++) {while (j >= 0 && seq[i] != seq[j + 1]) j = next[j];if (seq[i] == seq[j + 1]) j++;next[i] = j;}}bool kmp(char *seq, char *seq1, int n, int m) {int j = next[0], ans = 0;for (int i = 0; i < n; i++) {while (j >= 0 && seq[i] != seq1[j + 1]) j = next[j];if (seq[i] == seq1[j + 1]) j++;if (j == m - 1) {//根据题意}}return false;}int solve() {if (n - (next[n - 1] + 1) == 0) return 1;if (n % (n - (next[n - 1] + 1)) == 0) return n / (n - (next[n - 1] + 1));else return 1;}int main() {while (~scanf("%s", s) && strcmp(s, ".") != 0) {n = strlen(s);get_next(s, n);printf("%d\n", solve());}return 0;}


0 0