---
title: "[KMP-循环节问题]HDU 1358 period"
author: "Coco_young"
date: "2012-06-27T17:13:00Z"
tags: []
slug: "kmp-hdu-1358-period"
draft: false
lastmod: "2013-02-03T02:37:18Z"
id: 1786440
url: "https://coco-young.iteye.com/blog/1786440"
---

传送门：[http://acm.hdu.edu.cn/showproblem.php?pid=1358](http://acm.hdu.edu.cn/showproblem.php?pid=1358)

题目大意：给定一个字符串，求出所有循环的前缀串，输出前缀串的长度和循环的次数（大于一才算循环串）

思路：同上一道题一样，也是求循环节，这里，枚举长度为2-N的所有前缀串（next数组可以一次预处理求出），求出其最小循环节，判断前缀串长度是否可以整除循环节长度整除，并且前缀串长度不等于循环节长度，满足条件就输出。

代码：

```
#include<iostream>
using namespace std;
const int MAXN = 1111111;
int N,next[MAXN],cas;
char s[MAXN];
void makenext(){
    int i = 0,j = -1;
    next[0] = -1;
    while(i<=N){
        if(s[i]==s[j]||j==-1)next[++i]=++j;
        else j = next[j];
    }
}
void solve(){
    for(int i=2;i<=N;i++){
        int L = i-next[i];
        if((i%L)==0&&(i/L)!=1){
            printf("%d %d\n",i,i/L);
        }
    }
}
int main(){
    while(scanf("%d",&N),N){
        scanf("%s",s);
        makenext();
        printf("Test case #%d\n",++cas);
        solve();
        puts("");
    }
    return 0;
}
```