POJ3461 Oulipo

//4_6_2:	Oulipo计算单词在文本中出现的次数 POJ3461
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxt = 1000000 + 10;
const int maxw = 10000 + 10;
int cnt;
int nextval[maxw];
void KMP(char str[],char tar[])
{
	int i,j,k,str_length,tar_length;
	str_length = strlen(str);
	tar_length = strlen(tar);
	j = 0;
	k = -1;
	nextval[0] = -1;
	while(j < tar_length)		//这里的next数组一定要到tar_length,因为不止匹配一次
	{
		if(k == -1 || tar[j] == tar[k])
		{
			j ++;
			k ++;
			if(tar[j] != tar[k])
				nextval[j] = k;
			else
				nextval[j] = nextval[k];
		}
		else k = nextval[k];
	}
/********************上面求出了next数组********************/
	i = 0;
	j = 0;
	while(str[i])
	{
		if(j == -1 || str[i] == tar[j])
		{
			i ++;
			j ++;
		}
		else
			j = nextval[j];
		if(j == tar_length)
		{
			j = nextval[j];	//nextval数组一定要到tar_length这里
			cnt ++;
		}
	}
}
int main()
{
	int loop;
	char word[maxw];
	char text[maxt];
	cin >> loop;
	while(loop --)
	{
		cnt = 0;
		cin >> word;
		cin >> text;
		KMP(text,word);
		cout << cnt << endl;
	}
	return 0;
}
/*测试结果:通过POJ3461检测
3
BAPC
BAPC
1
AZA
AZAZAZA
3
VERDI
AVERDXIVYERDIAN
0
请按任意键继续. . .
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值