HDU - 1711:Number Sequence (KMP模板)

Posted riotian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
", kmp());
    }
    return 0;
}

以上是关于HDU - 1711:Number Sequence (KMP模板)的主要内容,如果未能解决你的问题,请参考以下文章

HDU——T 1711 Number Sequence

Number Sequence (HDU 1711)

HDU 1711 Number Sequence(KMP模板)

HDU - 1711 A - Number Sequence(kmp

Number Sequence HDU - 1711

hdu[1711]number sequence