POJ 1961 Period(KMP)

http://poj.org/problem?id=1961

题意 :给你一个字符串,让你输出到第几个字符时,循环结的个数。

思路 :这个题和2409差不多,稍微修改一下,加一个循环就行了,用的也是KMP。

#include <string.h>
#include <stdio.h>
#include <iostream>

using namespace std ;

const int maxn = 1000010 ;

char ch[maxn] ;
int next[maxn] ;

int main()
{
    int n ;
    int test = 1 ;
    while(scanf("%d%*c",&n)!=EOF)
    {
        if(n == 0) break ;
        scanf("%s",ch) ;
        printf("Test case #%d
",test) ;
        test++ ;
        int i = 0 , j = -1 ;
        next[0] = -1 ;
        while(i < n )
        {
            if(j == -1 || ch[i] == ch[j])
                next[++i] = ++j ;
            else
                j = next[j] ;
        }
        int len ;
        for(int k = 1 ; k <= n ; k++)
        {
            len = k - next[k] ;
            if(k != len && k % len == 0)
                printf("%d %d
",k,k / len) ;
        }
        printf("
") ;
    }
    return 0 ;
}
View Code
原文地址:https://www.cnblogs.com/luyingfeng/p/3545841.html