HDU 1711 Number Sequence KMP题解

本文介绍了一种使用KMP算法查找整数数列的方法,包括获取next数组和进行匹配搜索的过程。通过C语言实现,适用于查找大规模数列中的特定模式。

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值