题目:http://acm.hdu.edu.cn/showproblem.php?pid=5687
2016百度之星资格赛C题,直接套用字典树,顺便巩固了一下自己对字典树的理解
1 #include<stdio.h> 2 #include<string.h> 3 struct node{ 4 int next[27]; 5 int cnt; 6 void init(){ 7 cnt = 0;//计数 8 memset(next,-1,sizeof(next)); 9 } 10 }; 11 struct node trie[4444444]; 12 int tot = 0;//记录节点数 13 14 void insert(char *s){ 15 int cur = 0,len = strlen(s); 16 for(int i = 0;i<len;i++){ 17 int temp = s[i]-'a'; 18 int next = trie[cur].next[temp]; 19 if(next == -1){ 20 next = ++tot; 21 trie[next].init(); 22 trie[cur].next[temp] = next; 23 } 24 cur = next; 25 trie[cur].cnt++; 26 } 27 } 28 int find(char *s){ 29 int cur = 0,len = strlen(s); 30 for(int i = 0;i<len;i++){ 31 int temp = s[i]-'a'; 32 int next = trie[cur].next[temp]; 33 if(next == -1) 34 return 0; 35 cur = next; 36 } 37 return trie[cur].cnt>0;//注意 38 } 39 void del(char *s){ 40 int cur = 0,late,len = strlen(s); 41 //这里特判一下要删除的字符串是否存在 42 for(int i=0;i<len;i++){ 43 int tmp=s[i]-'a'; 44 int next=trie[cur].next[tmp]; 45 if(next==-1) return; 46 late = cur; 47 cur=next; 48 } 49 cur = 0; 50 for(int i = 0;i<len;i++){ 51 int temp = s[i]-'a'; 52 int next = trie[cur].next[temp]; 53 late = cur; 54 cur = next; 55 trie[cur].cnt--; 56 } 57 trie[cur].init(); 58 int temp = s[len-1]-'a'; 59 trie[late].next[temp] = -1; 60 } 61 int main(){ 62 int n; 63 scanf("%d",&n); 64 char op[33],s[33]; 65 trie[0].init(); 66 while(n--){ 67 scanf(" %s %s",op,s); 68 if(op[0] == 'i'){ 69 insert(s); 70 }else if(op[0] == 's'){ 71 if(find(s)) 72 puts("Yes"); 73 else 74 puts("No"); 75 }else{ 76 del(s); 77 } 78 } 79 return 0; 80 }