http://blog.csdn.net/houszchina/article/details/72784261
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <math.h>
using namespace std;
struct Hcode
{
char ch;
deque<int> huffcode;
};
struct Hnode
{
int weight;
Hnode *parent;
Hnode *lchild;
Hnode *rchild;
};
struct cmp
{
bool operator()(const Hnode * a,const Hnode * b)
{
return a->weight > b->weight;
}
};
void huff_init(priority_queue<Hnode*,vector<Hnode*>,cmp> &pq,int n)
{
for(int i=0;i<n-1;i++)
{
if(pq.size()==1)
break;
Hnode *pnode=new Hnode;
Hnode *lnode=pq.top();
pq.pop();
Hnode *rnode=pq.top();
pq.pop();
pnode->parent=NULL;
pnode->weight=lnode->weight+rnode->weight;
pnode->lchild=lnode;
pnode->rchild=rnode;
lnode->parent=pnode;
rnode->parent=pnode;
pq.push(pnode);
}
}
void huff_code(Hnode *node,Hcode *code,int n)
{
for(int i=0;i<n;i++)
{
Hnode *curnode=&node[i];
while(1)
{
if(curnode->parent==NULL)
break;
else
{
if(curnode->parent->rchild==curnode)
code[i].huffcode.push_front(1);
else
code[i].huffcode.push_front(0);
}
curnode=curnode->parent;
}
}
}
void huff_print(Hcode *code,int n)
{
for(int i=0;i<n;i++)
{
cout<<code[i].ch<<" 's Huffman code is:";
deque<int>::iterator it;
for(it=code[i].huffcode.begin();it!=code[i].huffcode.end();it++)
cout<<*it;
cout<<endl;
}
}
int main()
{
int n;
while(~scanf("%d",&n))
{
Hcode code[1005];
Hnode node[1005];
for(int i=0;i<n;i++)
{
cin>>node[i].weight;
node[i].parent=NULL;
node[i].lchild=NULL;
node[i].rchild=NULL;
}
getchar();
for(int i=0;i<n;i++)
cin>>code[i].ch;
priority_queue<Hnode*,vector<Hnode*>,cmp> pq;
for(int i=0;i<n;i++)
pq.push(node+i);
huff_init(pq,n);
huff_code(node,code,n);
huff_print(code,n);
}
return 0;
}