HDU_1711 Number Sequence(KMP)

第一道kmp的题目,没想到纠结在上边这么多时间,也不知道哪错了,反正改着改着就对了。。。

#include <iostream>
#include
<cstdio>
using namespace std;
const int maxn = 1000000;
const int maxm = 10000;

int a[maxn+10], b[maxm+10];
int next[maxm+10];

void get_next(int num[], int m)
{
next[
0] = -1;
for(int i = 1, j = -1; i < m; i++)
{
while(j >= 0 && num[j+1] != num[i])
j
= next[j];
if(num[j+1] == num[i])
j
++;
next[i]
= j;
}
}

int kmp(int a[], int b[], int n, int m)
{
get_next(b, m);
for(int i = 0, j = -1; i < n; i++)
{
while(j >= 0 && b[j+1] != a[i])
j
= next[j];
if(b[j+1] == a[i])
j
++;
if(j == m-1)
return i-j+1;
}
return -1;
}

int main()
{
//freopen("data.in", "r", stdin);
int t, n, m;
while(scanf("%d", &t)!= EOF)
{
while(t--)
{
scanf(
"%d%d", &n, &m);
for(int i = 0; i < n; i++)
scanf(
"%d", a+i);
for(int j = 0; j < m; j++)
scanf(
"%d", b+j);
printf(
"%d\n", kmp(a, b, n, m));
}
}
return 0;
}

你可能感兴趣的:(sequence)