HDU 1358 Period

kmp

 ps:poj 2406 Power Strings 是这题的简化版 ←_←

太水就不贴代码了。。。

 

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

const int maxn=1000010;

char s[maxn];
int next[maxn];
int n;

void getnext (char* s,int* next){
    next[0]=next[1]=0;
    for (int i=1;i<n;i++){
        int j=next[i];
        while (j&&s[i]!=s[j])
            j=next[j];
        next[i+1]=s[i]==s[j]?j+1:0;
    }
}

int main (){
    int kase=0;
    while (~scanf ("%d",&n)&&n){
        scanf ("%s",s);
        getnext (s,next);
        cout<<"Test case #"<<++kase<<endl;
        for (int i=1;i<=n;i++){
            if (next[i]&&i%(i-next[i])==0)
                cout<<i<<" "<<i/(i-next[i])<<endl;
        }
        cout<<endl;
    }
    return 0;
}

你可能感兴趣的:(HDU)