POJ 2406

题面:http://poj.org/problem?id=2406

本题中的可能的最短循环节即为KMP中的next[len-1],若len-next[len-1]能被len整除,则有最短循环节,否则输出1。

Code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1000005;
int next[N];
char s[N];
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];
        }
    }
}
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);
    }
}
posted @ 2019-07-16 15:08  prestige  阅读(75)  评论(0编辑  收藏  举报