POJ 2418 Hardwood Species(trie 树)
开始想用map的,字典序不会搞,还是老老实实的用trie树把。好久没写了,忘得差不多了。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 #include <map> 6 #include <cmath> 7 #include <string> 8 #include <queue> 9 #include <vector> 10 #include <algorithm> 11 using namespace std; 12 struct node 13 { 14 int data; 15 struct node *next[129]; 16 }; 17 int num = 0; 18 char o[51]; 19 struct node *build() 20 { 21 int i; 22 node *p; 23 p = new node; 24 p -> data = 0; 25 for(i = 0; i <= 128; i ++) 26 p -> next[i] = NULL; 27 return p; 28 } 29 void insert(struct node *head,char *str) 30 { 31 int i,len; 32 len = strlen(str); 33 node *p; 34 p = head; 35 for(i = 0; i < len; i ++) 36 { 37 if(p->next[str[i]] == NULL) 38 { 39 p->next[str[i]] = build(); 40 } 41 p = p->next[str[i]]; 42 } 43 p -> data ++; 44 } 45 void dfs(struct node *head,int step) 46 { 47 int i; 48 node *p; 49 p = head; 50 if(p->data > 0) 51 { 52 o[step] = '\0'; 53 printf("%s %.4lf\n",o,p->data*100.0/num); 54 } 55 for(i = 0; i <= 128; i ++) 56 { 57 if(p->next[i] != NULL) 58 { 59 o[step] = i; 60 dfs(p->next[i],step+1); 61 } 62 } 63 } 64 int main() 65 { 66 char p[51]; 67 node *head; 68 head = build(); 69 while(gets(p) != 0) 70 { 71 insert(head,p); 72 num ++; 73 } 74 dfs(head,0); 75 return 0; 76 }