您的位置:首页 > 产品设计 > UI/UE

HDU 1711 Number Sequence KMP题解

2014-08-05 21:29 417 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: