poj1961(kmp算法next数组应用)

题目链接:https://vjudge.net/problem/POJ-1961

题意:给定一个长为n的字符串(n<=1e6),对于下标i(2<=i<=n),如果子串s(1...i)是周期子串,输出其最大周期。

思路:

  考察对kmp算法中next数组的定义掌握,如果(i+1)%(i-j)==0 && (i+1)/(i-j) > 1,那么该子串即为满足条件。

AC代码:

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

const int maxn=1e6+5;
int n,cas,nex[maxn];
char s[maxn];

void get_next(){
    int j;
    j=nex[0]=-1;
    for(int i=1;i<n;++i){
        while(j>-1&&s[i]!=s[j+1]) j=nex[j];
        if(s[i]==s[j+1]) ++j;
        nex[i]=j;
        if((i+1)%(i-j)==0&&(i+1)/(i-j)>1)
            printf("%d %d\n",i+1,(i+1)/(i-j));
    }
}

int main(){
    while(scanf("%d",&n),n){
        scanf("%s",s);
        printf("Test case #%d\n",++cas);
        get_next();
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/FrankChen831X/p/11785429.html
今日推荐