HDU 5687 字典樹入門
阿新 • • 發佈:2017-07-19
!= 超過 成了 spl 統計 names cnblogs nbsp otto
1、insert : 往神奇字典中插入一個單詞
2、delete: 在神奇字典中刪除所有前綴等於給定字符串的單詞
3、search: 查詢是否在神奇字典中有一個字符串的前綴等於給定的字符串
Source
2016"百度之星" - 資格賽(Astar Round1)
算是trie的入門級題目吧,也是第一次做字典樹,搞了好久。
一開始每個node分一個bool變量總感覺可以,後發現操作都是對前綴而言,並沒有精確到某一個詞,所以換成了int方便統計。
例節點root->a->p->p的值為x,就表示app為前綴的詞的數量,在insert和delete時維護這個變量、
還有就是指針的操作,又被搞迷糊一直RE,例如 node *p1=new node(),*p2=new node();
p1->child=p2; 這時如果令p2=NULL,則p1->child並不會變為NULL,這時顯然的吧,,,,只是p1->child和p2指向了同一處內存而已,內存沒有delete,
p1->child也不會受到影響。同理如果delete p2,則p2指向的內存被釋放,p1->child指向的這塊也是被釋放的內存了。
Problem C
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 1423 Accepted Submission(s): 426
1、insert : 往神奇字典中插入一個單詞
2、delete: 在神奇字典中刪除所有前綴等於給定字符串的單詞
3、search: 查詢是否在神奇字典中有一個字符串的前綴等於給定的字符串
Input 這裏僅有一組測試數據。第一行輸入一個正整數N,代表度熊對於字典的操作次數,接下來N行,每行包含兩個字符串,中間中用空格隔開。第一個字符串代表了相關的操作(包括: 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> usingnamespace std; struct node { int have; node *child[26]; node(){have=0;for(int i=0;i<26;++i) child[i]=NULL;} }; node *root; void release(node *p) { if(p==NULL) return; for(int i=0;i<26;++i){ if(p->child[i]!=NULL) release(p->child[i]); } delete p; } void Insert(char *s) { node *p=root; int n1=strlen(s); for(int i=0;i<n1;++i){int t=s[i]-‘a‘; if(p->child[t]==NULL) p->child[t]=new node(); p=p->child[t]; p->have++; } } void Delete(char *s) { node *p=root,*pre=p; int n1=strlen(s),t,num=0; for(int i=0;i<n1;++i){ t=s[i]-‘a‘; if(p->child[t]==NULL) return; pre=p; p=p->child[t]; }num=p->have; release(p); pre->child[t]=NULL; p=root; for(int i=0;i<n1-1;++i){ p=p->child[s[i]-‘a‘]; p->have-=num; } } bool Search(char *s) { node *p=root; int n1=strlen(s); for(int i=0;i<n1;++i){ int t=s[i]-‘a‘; if(p->child[t]==NULL) return 0; p=p->child[t]; } if((p->have)<1) return 0; return 1; } int main() { int N,i,j; char s1[25],s2[35]; cin>>N; root=new node(); while(N--){ scanf("%s%s",s1,s2); if(!strcmp(s1,"insert")){ Insert(s2) ; } else if(!strcmp(s1,"delete")){ Delete(s2); } else if(!strcmp(s1,"search")){ Search(s2)?puts("Yes"):puts("No"); } }release(root); return 0; }
HDU 5687 字典樹入門