哈夫曼树


算法分析课。。。


#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#include<string> 
using namespace std;
struct Node 
{
	Node *left,*right,*father;
	int val;
	char key;
	Node()
	{
		left=right=father=NULL;
		val=0;
	}
	Node(char kk,int vv)
	{
		left=right=father=NULL;
		val=vv;
		key=kk;	
	}
	friend bool operator<(Node a,Node b)
	{
		return a.val>b.val;
	}
}root;
int n;
char c[100];
char str[110];
int f[100];
priority_queue<Node> q;
void huffMan()
{
	while(q.size()!=1)
	{
		Node *tmp1=new Node();
		*tmp1 = q.top();
		q.pop();
		Node *tmp2=new Node();
		*tmp2 = q.top();
		q.pop();
		Node *p=new Node();
		p->val=tmp1->val+tmp2->val;
		p->left=tmp1;
		p->right=tmp2;
		q.push(*p);
	}
	root=q.top();
}
void dfs(Node *x,int cnt)
{
	if(x->left==NULL||x->right==NULL)
	{
		str[cnt]='\0';
		cout<<x->key<<" "<<str<<endl;
		return;
	}
	str[cnt]='0';
	dfs(x->left,cnt+1);
	str[cnt]='1';	 
	dfs(x->right,cnt+1);
}
int main()
{
	cout<<"ÊäÈë×Ö·û¼¯´óС"<<endl;
	cin>>n;
	cout<<"ÊäÈë×Ö·û¼¯°üº¬µÄ×Ö·û¼°¸Ã×Ö·ûµÄƵÂÊ"<<endl;
	for(int i=0;i<n;i++) 
	{
		cin>>c[i]>>f[i];
		q.push(Node(c[i],f[i]));
	}
	huffMan();
	cout<<"Êä³ö¹þ·òÂü±àÂë"<<endl;
	dfs(&root,0);
	return 0;
}
/*
6
f 5
e 9
c 12
b 13
d 16
a 45
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值