- 题目描述:
哈夫曼树,第一行输入一个数n,表示叶结点的个数。需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出所有结点的值与权值的乘积之和。
- 输入:
输入有多组数据。
每组第一行输入一个数n,接着输入n个叶节点(叶节点权值不超过100,2<=n<=1000)。
- 输出:
输出权值。
- 样例输入:
5
1 2 2 5 9
- 样例输出:
37 权值为层数,从0开始,一开始本来想用数组来构造哈夫曼树,代码如下:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm> #define MAX 1009
#define HMAX 2009 struct Haff
{
int level;
int key;
bool isLeaf;
};
Haff haff[MAX]; int cmp(const void* a, const void *b) {
Haff at = *(Haff *)a;
Haff bt = *(Haff *)b;
if(at.key != bt.key)
return at.key - bt.key;
else if(at.isLeaf == bt.isLeaf) {
return ;
}
else {
if(at.isLeaf == true) {
return ;
}
else {
return -;
}
}
} int max(int a, int b) {
return a > b ? a: b;
}
int main(int argc, char const *argv[])
{
int n;
while(scanf("%d",&n) != EOF) {
for(int i = ; i < n; i++) {
scanf("%d",&haff[i].key);
haff[i].level = ;
haff[i].isLeaf = true;
}
int ptr = ;
int count = n;
int cen;
int N = * n - ;
while(ptr < N - ) {
qsort(&haff[ptr],count-ptr, sizeof(Haff), cmp); int pj = ptr + ;
cen = max(haff[ptr].level, haff[pj].level);
haff[ptr].level = cen;
haff[pj].level = cen;
haff[count].key = haff[ptr].key + haff[pj].key;
haff[count].level = cen + ;
haff[count].isLeaf = false;
count++;
ptr = ptr + ;
} int sum = ;
cen = haff[N-].level; /*for(int i = 0; i < count; i++) {
printf("%d %d\t",haff[i].key, haff[i].level);
}
printf("\n");*/
for(int i = ; i < count; i++) {
if(haff[i].isLeaf == true) {
sum = sum + (cen - haff[i].level) * haff[i].key;
}
}
printf("%d\n",sum);
}
return ;
}但这样做,level的值会出现错误。
后来发现去计算答案根本不需要建树,代码如下:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm> #define MAX 1009 int haff[MAX]; int cmp(const void* a, const void *b) {
int at = *(int *)a;
int bt = *(int *)b;
return at - bt; } int max(int a, int b) {
return a > b ? a: b;
}
int main(int argc, char const *argv[])
{
int n;
while(scanf("%d",&n) != EOF) {
for(int i = ; i < n; i++) {
scanf("%d",&haff[i]);
}
int ptr = ;
int count = n;
int N = * n - ;
int sum = ;
while(ptr < N - ) {
qsort(&haff[ptr],count-ptr, sizeof(int), cmp); int pj = ptr + ;
haff[count] = haff[ptr] + haff[pj];
sum = sum + haff[count];
count++;
ptr = ptr + ;
}
printf("%d\n",sum);
}
return ;
}