字典树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 helloSample 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;}
相关文章推荐
- HDU 1247 Hat’s Words(字典树Trie)
- Data Structure: Trie(字典树)
- leetcode 208. Implement Trie (Prefix Tree) 字典树的构造 + 必须要掌握的数据结构
- HDU-4825 Xor Sum (Trie 字典树 2014年百度之星程序设计大赛-资格赛)
- Trie字典树
- hdu1251 字典树trie 模板题
- Trie字典树应用HDU--1251
- trie 字典树
- Trie-tree (字典树)
- 字典树(Trie tree)
- HDOJ 1251 统计难题(j简单的字典树trie的应用)
- HDU 1251 Trie字典树
- 算法导论:Trie字典树
- Trie Tree (字典树)的简单使用 与 模板。
- hdu 1247 Hat’s Words trie 简单字典树
- 字典树(Trie)归纳总结,模版
- trie tree 字典树的简介与实现
- Data Structure: Trie(字典树)
- 【 Codeforces Round #367 (Div. 2) D】 Vasiliy's Multiset (Trie 按数位建字典树)
- 字典树 Trie