KMP POJ1961 Period

POJ1961 Period

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=10934

题意:给一个字符串,起点固定,终点从前往后遍历,输出存在以“某一前缀为周期串的原始串”的结点位置和根据前缀得到的周期。

思路:递推的思想,具体用KMP实现,照着大白书打的。注意个人使用的KMPnext表示长度,而遍历字符串时从0点开始,所以坐标与长度运算时注意+1-1

源码:

#include <cstdio>

#include <cmath>

#include <cstring>

#include <cstring>

#include <algorithm>

#include <iostream>

using namespace std;

int const MAXN = 1000000+5;

int fail[MAXN];

char s[MAXN];

void failure(char s[],int fail[],int n)

{

    fail[0] = 0;

    int j = fail[0];

    for(int i=1; i<n; i++){

        while(j && s[j]!=s[i])  j = fail[j-1];

        if(s[j]==s[i])  j++;

        fail[i] = j;

    }

}

int main()

{

    int n;

    int cas = 0;

    while(scanf("%d",&n)!=EOF && n){

        scanf("%s",s);

        failure(s,fail,n);

//        for(int i=0; i<n; i++)

//            printf("%d ",fail[i]);

//        printf("\n");

        printf("Test case #%d\n",++cas);

        for(int i=1; i<n; i++){

            int temp = i - fail[i] + 1 ;///错位数,因为fail表示长度比同等的i1i表示坐标),所以最后结果要加1

            if(fail[i] && (i+1)%temp==0){

                printf("%d %d\n",i+1,(i+1)/temp);

            }

        }

        printf("\n");

    }

    return 0;

}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值