标签:
void Start() { int i = 0, j = -1; while (i < m-1) { if (j == -1 || b[i] == b[j]) { ++i; ++j; if (b[i] != b[j]) next[i] = j; else next[i] = next[j]; } else j = next[j]; } }
详解KMP算法网址:(原创)详解KMP算法 - 孤~影 - 博客园 http://www.cnblogs.com/yjiyjige/p/3263858.html
#include<stdio.h>
const int N=1000010;
int a[N], b[10010], next[10010];
int m, n;
void Getnext()
{
int i = 0, j = -1;
while (i < m)
{
if (j == -1 || b[i] == b[j])
{
i++;
j++;
if (b[i] == b[j])
next[i] = next[j];
else next[i] = j;
}
else j = next[j];
}
}
int main ()
{
int T, i, j;
scanf("%d", &T);
while (T--)
{
scanf("%d%d", &n, &m);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < m; i++)
scanf("%d", &b[i]);
next[0] = -1;
Getnext();
i = 0; j = 0;
while (i < n && j < m)
{
if (j == -1 || a[i] == b[j])
{
i++;
j++;
}
else j = next[j];
}
if (j == m) printf("%d\n", i-j+1);
else printf("-1\n");
}
return 0;
}
HDU 1711 Number Sequence(KMP模板)
标签:
原文地址:http://www.cnblogs.com/syhandll/p/4775424.html