2016"百度之星" - 资格赛(Astar Round1)Problem C (tire树)

来源:互联网 发布:js将base64转换为图片 编辑:程序博客网 时间:2024/06/16 06:59

Problem C

Accepts: 832
Submissions: 6612
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 131072/131072 K (Java/Others)
Problem Description

度熊手上有一本神奇的字典,你可以在它里面做如下三个操作: 1、insert : 往神奇字典中插入一个单词 2、delete: 在神奇字典中删除所有前缀等于给定字符串的单词 3、search: 查询是否在神奇字典中有一个字符串的前缀等于给定的字符串

Input

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

Output

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

Sample Input
5insert helloinsert hehesearch hdelete hesearch hello
Sample Output
YesNo
题解:建立tire树,然后insert,delete,search
AC代码:
#include<iostream>#include<memory.h>#include<cstdlib>#include<cstdio>#include<cmath>#include<cstring>#include<string>#include<cstdlib>#include<iomanip>#include<vector>#include<list>#include<map>#include<algorithm>typedef long long LL;using namespace std;char op[32],s[32];typedef struct node{    int num;    node *next[30];    node(){        memset(next,0,sizeof(next));        num=0;    }}Trie;void Insert(node *root,char *s){    node *p=root;    for(int i=0; s[i]; i++){        int x=s[i]-'a';        if(p->next[x]==NULL) p->next[x]=new node;        p=p->next[x];        p->num++;    }}void Delete(node *root,char *s,int cnt){    node *p=root;    for(int i=0;s[i];i++){        int x=s[i]-'a';        p=p->next[x];        p->num-=cnt;    }    for(int i=0;i<30;i++)p->next[i]=0;}int Search(node *root,char *s){    node *p=root;    for(int i=0;s[i];i++){        int x=s[i]-'a';        if(p->next[x]==NULL) return 0;        p=p->next[x];    }    return p->num;}int main(){    int n;    scanf("%d",&n);    Trie *root=new node;    for(int i=0;i<n;i++){        scanf("%s %s",op,s);        if(op[0]=='i'){            Insert(root,s);        }else if(op[0]=='s'){            int ans=Search(root,s);            if(ans) puts("Yes");            else    puts("No");        }else{            int cnt=Search(root,s);            if(cnt) Delete(root,s,cnt);        }    }    return 0;}


1 0
原创粉丝点击