给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;
}