HDU 1711 Number Sequence KMP

题目地址: http://acm.hdu.edu.cn/showproblem.php?pid=1711


AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <deque>
#include <queue>
#include <iterator>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <cctype>
using namespace std;

typedef long long LL;
const int N=10005;
const LL II=100000000;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);

int next[N],tlen,wlen;
int text[1000009],word[N];

void getnext(int *p)
{
    int j=0,k=-1;
    next[0]=-1;
    while(j<wlen)//len是p的长度
    {
        if(k==-1||p[j]==p[k])
        {
            j++;    k++;
            next[j]=k;
        }
        else
            k=next[k];
    }
}

int kmp(int *text,int *word)//主串、模式串
{//返回从第几个开始出现模式串
    int i=0,j=0,k=0;
    while(i<tlen)
    {
        if(j==-1||text[i]==word[j])
        {
            i++;j++;
        }
        else
            j=next[j];
        if(j==wlen) return i-wlen+1;
    }
    return -1;
}

int main()
{
    int i,j,T;
    cin>>T;
    while(T--)
    {
        scanf("%d%d",&tlen,&wlen);
        for(i=0;i<tlen;i++)
            scanf("%d",&text[i]);
        for(i=0;i<wlen;i++)
            scanf("%d",&word[i]);
        getnext(word);
        int xx=kmp(text,word);
        printf("%d
",xx);
    }
    return 0;
}


原文地址:https://www.cnblogs.com/dyllove98/p/3202881.html