#include<cstdio>
#include<iostream>
using namespace std;
#include<cstring>
#include<limits.h>
#include<algorithm>
const int maxn = 1010;
typedef struct{
int weight;
char s;
int parent,lchild,rchild;
}HTNode,HuffmanTree[maxn];
void twoSelect(HuffmanTree HT,int n,int &s1,int &s2)
{
int max1 = INT32_MAX,max2 = max1;
for (int i = 1; i <= n; ++i)
{
if(HT[i].weight < max1 && HT[i].parent == 0){
max2 = max1;
s2 = s1;
max1 = HT[i].weight;
s1 = i;
}else if(HT[i].weight < max2 && HT[i].parent == 0){
max2 = HT[i].weight;
s2 = i;
}
}
if( s1 > s2) swap(s1,s2);
// printf("%d %d\n",max1,max2);
// printf("\n");
}
void createHuffmanTree(HuffmanTree HT,int n,int *weight)
{
int s1,s2;
for (int i = 1; i <= n; ++i,++weight)
{
HT[i].weight = *weight;
HT[i].parent = HT[i].lchild = HT[i].rchild = 0;
}
for (int i = n+1; i <= 2 * n - 1; ++i)
{
twoSelect(HT,i-1,s1,s2);
HT[s1].parent = HT[s2].parent = i;
HT[i].lchild = s1;
HT[i].rchild = s2;
HT[i].parent = 0;
HT[i].weight = HT[s1].weight + HT[s2].weight;
}
}
char** HuffmanTreeCoding(HuffmanTree HT,int n)
{
if(n <= 1) return NULL;
int m = 2 * n - 1;
// char *cd = (char *)malloc(n * sizeof(char)) ;
// char** hc = (char **)malloc((n+1) * sizeof(char *));
char *cd = new char[n];
char **hc = new char*[n+1];
int start,p,now;
cd[n-1] = '\0';
for (int i = 1; i <= n; ++i)
{
start = n - 1;
p = HT[i].parent;
now = i;
while(p != 0){
--start;
if(HT[p].lchild == now){
cd[start] = '0';
}else{
cd[start] = '1';
}
now = p;
p = HT[p].parent;
}
//hc[i] = (char *)malloc( (n - start) * sizeof(char));
hc[i] = new char[n-start];
strcpy(hc[i],&cd[start]);
}
delete[] cd;
return hc;
}
int weight[maxn];
int main()
{
int n;
while(scanf("%d",&n)!=EOF){
HuffmanTree HT;
for (int i = 0; i < n; ++i)
{
scanf("%d",&weight[i]);
}
createHuffmanTree(HT,n,weight);
char ** HC;
HC = HuffmanTreeCoding(HT,n);
for (int i = 1; i <= n; ++i)
{
cout << HC[i] << endl;
}
delete(HC);
}
return 0;
}
哈夫曼树代码
最新推荐文章于 2024-04-20 11:37:23 发布