HDU 1358 Period

5 篇文章 0 订阅

题目:


传送门

题意:

给出一个字符串,求出前缀字符串中是周期串的长度和周期数(周期数大于1)。

思路:

利用KMP求出前缀表p[],看看每个前缀串的长度减去前缀表是否可以被前缀串的长度整除,即len%(len-p[len])==0?,即len-p[len]就为周期串的周期长度,len/(len-p[len])即为周期数。

代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=1e6+5;
int n;
char a[maxn];
int p[maxn];
void prefix_table()
{
    int i=0,j=-1;
    p[0]=-1;
    while (i<=n)
    {
        if(j==-1||a[i]==a[j])
        {
            p[++i]=++j;
        }
        else
        {
            j=p[j];
        }
    }
}
int main()
{
    int num=0;
    while (scanf("%d",&n)!=EOF&&n)
    {
        num++;
        scanf("%s",a);
        prefix_table();
        printf("Test case #%d\n",num);
        for (int i=0;i<=n;i++)
        {
            int t=i-p[i];
            if(i%t==0&&i/t>1)
            {
                printf("%d %d\n",i,i/t);
            }
        }
        printf("\n");
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值