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

HDU 1686: Oulipo

时间:2017-08-27 14:41:46      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:output   match   style   dex   multiple   name   ipo   index   UI   


///@link http://acm.hdu.edu.cn/showproblem.php?pid=1686
///@author Sycamore
///@date Aug, 27
#include <bits/stdc++.h>
using namespace std;
typedef vector<intVI;
//notations:
//t - text
//p - pattern
//pi -an auxiliary array such that p[0,pi[i]] 
//    is the longest suffix of p[0,i]
VI getPi(const stringp)
{
	
	VI pi = VI(p.length());
	int k = -2;
	for (int i = 0; i < p.length(); i++) 
	{
		//now k==p[i-1]
		while (k >= -1 && p[k + 1] != p[i])//find pi[i] using pi[i-1]
			k = (k == -1) ? -2 : pi[k];//make shifts
		pi[i] = ++k;
	}
	return pi;
}
 
int KMP(const stringtconst stringp)
{
	int cnt = 0;
	VI pi = getPi(p);
	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]
			//return i - k;//return if only the first match is required
			//output multiple matches
			//cout << "matched at index " << i - k << ": ";
			//cout << t.substr(i - k, p.length()) << endl;
			cnt++;
			k = (k == -1) ? -2 : pi[k];
		}
	}
	return cnt;
}
 
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int T;
	cin >> T;
	while (T--)
	{
		string p, t;
		cin >> p >> t;
		cout << KMP(t, p) <<‘\n‘;
	}
	return 0;
}

 

HDU 1686: Oulipo

标签:output   match   style   dex   multiple   name   ipo   index   UI   

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

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