KMP模板题目。

CODE:

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;

__int64 a[1000001];
__int64 b[10001];
int nextval[10001];
__int64 N, M;

int get(__int64 a[], __int64 b[], int pos)
{
    __int64 i, j;
    i = pos;     j = 1;
    while(i <= a[0] && j <= b[0])
    {
        if(a[i] == b[j] || j == 0)
        {
            i++;
            j++;
        }
        else j = nextval[j];
    }
    if(j > b[0]) return i-M;
        return -1;
}

void get_nextval(__int64 b[], int nextval[])
{
    __int64 i, j;
    i = 1;     nextval[1] = 0;     j = 0;
    while(i < b[0])
    {
        if(j == 0 || b[i] == b[j])
        {
            ++i; ++j;
            if(b[i] != b[j]) nextval[i] = j;
            else nextval[i] = nextval[j];
        }
        else
        {
            j = nextval[j];
        }
    }
}


int main()
{
    int T;
    int i;
    scanf("%d", &T);
    while(T--)
    {
        memset(a, 0sizeof(a));
        memset(b, 0sizeof(b));
        memset(nextval, 0sizeof(nextval));
        scanf("%I64d%I64d", &N, &M);
        a[0] = N; b[0] = M;
        for(i = 1; i <= N; i++) scanf("%I64d", &a[i]);
        for(i = 1; i <= M; i++) scanf("%I64d", &b[i]);
        get_nextval(b, nextval);
        printf("%d\n"get(a, b, 1));
    }
    return 0;
}

 

posted on 2012-08-10 16:27  有间博客  阅读(200)  评论(0编辑  收藏  举报