hdu 5687 裸字典樹

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

1、insert : 往神奇字典中插入一個單詞

2、delete: 在神奇字典中刪除所有前綴等於給定字符串的單詞

3、search: 查詢是否在神奇字典中有一個字符串的前綴等於給定的字符串
Input
這裏僅有一組測試數據。第一行輸入一個正整數N(1≤N≤100000)N(1≤N≤100000),代表度熊對於字典的操作次數,接下來NN行,每行包含兩個字符串,中間中用空格隔開。第一個字符串代表了相關的操作(包括: 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 <bits/stdc++.h>
using namespace std;

const int MAXN = 3000005;
const int CASE_SIZE = 26;
struct Trie
{
    int child[MAXN][CASE_SIZE],value[MAXN],trieN,root;
    void init()
    {
        trieN=root=0;value[root]=0;
        memset(child[root],-1,sizeof(child[root]));
    }
    int newnode()
    {
        trieN++;value[trieN]=0;
        memset(child[trieN],-1,sizeof(child[trieN]));
        return trieN;
    }
    void insert(char *s)
    {
        int x=root;
        for(int i=0;s[i];i++)
        {
            int d=s[i]-'a';
            if(child[x][d]==-1)
                child[x][d]=newnode();
            x=child[x][d];
            value[x]++;
        }
    }
    void del(char *s)
    {
        int x=root;
        for(int i=0;s[i];i++)
        {
            int d=s[i]-'a';
            if(child[x][d]==-1) {
                return ;
            }
            x=child[x][d];
        }
        int res=value[x];
        x=root;
        for(int i=0;s[i];i++)
        {
            int d=s[i]-'a';
            if(child[x][d]==-1) {
                return ;
            }
            int pre=x;
            x=child[x][d];
            value[x]-=res;
            if(value[x]==0) child[pre][d]=-1;
        }
    }
    int search(char *s)
    {
        int x=root;
        for(int i=0;s[i];i++)
        {
            int d=s[i]-'a';
            if(child[x][d]==-1)
                return 0;
            x=child[x][d];
        } 
        if(value[x]) return 1;
        return 0;
    }
}trie;


char s[30];
char str[30];
int main()
{
    int n;
    scanf("%d",&n);
    trie.init();
    while(n--){
        scanf("%s",str);
        scanf("%s",s);
        if(str[0]=='i') trie.insert(s);
        if(str[0]=='d') trie.del(s);
        if(str[0]=='s') if(trie.search(s)) cout<<"Yes"<<endl;
        else cout<<"No"<<endl;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章