输入格式如下
6
abcdef
6 1 5 4 2 4
代码如下:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
typedef struct
{
char data;
int weight;
int lc,rc,pa;
} PN;
int n;
stack<char>que;
char a[1000];
PN ha[1000];
void Select(int i,int &i1,int &i2)
{
int min1=100000,min2=100000;
for(int j=0; j<i; j++)
{
if(ha[j].pa==-1)
{
if(ha[j].weight<min1)
{
min2=min1;
i2=i1;
min1=ha[j].weight;
i1=j;
}
else if(ha[j].weight<min2)
{
min2=ha[j].weight;
i2=j;
}
}
}
}
void creathafuman()
{
int i,j,k;
for(i=0; i<2*n-1; i++)
{
ha[i].pa=-1;
ha[i].lc=-1;
ha[i].rc=-1;
}
for(i=n; i<2*n-1; i++)
{
int i1,i2;
Select(i,i1,i2);
ha[i].weight=ha[i1].weight+ha[i2].weight;
ha[i1].pa=i;
ha[i2].pa=i;
ha[i].lc=i1;
ha[i].rc=i2;
}
}
void print()
{
for(int i=0;i<n;i++)
{
int k=i;
while(ha[k].pa!=-1)
{
int j=ha[k].pa;
if(ha[j].lc==k)
que.push('0');
else
que.push('1');
k=j;
}
printf("%c: ",a[i]);
while(!que.empty())
{
char t=que.top();
que.pop();
cout<<t;
}
cout<<endl;
}
}
int main()
{
int i;
scanf("%d",&n);
scanf("%s",a);
for(i=0; i<n; i++)
{
scanf("%d",&ha[i].weight);
}
creathafuman();
printf("哈夫曼树的解码结果如下:\n");
print();
}