#include
#include
#include
using namespace std;
struct node
{
int weight;
int lchild,rchild,parent;
};
void select2(vector &v,int n,int& s1,int& s2)
{
s1=s2=0;
for(int i=1;i {
if(v[i].weight&&!v[i].parent)
{
if(v[i].weight {
s2=s1;s1=i;
}else if(v[i].weight {
s2=i;
}
}
}
return;
};
void huffman_coding(int weights[],int n)
{
int i,s1=0,s2=0;
vector tree(2*n);
cout< vector code(n);
tree[0].weight=INT_MAX;
for(i=1;i {
tree[i].weight=weights[i-1];
tree[i].lchild=tree[i].parent=tree[i].rchild=0;
}
for(i=n+1;i<2*n;i++)
{
select2(tree,i-1,s1,s2);
tree[i].weight=tree[s1].weight+tree[s2].weight;
tree[i].parent=0;tree[i].lchild=s1;tree[i].rchild=s2;
tree[s1].parent=tree[s2].parent=i;
}
for(i=1;i {
int p=tree[i].parent;
while(p)
{
code[i-1]+=(i==tree[p].lchild)?'0':'l';
p=tree[p].parent;
}
}
copy(code.begin(),code.end(),ostream_iterator(cout,"\n"));
}
int main()
{
int weight[]={1,2,3,4,5,6,7,8,9};
huffman_coding(weight,sizeof(weight)/sizeof(int));
}
阅读(801) | 评论(0) | 转发(0) |