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\n", ++test);
        for (int i = 2; i <= n; i++)
        {
            if (Next[i] > 0 && i % (i - Next[i]) == 0)
                printf("%d %d\n", i, i / (i - Next[i]));
        }
        printf("\n");
    }

}

 

转载于:https://www.cnblogs.com/zhaopAC/p/5394878.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值