poj 2418 Hardwood Species 二叉排序树



这道题看例子就能明白是什么意思。唯一坑人的地方就是要纠结如何判断输入结束的标志。看了一下别人的代码,无语了。这道题可以用两道题来写。一种是map,一种是创建排序二叉树。

map写法:

#include<iostream>
#include<map>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
map<string,int> mapTree;
int main() {
	double ans=0;
	string s;
	while(getline(cin,s)) {
		//if(s=="end") break;
		mapTree[s]++;
		ans++;
	}
	map<string,int>::iterator ite;
	for(ite=mapTree.begin(); ite!=mapTree.end();ite++) {
		cout<<ite->first;
		printf(" %.4f\n",ite->second *100.0/ans);
	}
	return 0;
}

二叉排序树写法:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
typedef struct node{
	char s[35];
	struct node *rc,*lc;
	int num;
}nod;
nod *root;
double ans=0;
void insert(char a[]) {
	nod *p=root,*q;
	if(p==NULL) {
		root=(nod *)malloc(sizeof(nod));
		strcpy(root->s,a);
		root->num=1;
		root->lc=NULL;
		root->rc=NULL;
		return ;
	}
	int flag=0;
	while(p) {
		if(strcmp(p->s,a)==0) {
			p->num++;
			flag=1;
			return ;
		}
		q=p;
		p=strcmp(p->s,a)>0 ? p->lc:p->rc;
	}
	if(flag==0) {
		nod *temp=(nod *)malloc(sizeof(nod));
		strcpy(temp->s,a);
		temp->rc=NULL;
		temp->lc=NULL;
		temp->num=1;
		if(strcmp(q->s,a)>0)  q->lc=temp;
		else q->rc=temp;
	}
}

void print(nod *p) {
	if(p!=NULL) {
		print(p->lc);
		printf("%s %.4f\n",p->s,p->num*100.0/ans);
		print(p->rc);
	}
}

int main() {
	char a[35];
	root=NULL;
	while(gets(a) &&strcmp(a,"end")) {
		insert(a);
		ans++;
	}
	nod *p=root;
	print(p);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值