码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1711: Number Sequence

时间:2017-08-19 12:55:47      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:build   mil   out   seq   tor   UI   match   while   lin   


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

 

HDU 1711: Number Sequence

标签:build   mil   out   seq   tor   UI   match   while   lin   

原文地址:http://www.cnblogs.com/zjnu/p/7395771.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!