标签:blog io for 2014 ar amp size log
KMP查找整数数列,不是查找字符串。
原理是一样的,不过把字符串转换为数列,其他基本上是一样的。
#include <stdio.h>
#include <string.h>
const int MAX_N = 1000001;
const int MAX_M = 10001;
int strN[MAX_N], strM[MAX_M], next[MAX_M], N, M;
void getNext()
{
memset(next, 0, sizeof(int) * M);
for (int i = 1, j = 0; i < M; )
{
if (strM[i] == strM[j]) next[i++] = ++j;
else if (j > 0) j = next[j-1];
else i++;
}
}
int kmpSearch()
{
int i = 0, j = 0;
for ( ; M-j <= N-i && j < M; )
{
if (strN[i] == strM[j]) i++, j++;
else if (j > 0) j = next[j-1];
else i++;
}
if (j == M) return i-M+1;//注意题意从1开始
return -1;
}
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
scanf("%d %d", &N, &M);
for (int i = 0; i < N; i++)
{
scanf("%d", strN+i);
}
for (int i = 0; i < M; i++)
{
scanf("%d", strM+i);
}
getNext();
printf("%d\n", kmpSearch());
}
return 0;
}
HDU 1711 Number Sequence KMP题解,布布扣,bubuko.com
HDU 1711 Number Sequence KMP题解
标签:blog io for 2014 ar amp size log
原文地址:http://blog.csdn.net/kenden23/article/details/38390983