Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs froms in exactly one position".
Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively.
Next follow n non-empty strings that are uploaded to the memory of the mechanism.
Next follow m non-empty strings that are the queries to the mechanism.
The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'.
For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).
2 3 aaaaa acacaca aabaa ccacacc caaac
YES NO NO
题意不难,就是给n串母串和m个询问,问母串里是否存在与询问串只差一个字符的串?
分析:看到n个母串,应该第一时间想到字典树才对,但是当时比赛的时候傻缺了,以为要分串长度的情况讨论加上字典树不熟,一直没写出来。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <functional>
#define rep(i,a,b) for (int i=a;i<((b)+1);i++)
#define Rep(i,a,b) for (int i=a;i>=b;i--)
#define foreach(e,x) for (__typeof(x.begin()) e=x.begin();e!=x.end();e++)
#define mid ((l+r)>>1)
#define lson (k<<1)
#define rson (k<<1|1)
#define MEM(a,x) memset(a,x,sizeof a)
using namespace std;
const int N=400050;
typedef pair<int, int> pii;
typedef long long ll;
struct Trie{
int size,node[1000005][26];
bool is_node[1000005];
Trie(){
size=1;
MEM(node,0);
MEM(is_node,false);
}
int idx(char c){
return c-'a';
}
void insert(char *s){
int u=0,l=strlen(s);
rep(i,0,l-1){
int c=idx(s[i]);
if (!node[u][c]) node[u][c]=size++;
u=node[u][c];
}
is_node[u]=size;
}
bool exist(char *s){
int u=0,l=strlen(s);
rep(i,0,l-1){
int c=idx(s[i]);
rep(j,0,2){
if (c==j||node[u][j]==0) continue;
int u2=node[u][j];
bool flag=true;
rep(k,i+1,l-1){
int c=idx(s[k]);
if (!node[u2][c]){
flag=false;
break;
}
u2=node[u2][c];
}
if (flag&&is_node[u2]) return true;
}
if (!node[u][c]) return false;
u=node[u][c];
}
return false;
}
}tree;
char s[1000005];
int n,m;
int main(int argc, char const *argv[]){
scanf("%d%d",&n,&m);
rep(i,1,n){
scanf("%s",s);
tree.insert(s);
}
rep(i,1,m){
scanf("%s",s);
tree.exist(s)?puts("YES"):puts("NO");
}
return 0;
}