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

字典树

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值