#include<stdio.h>
#include<stdlib.h>
#include<string.h>
const int maxn = 1e5 + 5;
struct node
{
int w, pre, l, r;
};
struct tree
{
int m, root;
struct node *ht;
};
void print_ans(struct tree *p, int n)
{
printf("序號 權值 父母 左 右\n");
for(int i=0;i<2*n-1;i++)
{
printf("%d\t%d\t%d\t%d\t%d\n", i, p->ht[i].w, p->ht[i].pre, p->ht[i].l, p->ht[i].r);
}
}
struct tree *huffman(int n, int *q)
{
int i, j;
int m1, m2, x1, x2;
struct tree *new_node;
new_node = malloc(sizeof(*new_node));
new_node->ht = malloc(sizeof(struct node * [2 *n -1]));
for(i = 0; i<2*n-1; i++)
{
new_node->ht[i].l = new_node->ht[i].r = new_node->ht[i].pre = -1;
if(i < n)
{
new_node->ht[i].w = q[i];
}
else new_node->ht[i].w = -1;
}
printf("初始的狀態:\n");
print_ans(new_node, n);
for(i = 0; i<n-1; i++)
{
m1 = maxn;
m2 = maxn;
x1 = -1;
x2 = -1;
for(j = 0; j<n+i;j++)
{
if(new_node->ht[j].w < m1 && new_node->ht[j].pre == -1)
{
m2 = m1;
x2 = x1;
m1 = new_node->ht[j].w;
x1 = j;
}
else if(new_node->ht[j].w < m2 && new_node->ht[j].pre == -1)
{
m2 = new_node->ht[j].w;
x2 = j;
}
}
// printf("小 = %d, 次小 = %d\n", m1, m2);
new_node->ht[n+i].w = m1 + m2;
new_node->ht[x1].pre = new_node->ht[x2].pre = new_node->ht[n+i].w;
new_node->ht[n+i].l = x1;
new_node->ht[n+i].r = x2;
}
new_node->root = 2 * n - 2;
return new_node;
};
int main()
{
int i;
int n;
int a[maxn];
struct tree *p;
while(1)
{
printf("請輸入結點數:(輸入0結束)\n");
scanf("%d", &n);
if(!n) break;
printf("輸入%d個節點:\n", n);
for(int i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
p = huffman(n, a);
printf("最優排列方法:\n");
print_ans(p, n);
}
return 0;
}