2016百度之星资格赛 C题

来源:互联网 发布:mac steam 游戏存档 编辑:程序博客网 时间:2024/05/22 00:30

Problem C

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

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

1、insert : 往神奇字典中插入一个单词2、delete: 在神奇字典中删除所有前缀等于给定字符串的单词3、search: 查询是否在神奇字典中有一个字符串的前缀等于给定的字符串
Input

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

Output

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

Sample Input
5insert helloinsert hehesearch hdelete hesearch hello
Sample Output
YesNo字典树,删除有点麻烦
#include <iostream>#include <cstring>#include <cstdio>using namespace std;struct trie{    int v;    trie *ch[35];};trie *root;char c[50],s[50];int n;void buildtrie(char *s){    int l=strlen(s);    trie *p=root,*q=NULL;    for (int i=0;i<l;i++)    {        int t=s[i]-'a';        if (p->ch[t]!=NULL)        {            p=p->ch[t];            p->v++;        }        else        {            q=new trie;            q->v=1;            for (int j=0;j<35;j++) q->ch[j]=NULL;            p->ch[t]=q;            p=p->ch[t];        }    }}void del(char *s){    trie *p=root,*path[50];    int h=0,v;    for (int i=0;i<50;i++) path[i]=NULL;    int l=strlen(s);    for (int i=0;i<l;i++)    {        int t=s[i]-'a';        if (p->ch[t]==NULL) return ;        p=p->ch[t];        path[h++]=p;    }    v=p->v;    for (int i=0;i<35;i++) p->ch[i]=NULL;    for (int i=0;i<h;i++) path[i]->v-=v;}bool ser(char *s){    trie *p=root;    int l=strlen(s);    for (int i=0;i<l;i++)    {        int t=s[i]-'a';        if (p->ch[t])        {            p=p->ch[t];            if (p->v==0) return 0;        }        else return 0;    }    return 1;}int main(){    root=new trie;    root->v=0;    for (int i=0;i<35;i++) root->ch[i]=NULL;    scanf("%d",&n);    for (int i=1;i<=n;i++)    {        scanf("%s%s",c,s);        if (c[0]=='i') buildtrie(s);        else if (c[0]=='d') del(s);        else        {            if (ser(s)) printf("Yes\n");            else printf("No\n");        }    }    return 0;}


0 0
原创粉丝点击