hdu1711 Number Sequence

kmp模板题
#include<stdio.h>
#include<string.h>

const int maxn = 1e6+10;
int t[maxn],p[maxn],next[maxn];
int tlen,plen;

int kmp()
{
    int i = 0,j = 0;
    while(i < tlen && j < plen)
    {
        if(j == -1 || t[i] == p[j])
        {
            i++,j++;
        }
        else
            j = next[j];
    }
    if(j == plen)
        return i - j + 1;
    else return -1;
}

void getNext()
{
    next[0] = -1;
    int i = 0,j = -1;
    while(i < plen)
    {
        if(j == -1 || p[i] == p[j])
        {
            ++i;
            ++j;
            next[i] = j;
        }
        else
            j = next[j];
    }
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&tlen,&plen);
        for(int i = 0; i < tlen; i++)
            scanf("%d",&t[i]);
        for(int i = 0; i < plen; i++)
            scanf("%d",&p[i]);
        getNext();
        printf("%d\n",kmp());
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/feynmanz/article/details/80273417