#include<stdio.h>
#include<stdlib.h>
typedef struct {
int weight, parent, lchild, rchild;
}HuffNode,*HuffmanTree;
int select(HuffmanTree H, int n, int& s1, int& s2) {
for (int i = 1; i <= n; i++) {
if (H[i].parent == 0) {
s1 = i;
break;
}
}
for (int i = 1; i <= n; i++) {
if (H[i].weight < H[s1].weight && H[i].parent == 0) {
s1 = i;
}
}
for (int i = 1; i <= n; i++) {
if (H[i].parent == 0 && i != s1) {
s2 = i;
break;
}
}
for (int i = 1; i <= n; i++) {
if (H[i].weight < H[s2].weight && H[i].parent == 0 && i != s1) {
s2 = i;
}
}
return 1;
}
int CreateHuffmanTree(HuffmanTree &H,int n) {
int m = 2 * n - 1;
H = (HuffmanTree)malloc((m+1)*sizeof(HuffNode));
for (int i = 1; i <= m;i++) {
H[i].parent = 0;
H[i].rchild = 0;
H[i].lchild = 0;
}
for (int i = 1; i <= n; i++) {
scanf_s("%d", &H[i].weight);
}
int s1, s2;
for (int j = n+1; j <=m ;j++) {
select(H, j-1, s1, s2);
H[s1].parent = j;
H[s2].parent = j;
H[j].lchild = s1;
H[j].rchild = s2;
H[j].weight = H[s1].weight + H[s2].weight;
}
return 1;
}
int main() {
HuffmanTree L;
int n;
scanf_s("%d", &n);
CreateHuffmanTree(L, n);
printf("\n");
for (int j = 1; j <= 2 * n - 1; j++) {
printf("%d %d %d %d\n", L[j].weight,L[j].parent,L[j].lchild,L[j].rchild);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef struct BNode
{
int weigth;
int parent, lchild, rchild;
}HTNode, * HuffmanTree;
typedef char** HuffmanCode;
Status Init(HuffmanTree& L, int n)
{
int m = 2 * n - 1;
L = (HTNode*)malloc((m + 1) * sizeof(HTNode));
for (int i = 1; i <= n; i++)
{
scanf("%d", &L[i].weigth);
L[i].parent = 0;
L[i].lchild = 0;
L[i].rchild = 0;
}
for (int j = n + 1; j <= 2 * n - 1; j++)
{
L[j].weigth = 0;
L[j].parent = 0;
L[j].lchild = 0;
L[j].rchild = 0;
}
return OK;
}
Status select(HuffmanTree &L, int n, int& s1, int& s2)
{
int m1, m2;
for(int i=1;i<=n;i++)
{
if(L[i].parent==0)
{
s1=i;
break;
}}
for ( i = 1; i <= n; i++)
{
if (L[i].weigth < L[s1].weigth && L[i].parent == 0)
{
s1 = i;
}
}
for( i=1;i<=n;i++)
{
if(L[i].parent==0&&i!=s1)
{
s2=i;
break;
}}
for (i = 1; i <= n; i++)
{
if (L[i].weigth < L[s2].weigth && i != s1 && L[i].parent == 0)
{
s2 = i;
}
}
return OK;
}
void Huffman(HuffmanTree L, int n)
{
if (n <= 1) return;
int s1, s2;
for (int k = n + 1; k <= 2 * n - 1; k++)
{
select(L, k - 1, s1, s2);
L[s1].parent = k;
L[s2].parent = k;
L[k].lchild = s1;
L[k].rchild = s2;
L[k].weigth = L[s1].weigth + L[s2].weigth;
}
}
int main()
{
HuffmanTree L;
int n;
int m1, m2, e1, e2;
scanf("%d", &n);
Init(L, n);
Huffman(L, n);
printf("\n");
for (int j = 1; j <= 2 * n - 1; j++)
printf("%d\n", L[j].weigth);
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ebb0e74eb82753b0c76afa17b5c4a93d.png#pic_center)