Watto and Mechanism

给n个字符串,询问给定字符串是否存在,与n个字符串中有字符串与询问字符串只差一个字母,字母只有a,b,c

一眼trie,insert可以先写

void insert(string s){
	int id=0;
	int m=s.length();
	for(int i=0;i<m;i++){
		int t=s[i]-'a';
		if(!trie[id][t]){
			trie[id][t]=++tot;
		}
		id=trie[id][t];
	}
	word[id]=1;
}

怎么找呢

可以写一个深搜dfs

搜索是否下一个节点是否存在a,b,c

// Problem: C. Watto and Mechanism
// Contest: Codeforces - Codeforces Round 291 (Div. 2)
// URL: https://codeforces.com/problemset/problem/514/C
// Memory Limit: 256 MB
// Time Limit: 3000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<iostream>
#include<algorithm>
#include<cstring>
#include<bitset>
#include<vector>
#define INF (1ll<<60)
using namespace std;
typedef long long ll;
const int N=6e5+9;
int trie[N][4];//abc
bitset<N> word;
int tot=0;
bool res=false;
string t;
void insert(string s){
	int id=0;
	int m=s.length();
	for(int i=0;i<m;i++){
		int t=s[i]-'a';
		if(!trie[id][t]){
			trie[id][t]=++tot;
		}
		id=trie[id][t];
	}
	word[id]=1;
}
void dfs(int dep,int pos,int cnt){
	if(cnt>1 || res){
		return;
	}
	if(dep==(int)t.size()){
		if(word[pos] && cnt==1){
			res=true;
		}
		return;
	}
	for(int i=0;i<=2;i++){
		if(!trie[pos][i]){
			continue;
		}
		if(t[dep]-'a'==i){
			dfs(dep+1,trie[pos][i],cnt);
		}else{
			dfs(dep+1,trie[pos][i],cnt+1);
		}
	}
	
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
	int n,m;
	cin>>n>>m;
	//n
	for(int i=1;i<=n;i++){
		string s;
		cin>>s;
		insert(s);
	}
	//m
	for(int i=1;i<=m;i++){
		cin>>t;
		dfs(0,0,0);
		cout<<(res?"YES":"NO")<<'\n';
		res=false;
	}
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值