sicily--1282. Computer Game

1.KMP算法:http://blog.csdn.net/chenhq1991/article/details/7830193

2.因为题目说说的60000的长度是 code 的长度,主串的长度未知,所以要开大点

3.有了KMP算法,这道题就很简单了,但是KMP对我来说的确很难理解

#include<iostream>
#include<vector>
using namespace std;

int code_dimension;
int code[60000];
int protection_dimension;
int protection[1000000];//坑爹
int Next[60000];

void getNext()
{
	int j,k;
	Next[0] = -1;
	j = 0;//j 为主串下标
	k = -1;//k 为子串下标
	while(j < code_dimension - 1)
	{
		if(k == -1 || code[j] == code[k])
		{
			j++;
			k++;
			Next[j] = k;//next[1] = 0;
		}
		else
		{
			k = Next[k];
		}
	}

}

int KMPMatch( )
{
	getNext();
	int i = 0;//为主串的下标
	int j = 0;//为子串的下标
	while(i < protection_dimension)
	{
		if(j == -1 || protection[i] == code[j])//j = -1的情况就是匹配的子串要从头开始
		{
			i++;
			j++;
		}
		else
		{
			j = Next[j];//protection[i] != code[j]
		}

		if(j == code_dimension)//匹配结束
			return i - code_dimension;
	}
	return -1;//表示匹配不成功
}

int main()
{
	
	while(cin >> code_dimension && code_dimension != 0)
	{
		
		for(int i = 0; i < code_dimension; i++)
		{
			cin >> code[i];
		}

		cin >> protection_dimension;
		for(int i = 0; i < protection_dimension; i++)
		{
			cin >> protection[i];
		}
		int index = KMPMatch();
		if(index != -1)
			cout << index << endl;
		else
			cout << "no solution" << endl;
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值