HDU 5687 Problem C 字典树

Problem C
Time Limit:1000MS     Memory Limit:131072KB     64bit IO Format:%I64d & %I64u

Description

度熊手上有一本神奇的字典,你可以在它里面做如下三个操作: 

  1、insert : 往神奇字典中插入一个单词 

  2、delete: 在神奇字典中删除所有前缀等于给定字符串的单词 

  3、search: 查询是否在神奇字典中有一个字符串的前缀等于给定的字符串 

Input

这里仅有一组测试数据。第一行输入一个正整数,代表度熊对于字典的操作次数,接下来行,每行包含两个字符串,中间中用空格隔开。第一个字符串代表了相关的操作(包括: insert, delete 或者 search)。第二个字符串代表了相关操作后指定的那个字符串,第二个字符串的长度不会超过30。第二个字符串仅由小写字母组成。

Output

对于每一个search 操作,如果在度熊的字典中存在给定的字符串为前缀的单词,则输出Yes 否则输出 No。

Sample Input

5
insert hello
insert hehe
search h
delete he
search hello

Sample Output

Yes
No


来自琪琪学长的字典树模板
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
#include <iomanip>
#include <math.h>
#include <map>
using namespace std;
#define FIN     freopen("input.txt","r",stdin);
#define FOUT    freopen("output.txt","w",stdout);
#define INF     0x3f3f3f3f
#define lson    l,m,rt<<1
#define rson    m+1,r,rt<<1|1
typedef long long LL;

struct node{
   int next[27];
   int v,num;
   void init(){
      v=0;
      num=0;
      memset(next,-1,sizeof(next));
   }
}L[400000];

int tot=0;

void add(char a[],int len){
   int now=0;
   for(int i=0;i<len;i++){
       int tmp=a[i]-'a';
       int next=L[now].next[tmp];
       if(next==-1){
           next=++tot;
           L[next].init();
           L[next].v=-1;
           L[now].next[tmp]=next;
       }
       now=next;
       L[now].num++;
   }
   L[now].v=0;
}

bool query(char a[],int len){
   int now=0;
   for(int i=0;i<len;i++){
       int tmp=a[i]-'a';
       int next=L[now].next[tmp];
       if(next==-1)  return false;
       now=next;
   }
   return L[now].num>0;
}

void deletes(char a[],int len){
   int now=0,late;
   for(int i=0;i<len;i++){
       int tmp=a[i]-'a';
       int next=L[now].next[tmp];
       if(next==-1)  return ;
       late=now;
       now=next;
   }
   now=0;
   for(int i=0;i<len;i++){
       int tmp=a[i]-'a';
       int next=L[now].next[tmp];
       if(next==-1)  return ;
       late=now;
       now=next;
       L[now].num--;
   }

   L[now].init();
   int tmp=a[len-1]-'a';
   L[late].next[tmp]=-1;

}

int main()
{
    //FIN
    int N;
    L[0].init();
    scanf("%d",&N);
    while(N--){
        char op[10];
        char word[35];
        scanf("%s",op);
        scanf("%s",word);
        int len=strlen(word);
        if(op[0]=='i')  add(word,len);
        if(op[0]=='s'){
            if(query(word,len))  printf("Yes
");
            else  printf("No
");
        }
        if(op[0]=='d')  deletes(word,len);


    }
    return 0;

}

  

原文地址:https://www.cnblogs.com/Hyouka/p/5803797.html