您的位置:首页 > 其它

字典树Trie

2017-10-07 16:12 190 查看
度熊手上有一本神奇的字典,你可以在它里面做如下三个操作:   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 <iostream>#include <stdio.h>#include<string.h>#include<algorithm>using namespace std;struct Trie{Trie *next[27];int v;Trie(){for(int i=0; i<27; i++)next[i]=NULL;v=0;}};void insert (char *str,Trie *root){//cout <<"______________1111111______________"<<endl;int m;Trie *p;p=root;//cout<<"adsadadasda     "<<p->v<<endl;for(int i=0;str[i]; i++){m=str[i]-'a';if(p->next[m]==NULL){(p->next[m])=new Trie;//cout<<"-------"<<i<<endl;}((p->next[m])->v)++;//cout<<"----------------"<<bool(p->next['l'-97])<<endl;p=(p->next[m]);}}int quere(char *str,Trie *root){int m,i;Trie *p;p=root;for(i=0;str[i ]; i++){m=str[i]-'a';//cout <<"______________****222222______________"<<endl;// cout<<(q->v)<<endl;if(p->next[m]==NULL){return 0;}//cout <<"______________222222______________"<<endl;p=p->next[m];}return 1;}int del(char *str,Trie *root){int len=strlen(str);//cout <<"______________3333333______________"<<endl;int m,i,k;Trie *p,*q;p=root;q=root;for(i=0; str[i]; i++){m=str[i]-'a';if(p->next[m]==NULL){return 0;}if(i==len-1){k=p->next[m]->v;}p=p->next[m];}for(i=0; str[i]; i++){m=str[i]-'a';if(q->next[m]==NULL){return 0;}(q->next[m]->v)=(q->next[m]->v)-k;if((q->next[m]->v)<1){q->next[m]=NULL;return 0;}if(i==len-1){q->next[m]=NULL;}q=q->next[m];}return 0;}/*void show(Trie *root,int j=0){for(int i=0; i<=25; i++)if(root->next[i]!=NULL){cout<<j<<"--------"<<char(i+97)<<endl;show(root->next[i],j+1);}}*/int main(){Trie *root;char a[10],str[25];int n;while(scanf("%d",&n)!=EOF){root=new Trie;while(n--){scanf("%s%s",a,str);(root->v)=1;if(strcmp(a,"insert")==0){insert(str,root);// show(root);}if(strcmp(a,"search")==0){int b=quere(str,root);// cout <<"______________444444______________"<<endl;if(b){//   cout <<"______________555555______________"<<endl;printf("Yes\n");}elseprintf("No\n");}if(strcmp(a,"delete")==0)del(str,root);//show(root);}}return 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: