算法分析课。。。
#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
*/