集训笔记---KMP(HDUOJ NO.2594)

有一个坑是,求出来的next数组的值不能超过两个源字符串的长度如果超过记得要回溯一下

KMP会整理出来,终于结束了,可能要走了,ACM可能真的玩不起,但是无悔

题目链接http://acm.hdu.edu.cn/showproblem.php?pid=2594

AC代码

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char s1[100050], s2[50050];
int nxt[100010];
int n, m;
void get_next();
int main(void)
{
    while(scanf("%s %s", s1, s2) != EOF)
    {
        n = strlen(s1);
        m = strlen(s2);
        strcat(s1, s2);
        get_next();
        int k = m + n;
        while(nxt[k] > n || nxt[k] > m)
            k = nxt[k];
        if(nxt[k] == 0)
        {
            printf("0\n");
        }
        else
        {
            int x = nxt[k];
            for(int i = 0; i < x; i++)
            {
                printf("%c", s1[i]);
            }
            printf(" %d\n", x);
        }
    }
    return 0;
}
void get_next()
{
    int i = 0;
    int j = -1;
    nxt[0] = -1;
    while(i < (m+n))
    {
        if((j == -1) || (s1[i] == s1[j]))
        {
            i++;
            j++;
            nxt[i] = j;
        }
        else
        {
            j = nxt[j];
        }
    }
}

猜你喜欢

转载自blog.csdn.net/zzuli_xiaomingke/article/details/82185134
今日推荐