转载http://blog.youkuaiyun.com/cnyali/article/details/51376310
字典树
- #include<stdio.h>
- #include<string.h>
- #include<stdlib.h>
- struct node{
- int count;
- struct node *next[100];
- node(){
- count=0;
- memset(next,0,sizeof(next));
- }
- };
- node *h,*p,*q;
- int ans;
- char sx[40];
- void insert(char *s){
- int i,j,k;
- p=h;
- k=strlen(s);
- for(i=0;i<k;i++){
- if(p->next[s[i]-' ']==NULL){
- q=new node;
- p->next[s[i]-' ']=q;
- }
- p=p->next[s[i]-' '];
- }
- if(p->count==0)p->count=1;
- else p->count++;
- }
- void out(node *t,int x){
- if(t==0)return;
- for(int i=0;i<=95;i++)
- if(t->next[i]!=0){
- sx[x]=i+' ';
- if(t->next[i]->count!=0){
- sx[x+1]='\0';
- printf("%s %.4f\n",sx,100.0*t->next[i]->count/ans);
- }
- out(t->next[i],x+1);
- }
- return;
- }
- int main(){
- char s[40];
- h=new node;
- while(gets(s)!=NULL){
- //if(strcmp(s,"0")==0)break;
- insert(s);ans++;
- };
- out(h,0);
- return 0;
- }
二叉排序树
- #include<cstdio>
- #include<algorithm>
- #include<cstring>
- #include<string>
- using namespace std;
- struct node{
- char ch[100];
- int l,r;
- int cnt;
- }a[10001];
- int len,sum=0;
- void insert(int h,char *s){
- int cmp=strcmp(a[h].ch,s);
- if (cmp==0){a[h].cnt++;return ;}
- if(cmp<0){
- if(a[h].r==0){
- strcpy(a[++len].ch,s);
- a[len].cnt=1;
- a[h].r=len;
- }else insert(a[h].r,s);
- }else{
- if(a[h].l==0){
- strcpy(a[++len].ch,s);
- a[len].cnt=1;
- a[h].l=len;
- }else insert(a[h].l,s);
- }
- }
- void out(int h){
- if(a[h].l!=0)out(a[h].l);
- printf("%s %.4f\n",a[h].ch,100.0*a[h].cnt/sum);
- if(a[h].r!=0)out(a[h].r);
- }
- int main(){
- int i,j,k,m,n;
- char s[100];
- gets(a[1].ch);a[1].cnt=1;len=1;sum=1;
- while(gets(s)!=NULL){
- insert(1,s);sum++;
- }
- out(1);
- return 0;
- }