HDU 2594 Simpsons’ Hidden Talents

http://acm.hdu.edu.cn/showproblem.php?pid=2594

好题,做完之后直接对KMP的理解提升一个档次。

主要考察对_next数组含义的理解,之前的理解有点模糊,卡了两个半小时。

View Code
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std ; 
int m;
char a[50010],b[100010];
int _next[100010];
void Init_()
{
    int i,k;
    i = 0; k = -1; _next[0] = -1;  
    while(i < m){  
        if(k == -1 || b[i] == b[k]){  
            i++;k++;  
            _next[i] = k;   
        }  
        else  
            k = _next[k];  
    }  
}
int main()
{
    while(~scanf("%s%s",b,a))
    {
        int len1=strlen(b);
        int len2=strlen(a);
        strcat(b,a);
        m=strlen(b);
        Init_();
        int minx=min(len1,len2);
        while(1)
        {
            if(_next[m]<=minx)break;
            m=_next[m];
        }
        int ans=_next[m];
        if(!ans)
            puts("0");
        else
        {
            for(int i=0;i<ans;i++)
                putchar(b[i]);
            printf(" %d\n",ans);
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xiaohongmao/p/2526650.html