hdu 1711 KMP

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1e6+9;
const int maxn1 = 1e4+9;
int a[maxn], b[maxn1];
int n, m;
int next[maxn1];

void Next()
{
    next[0] = -1;
    for(int j = 1; j < m; j++)
    {
        int i = next[j-1];
        while(b[j] != b[i+1] && i >= 0) i = next[i];//如果不相等,就如他們匹配不成功,如 1 1 2 1 1 4, 4和2不等
        if(b[j] == b[i+1]) next[j] = i+1;//如同 1 1 2與1 1 4匹配,所以 要 i = next[i];
        else next[j] = -1;
    }
}

int kmp()
{
    Next();
    int p = 0, s = 0;
    while(p < m && s < n)
    {
        if(b[p] == a[s]) p++, s++;
        else
        {
            if(p == 0) s++;
            else p = next[p-1] + 1;
        }
    }
    if(p < m) return -1;
    return s-m;
}

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        memset(next, 0, sizeof(next));
        scanf("%d%d", &n, &m);
        for(int i = 0; i < n; i++) scanf("%d", a+i);
        for(int i = 0; i < m; i++) scanf("%d", b+i);
        int w = kmp();
        printf("%d\n", w==-1?-1:w+1);
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章