病毒感染检测 kmp c++

d16a5a7b6e5e4cf1b4b5f1e8d2cb487b.png

#include <bits/stdc++.h>
using namespace std;

void get_next(string t, int next[])
{
	int i = 1, j = 0;
	next[1] = 0;
	while (i < t.size() - 1)
	{
		if (j == 0 || t[i] == t[j])
		{
			i ++;
			j ++;
			if (t[i] != t[j]) next[i] = j;
			else next[i] = next[j];
		}
		else j = next[j];
	}
}

int index_kmp(string people, string temp, int pos, int next[])
{
	int i = pos, j = 1;
	while (i < people.size() && j < temp.size())
	{
		if (j == 0 || people[i] == temp[j])
		{
			i ++;
			j ++;
		}
		else j = next[j];
	}
	if (j >= temp.size()) return i - temp.size() + 1;
	else return 0;
}

bool virus_detection(string virus, string people)
{
	string d_virus = virus;
	for (int i = 1; i <= virus.size() - 1; ++i)
		d_virus += virus[i];
	
	int flag = 0;
	for (int i = 1; i <= virus.size() - 1; ++i)
	{
		string temp = " ";
		for (int j = i; j <= i + virus.size() - 2; ++j)
			temp += d_virus[j];
		
		int next[virus.size()];
		get_next(temp, next);
		flag = index_kmp(people, temp, 1, next);
		if (flag) break;
	}
	
	if (flag) return true;
	else return false;
}

int main()
{
	int n;
	cin >> n;
	
	string virus, people;
	while (n --)
	{
		cin >> virus + 1 >> people + 1; 
		if (virus_detection(virus, people)) cout << "YES" << endl;
		else cout << "NO" << endl;
	}
	
	return 0;
}

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值