POJ - 1961 Period(next数组求循环节)

题目链接:http://poj.org/problem?id=1961

题意:给你一个字符串,求每个前缀的大于等于2的循环节长度,输出前缀长和循环节循环的次数

思路:通过next数组,next表示模式串如果第i位(设str[0]为第0位)与文本串第j位不匹配则要回到第next[i]位继续与文本串第j位匹配。则模式串第1位到next[n]与模式串第n-next[n]位到n位是匹配的,如果n%(n-next[n])==0,则存在重复连续子串,长度为n-next[n],并且i!=j。


代码:

#include <cstdio>
#include <cmath>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <cctype>
#include <sstream>
#define INF 0x3f3f3f3f
#define INF 0x3f3f3f3f
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long LL;
typedef pair<LL, LL> P;
const int maxn = 1e6 + 5;
const int mod = 1e8 + 7;

int Next[maxn];
char T[maxn];
int n;
void getNext() {
    int j, k;
    j = 0;
    k = -1;
    Next[0] = -1;
    while(j < n)
        if(k == -1 || T[j] == T[k])
            Next[++j] = ++k;
        else
            k = Next[k];
}
int main() {
    //freopen ("in.txt", "r", stdin);
    int t=0;
    while (~scanf ("%d",&n)&&n){
        scanf ("%s",T);
        printf ("Test case #%d\n",++t);
        getNext();
        for (int i=2;i<=n;i++){
            int j=i-Next[i];
            if (i%j==0&&i/j>1){
                printf ("%d %d\n",i,i/j);
            }
        }
        printf ("\n");
    }
    return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值