Poj 1961 Period

还是利用KMP的next数组来计算循环节


直接上代码吧


#include<cstdio>
#include<cstring>
#include<algorithm>

void out(char *s,int k){
    printf("%s",s);
    printf("=%d\n",k);
}
#define debug(a) out(#a,a)

void calnext(char *arr,int *next){
    next[0]=-1;
    for(int i=1;arr[i];i++){
        int ind = next[i-1];
        while(ind >= 0 && arr[i] != arr[ind+1]) ind = next[ind];
        if(arr[i] == arr[ind+1]) next[i] = ind + 1;
        else next[i] = -1;
    }
}

const int maxn = 1123456;
char arr[maxn];
int next[maxn];

int main(){
    int n;
    int icase = 1;
    while(~scanf("%d",&n) && n){
        scanf("%s",arr);
        arr[n] = 0;
        calnext(arr,next);
        printf("Test case #%d\n",icase++);
//        for(int i=0;arr[i];i++)
//            printf("%d ",next[i]);
//        puts("");
        for(int i=1;arr[i];i++){
            int len = i + 1;
            int longer = len - (next[i] + 1);
            if(next[i] != -1 && len % longer == 0){
                printf("%d %d\n",len,len / longer);
            }
        }
        puts("");
    }
    return 0;
}


你可能感兴趣的:(Poj 1961 Period)