CodeForces - 514C Watto and Mechanism(字典树)
题目
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 from s 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.
Input
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’.
Output
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).
Examples
input
2 3
aaaaa
acacaca
aabaa
ccacacc
caaac
output
YES
NO
NO
题目大意与解题思路
先给n个字符串,再给m个查询,问存不存在和n个中的某一个只差一个字符
因为n和m非常大,所以用字典树处理前n个字符串,之后在字典树上dfs。
//这道题因为if() if() else if() else() 没有加”{}“调了好久QAQ
AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <string>
#include <map>
#include <set>
#define LL long long
using namespace std;
#define maxn 300007
#define maxx 600007
#define maxNode 3
int num[maxn][3];
char s[maxx];
struct node
{
node* next[maxNode];
int flag;
};
node* createNode()
{
node *q=new node;
for(int i=0;i<maxNode;i++)
{
q->next[i]=NULL;
}
return q;
}
void insertNode(node *trie,char *c)
{
int i=0;
int k;
node *p=trie;
while(c[i])
{
k=c[i++]-'a';
if(p->next[k]==NULL)
{
node *q=createNode();
p->next[k]=q;
}
p=p->next[k];
}
p->flag=1;
}
int dfs(node *trie,char *c,int x)
{
node *p=trie;
int i,j;
if(trie==NULL) return 0;
if(c[0]=='\0')
{
if(x==1&&p->flag)
{
return 1;
}
else
{
return 0;
}
}
for(i=0;i<3;i++)
{
if(c[0]=='a'+i)
{
if(dfs(trie->next[i],c+1,x)) return 1;
}
else if(x==0)
{
if(dfs(trie->next[i],c+1,1)) return 1;
}
}
return 0;
}
int main()
{
int len,n,i,j,k,m,x,y;
scanf("%d%d",&n,&m);
node *trie=createNode();
for(i=1;i<=n;i++)
{
scanf("%s",s);
insertNode(trie,s);
}
for(j=1;j<=m;j++)
{
scanf("%s",s);
bool flag=0;
for(i=0;i<3;i++)
{
if(s[0]=='a'+i)
{
if(dfs(trie->next[i],s+1,0))
{
flag=1;
break;
}
}
else if(dfs(trie->next[i],s+1,1))
{
flag=1;
break;
}
}
if(flag) printf("YES\n");
else printf("NO\n");
}
return 0;
}