poj 1961 Period(KMP)

来源:互联网 发布:javascript 提交表单 编辑:程序博客网 时间:2024/05/29 18:31

题目链接:http://poj.org/problem?id=1961

题目大意:给出一个长为n的字符串,求到每一个字符之前有多少个字串循环次数大于1

方法: kmp ,求出这个字符串的next数组,在字符串位数是i-next[i]的整数倍是,输出字串循环次数。

#include <iostream>#include <cstdio>#include <algorithm>#include <string>using namespace std;int next[1000010];char str[1000010];void getnext(char *s, int len){    int i = 0;    int j = -1;    next[0] = -1;    while(i < len)    {        if(j == -1 || str[i] == str[j])            next[++i] = ++j;        else            j = next[j];    }}int main(){    int n;    int cas = 0;    while(~scanf("%d",&n) && n)    {        scanf("%s",str);        getnext(str,n);        printf("Test case #%d\n",++cas);        for(int i=1;i<=n;i++)        {            int d = i - next[i];            if(next[i] && i % (i-next[i])== 0)                printf("%d %d\n",i, i/(i-next[i]));        } printf("\n");    }    return 0;}


1 0
原创粉丝点击