poj2418

题目大意:对给定的一些树名进行字典排序并输出所占的比例。

思路不难就是对给定的数进行字典排序,可是如何存储和如何进行排序是解决问题的关键了,这里我们用到一种叫做二叉搜索树的数据结构。

#include <iostream>
#include <string>
using namespace std;
struct BiNode
{
	char Name[50];
	BiNode *lchild,*rchild;
	int count;
};
class BiSortTree
{
public:
	BiSortTree(){};
	void Creat();
	~BiSortTree(){}
	void inOrderPrint(BiNode *root);
	void InsertBST(BiNode *root, char *s);
	BiNode *SearchBST(BiNode *root, char *name);
	BiNode *GetRoot(){return root;}
private:
	BiNode *root;
	int sum;
};
void BiSortTree::inOrderPrint(BiNode *root)
{
	double person;
	if(root->lchild) inOrderPrint(root->lchild);
	cout<<root->Name<<" ";
	person = (double)(root->count)/(double)(sum);
	person *= 100;
	printf("%.4lf\n",person);
	if(root->rchild) inOrderPrint(root->rchild);
}
void BiSortTree::Creat()
{
	char Name[50];
	sum=1;
	gets(Name);
	root = new BiNode;
	strcpy(root->Name, Name);
	root->count = 1;
	root->lchild = NULL;
	root->rchild = NULL;
	while(gets(Name))
	{
		if(Name[0] == '\0') break;
		InsertBST(root,Name);
		sum++;
	}
}
void BiSortTree::InsertBST(BiNode *root,char *s)
{
	int judge = strcmp(s,root->Name);
	if(judge == 0) root->count++;
	else if(judge < 0)
	{
		if(root->lchild) InsertBST(root->lchild, s);
		else
		{
			root->lchild = new BiNode;
			root->lchild->lchild = root->lchild->rchild = NULL;
			root->lchild->count = 1;
			strcpy(root->lchild->Name, s);
		}
	}
	else 
	{
		if(root->rchild) InsertBST(root->rchild, s);
		else 
		{
			root->rchild = new BiNode;
			root->rchild->lchild = root->rchild->rchild = NULL;
			root->rchild->count = 1;
			strcpy(root->rchild->Name, s);
		}
	}
}
int main()
{
	BiSortTree BiTree;
	BiTree.Creat();
	BiTree.inOrderPrint(BiTree.GetRoot());
	return 0;
}

 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值