码迷,mamicode.com
首页 > 其他好文 > 详细

[KMP]HDU1358 Period

时间:2017-06-08 20:33:54      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:思考   div   names   targe   bsp   target   href   get   开始   

题目链接

思考

题目就是利用KMP的失配数组来找循环串.具体看代码注释

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int nexta[1000002];
char s[1000002];
int n;
//失配数组 
void getnexta()
{
    memset(nexta,0,sizeof(nexta));
    int k = -1,j = 0;
    nexta[0] = -1;
    while(j < n )
    {

        if(k == -1 || s[k] == s[j])
        {
            nexta[j + 1] = k + 1;
            j ++;
            k ++;
        }
        else
        {
            k = nexta[k];
        }
    }

}
int main()
{
        int t = 0,temp;
        while(1)
        {
            t ++;
            scanf("%d",&n);
            if(n == 0)
                break;
            scanf("%s",s);
            printf("Test case #%d\n",t);
            getnexta();
            for(int i = 1; i <= n; i ++) //从1开始循环的原因是 nexta[0]必然是0 
            {
                if(nexta[i] == 0)
                {
                    continue;
                }
                else
                {
                    //这里是主要 
                    temp = i - nexta[i] ;//循环小节的长度
                    if( i  % temp == 0 && i  / temp  > 1)//这是由于nexta[i]表示的是i-1
                        printf("%d %d\n",i ,i  / temp);
                }

            }
        printf("\n");
        }
        return 0;
}

 

最后吐槽下我之前用KMP模板,之前的那个模板失配数组有毛病。

aaa这种串的失配数组是 0 0 1 大写的服!

[KMP]HDU1358 Period

标签:思考   div   names   targe   bsp   target   href   get   开始   

原文地址:http://www.cnblogs.com/OIerLYF/p/6964514.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!