首页 > 代码库 > HDU 1711 Number Sequence KMP题解

HDU 1711 Number Sequence KMP题解

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;
}