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

 

 

你可能感兴趣的:(数据结构)