标签:ref const while space lse ++ sequence ber number
#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;
}
HDU - 1711:Number Sequence (KMP模板)
标签:ref const while space lse ++ sequence ber number
原文地址:https://www.cnblogs.com/RioTian/p/13184355.html