HDU - 1711:Number Sequence (KMP模板)

原题链接

KMP模板:AC,858ms,13112KB内存 消耗太大了

#include<bits/stdc++.h>
using namespace std;
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const int inf = 1 << 30;
const LL maxn = 1e6 + 10;

int s1[maxn], s2[maxn], n, m;
int nxt[maxn];
void getNext() {
    int i = 1, j = 0;
    while (i < m) {
        if (j == 0 || s2[i] == s2[j]) {
            ++i, ++j;
            if (s2[i] != s2[j]) nxt[i] = j;
            else nxt[i] = nxt[j];
        }
        else j = nxt[j];
    }
}
int kmp() {
    getNext();
    int i = 1, j = 1;
    while (i <= n && j <= m) {
        if (s1[i] == s2[j] || j == 0) ++i, ++j;
        else j = nxt[j];
    }
    if (j > m) return i - m;
    else return -1;
}

int main()
{
    int T;
    cin>>T;
    while (T--) {
        ms(s1, 0); ms(s2, 0); ms(nxt, 0);
        cin>>n>>m;
        for (int i = 1; i <= n; i++)
            cin>>s1[i];
        for (int j = 1; j <= m; j++)
            cin>>s2[j];

        printf("%d\n", kmp());
    }
    return 0;
}
posted @ 2020-06-23 20:38  RioTian  阅读(150)  评论(0编辑  收藏  举报