poj1961 Period(KMP求周期性循环节)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_43408238/article/details/102643449

题意:给你一个字符串,然后让你看看有没有前缀的循环节大于1,如果有,输出前缀的长度和循环节大小。

思路:判断字符串是否是周期性字符串:i % (i - Next[i] )==0  ,循环节长度 i - Next[i] ,循环节出现次数为 i / (i - Next[i])。

AC Code:

#include<iostream>
#include<cstring>
#include<queue>
#include<map>
#include<stack>
#include<cmath>
#include<cstdio>
#include<iomanip>
#include<sstream>
#include<algorithm>

using namespace std;
#define read(x) scanf("%d",&x)
#define Read(x,y) scanf("%d%d",&x,&y)
#define sRead(x,y,z)  scanf("%d%d%d",&x,&y,&z)
#define gc(x)  scanf(" %c",&x);
#define mmt(x,y)  memset(x,y,sizeof x)
#define write(x) printf("%d\n",x)
#define INF 0x3f3f3f3f
#define ll long long
#define mod  998244353
#define pdd pair<double,double>
const int N = 1000;
const int M=  1e6;
char c[M+5],s[M+5];
int m;
int Next[M+5];
void kmp_pre()
{
    int i = 0;
    int j = Next[0] = -1;
    while(i < m){
        while(j != -1 && c[i]!=c[j]) j = Next[j];
        Next[++i] = ++j;
    }
}
int main()
{
    int  k = 1;
    while(~scanf("%d",&m)&&m){
        mmt(Next,0);
        scanf("%s",c);
        printf("Test case #%d\n",k++);
        kmp_pre();
        for(int i = 1;i <= m;++i){
            if(i%(i - Next[i]) == 0&&i / (i - Next[i])!=1){
                cout<<i<<" "<<i / (i - Next[i])<<endl;
            }
        }
        puts("");
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43408238/article/details/102643449