题目链接:http://codeforces.com/problemset/problem/514/C
题意:给出n个模式串,给出m个字符串,问字符串能否通过变换一次成为模式串(必须变换)
思路:利用模式串建立字典树,dfs查询是否有何m个字符串相差一位的模式串(每一个字符都有可能变换,开始写的时候以为只有当前字符不符合才进行变换,无法处理一些情况)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define maxn 600300
using namespace std;
struct Node
{
int ed;
Node *Next[5];
};
Node *tree=new Node;
char str[maxn];
void Insert(char s[])
{
int l=strlen(s);
Node *p=tree;
for (int i=0; i<l; i++)
{
int t=s[i]-'a';
if (p->Next[t]==NULL)
{
Node *newnode=new Node();
for (int j=0; j<5; j++)
newnode->Next[j]=NULL;
newnode->ed=0;
p->Next[t]=newnode;
}
p=p->Next[t];
}
p->ed=1;
}
int dfs(Node *p,int now,int flag)
{
int t=str[now]-'a';
if (str[now])
{cout<<now<<":"<<flag<<endl;
if (p->Next[t]!=NULL)
{
if (dfs(p->Next[t],now+1,flag))
return 1;
}
if (flag)
{
// flag=0;
for (int i=0; i<3; i++)
{
if (p->Next[i]!=NULL && i!=t)
{
if (dfs(p->Next[i],now+1,0))
return 1;
}
}
}
}
else
{
if (p->ed==1 && flag==0) return 1;
}
return 0;
}
void init()
{
for (int i=0;i<5;i++){//cout<<":"<<tree->Next[i];
tree->Next[i]=NULL;
}
tree->ed=0;
}
int main()
{
int n,m;
while (scanf("%d%d",&n,&m)!=EOF)
{
init();
for (int i=0;i<n;i++)
{
scanf("%s",&str);
Insert(str);
}
for (int i=0;i<m;i++)
{
scanf("%s",&str);
int l=strlen(str);
if (dfs(tree,0,1)) printf("YES\n");
else printf("NO\n");
}
}
}