codevs4189字典(字典树)

/*
本字典树较弱 只支持插入单词 查询单词.
特殊的 bool变量w 标记此字母是不是某个单词的结束
(然而这个题并没卵用) 
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#define maxn 300010
#define maxm 1010
using namespace std;
char s[maxm];
struct node
{
    int next[27];
    bool w;
}tire[maxn];
int n,m,topt;
void Add_tire()
{
    int l=strlen(s);
    int now=0;
    for(int i=0;i<l;i++)
      {
          int x=s[i]-'a'+1;
          if(tire[now].next[x])
          now=tire[now].next[x];
          else 
          {
              ++topt;
              tire[now].next[x]=topt;
              now=topt;
          }
      }
    tire[now].w=1;
}
int find()
{
    int len=strlen(s);
    int now=0,p=0,sum=0;
    while(p<=len-1)
      {
          if(tire[now].next[s[p]-'a'+1])
            {
              now=tire[now].next[s[p]-'a'+1];
            p++;
            continue;
          }
        return 0;
      }
    //if(!tire[now].w)return 0;
    return 1;
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
      {
          scanf("%s",s);
        Add_tire();
      }
    cin>>m;
    memset(s,0,sizeof(s));
    for(int i=1;i<=m;i++)
      {
          scanf("%s",s);
          int bo=find();
        if(bo)printf("YES
");
        else printf("NO
");
      } 
    return 0;
}
原文地址:https://www.cnblogs.com/yanlifneg/p/5463524.html