UVA3026Period(最短循环节)

题目链接

题意: 给定长度为n的字符串s,求他的每个前缀的最短循环节

分析: kmp预处理 next[]数组,然后对于 前 i 个字符,如果 next[i] > 0 && i % (i - next[i] ),前 i 个字符的循环节就是(i -1, ... i - next[i])

从 0 到 n - next[n] 是最小覆盖串,从 n - next[n] ... n-1就是循环节

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int Max = 1e6 + 10;
char str[Max];
int Next[Max];
void pre_kmp(int n)
{
    int i = 0, k = -1;
    Next[0] = -1;
    while (i < n)
    {
        while (k != -1 && str[k] != str[i])
            k = Next[k];
        Next[++i] = ++k;
    }
}
int main()
{
    int test = 0;
    int n;
    while (scanf("%d", &n) != EOF && n)
    {
        getchar();
        scanf("%s", str);
        pre_kmp(n);
        printf("Test case #%d
", ++test);
        for (int i = 2; i <= n; i++)
        {
            if (Next[i] > 0 && i % (i - Next[i]) == 0)
                printf("%d %d
", i, i / (i - Next[i]));
        }
        printf("
");
    }

}
原文地址:https://www.cnblogs.com/zhaopAC/p/5394878.html