HDU 1711: Number Sequence

本文详细介绍KMP字符串匹配算法的原理与实现过程,并通过一个具体的C++代码示例展示了如何构建模式串的部分匹配表以及如何进行高效字符串匹配。文章还提供了一个基于KMP算法的应用案例,帮助读者更好地理解该算法的实际用途。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


///@link http://acm.hdu.edu.cn/showproblem.php?pid=1711
///@author Sycamore
///@date 8/19/2017
///@ref stanford-acm-master
#include <iostream>
#include <string>
#include <vector>
 
using namespace std;
 
typedef vector<intVI;
#define string VI
#define length size
void buildPi(stringpVIpi)
{
	pi = VI(p.length());
	int k = -2;
	for (int i = 0; i < p.length(); i++) {
		while (k >= -1 && p[k + 1] != p[i])
			k = (k == -1) ? -2 : pi[k];
		pi[i] = ++k;
	}
}
 
int KMP(stringtstringp)
{
	VI pi;
	buildPi(p, pi);
	int k = -1;
	for (int i = 0; i < t.length(); i++) {
		while (k >= -1 && p[k + 1] != t[i])
			k = (k == -1) ? -2 : pi[k];
		k++;
		if (k == p.length() - 1) {
			// p matches t[i-m+1, ..., i]
			//cout << "matched at index " << i - k << ": ";
			return i - k;
			k = (k == -1) ? -2 : pi[k];
			
		}
	}
	return -1;
}
 
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int T;
	cin >> T;
	while (T--)
	{
		int a_len, b_len;
		cin >> a_len >> b_len;
		VI a(a_len), b(b_len);
		for (auto &e : a)cin >> e;
		for (auto &e : b)cin >> e;
		int res = KMP(a, b);
		if (~res)cout << res + 1;
		else cout << -1;
		cout << '\n';
	}
	
	return 0;
}

 

转载于:https://www.cnblogs.com/zjnu/p/7395771.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值