POJ2418 二叉排序树 && 字典树写法

来源:互联网 发布:ubuntu安装拼音输入法 编辑:程序博客网 时间:2024/05/29 10:21

转载http://blog.csdn.net/cnyali/article/details/51376310

字典树

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include<stdio.h>  
  2. #include<string.h>  
  3. #include<stdlib.h>  
  4. struct node{  
  5.     int count;    
  6.     struct node *next[100];  
  7.     node(){  
  8.         count=0;  
  9.         memset(next,0,sizeof(next));  
  10.     }  
  11. };  
  12. node *h,*p,*q;   
  13. int ans;  
  14. char sx[40];  
  15. void insert(char *s){  
  16.     int i,j,k;  
  17.     p=h;  
  18.     k=strlen(s);  
  19.     for(i=0;i<k;i++){  
  20.         if(p->next[s[i]-' ']==NULL){  
  21.             q=new node;  
  22.             p->next[s[i]-' ']=q;  
  23.         }  
  24.         p=p->next[s[i]-' '];       
  25.     }  
  26.     if(p->count==0)p->count=1;  
  27.     else p->count++;   
  28.       
  29. }  
  30. void out(node *t,int x){      
  31.     if(t==0)return;  
  32.     for(int i=0;i<=95;i++)  
  33.         if(t->next[i]!=0){  
  34.             sx[x]=i+' ';      
  35.             if(t->next[i]->count!=0){  
  36.                 sx[x+1]='\0';  
  37.                 printf("%s %.4f\n",sx,100.0*t->next[i]->count/ans);  
  38.             }  
  39.             out(t->next[i],x+1);  
  40.         }  
  41.     return;  
  42. }  
  43. int main(){  
  44.     char s[40];   
  45.     h=new node;  
  46.     while(gets(s)!=NULL){  
  47.     //if(strcmp(s,"0")==0)break;      
  48.     insert(s);ans++;  
  49.     };  
  50.     out(h,0);  
  51.     return 0;  
  52. }  

二叉排序树

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include<cstdio>  
  2. #include<algorithm>  
  3. #include<cstring>  
  4. #include<string>  
  5. using namespace std;  
  6. struct node{  
  7.     char ch[100];  
  8.     int l,r;  
  9.     int cnt;  
  10. }a[10001];  
  11. int len,sum=0;  
  12. void insert(int h,char *s){  
  13.     int cmp=strcmp(a[h].ch,s);  
  14.     if (cmp==0){a[h].cnt++;return ;}  
  15.     if(cmp<0){  
  16.         if(a[h].r==0){  
  17.             strcpy(a[++len].ch,s);  
  18.             a[len].cnt=1;  
  19.             a[h].r=len;  
  20.         }else insert(a[h].r,s);  
  21.     }else{  
  22.         if(a[h].l==0){  
  23.             strcpy(a[++len].ch,s);  
  24.             a[len].cnt=1;  
  25.             a[h].l=len;  
  26.         }else insert(a[h].l,s);  
  27.     }         
  28. }  
  29. void out(int h){  
  30.     if(a[h].l!=0)out(a[h].l);  
  31.     printf("%s %.4f\n",a[h].ch,100.0*a[h].cnt/sum);  
  32.     if(a[h].r!=0)out(a[h].r);  
  33. }  
  34. int main(){  
  35.     int i,j,k,m,n;  
  36.     char s[100];  
  37.    
  38.     gets(a[1].ch);a[1].cnt=1;len=1;sum=1;  
  39.     while(gets(s)!=NULL){  
  40.        insert(1,s);sum++;  
  41.     }  
  42.     out(1);  
  43.     return 0;  
  44. }  
0 0
原创粉丝点击