数据比较随机,直接bst可以过。
1 #include <cstring> 2 #include <cstdio> 3 using namespace std; 4 5 const int N = 101; 6 int tot; 7 8 struct Node 9 { 10 Node * ch[2]; 11 char v[N]; 12 int cnt; 13 int cmp( char * x ) 14 { 15 int tmp = strcmp( x, v ); 16 if ( tmp == 0 ) return -1; 17 return tmp < 0 ? 0 : 1; 18 } 19 }; 20 21 void insert( Node * & o, char * x ) 22 { 23 if ( o == NULL ) 24 { 25 o = new Node (); 26 o->ch[0] = o->ch[1] = NULL; 27 o->cnt = 1; 28 strcpy( o->v, x ); 29 return ; 30 } 31 int d = o->cmp(x); 32 if ( d == -1 ) 33 { 34 o->cnt++; 35 return ; 36 } 37 insert( o->ch[d], x ); 38 } 39 40 void free( Node * o ) 41 { 42 if ( o != NULL ) 43 { 44 free(o->ch[0]); 45 free(o->ch[1]); 46 delete o; 47 } 48 } 49 50 void inorder( Node * o ) 51 { 52 if ( o ) 53 { 54 inorder(o->ch[0]); 55 printf("%s %.4f\n", o->v, 100.0 * o->cnt / tot); 56 inorder(o->ch[1]); 57 } 58 } 59 60 Node * root; 61 char str[N]; 62 63 int main () 64 { 65 root = NULL; 66 tot = 0; 67 while ( gets(str) != NULL ) 68 { 69 tot++; 70 insert( root, str ); 71 } 72 inorder(root); 73 free(root); 74 return 0; 75 }
时间: 2024-10-15 16:56:02