Given a list of weights w1, w2, ..., wn, we can construct a binary tree with n leaves, where each leaf is marked with one weight. The is called a weighted binary tree. The weight of the tree is w1l1 + w2l2+ ... wnln, where li is the height of the leaf with weight wi.
For a given list of weights, there are many weighted trees with these weights. However, different weighted tree will have different weights. You are asked to write a program to find the mimimum weight among those weighted trees for a given list of weights.
The first line is the number n of test cases.
The next n lines are the test cases. Each test case is a list of weights that are positive numbers separated by spaces followed by the number 0, which signals the end of the weights.
Each line outputs the minimum weight for the test case.
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <set>
using namespace std;
struct huffman{
int sum;
int leftc;
int rightc;
int index;
int high;
friend bool operator<(huffman n1, huffman n2)
{
return n1.sum < n2.sum;
}
};
void mycout(huffman temp[], int index, int height)
{
if (temp[index].leftc == -1 && temp[index].rightc == -1)
{
temp[index].high = height;
return ;
}
else
{
mycout(temp, temp[index].leftc, height + 1);
mycout(temp, temp[index].rightc, height + 1);
}
return ;
}
int main()
{
const int max = 9999009;
int n;
cin >> n;
int num;
while (n --)
{
huffman node[1009];
int j = 0;
multiset<huffman> myset;
while (1)
{
cin >> num;
if (num == 0) break;
node[j].sum = num;
node[j].leftc = -1;
node[j].rightc = -1;
node[j].index = j;
myset.insert(node[j]);
++ j;
}
int allcot = j;
while (myset.size() > 1)
{
huffman temp1, temp2;
multiset<huffman>::iterator it = myset.begin();
temp1 = (*it);
myset.erase(it);
it = myset.begin();
temp2 = *it;
myset.erase(it);
node[j].sum = temp1.sum + temp2.sum;
node[j].leftc = temp1.index;
node[j].rightc = temp2.index;
node[j].index = j;
myset.insert(node[j]);
++ j;
}
mycout(node, j - 1, 0);
int number = 0;
for (int i = 0; i < allcot; ++ i)
{
//cout << node[i].sum << " " << node[i].high << endl;
number += node[i].sum * node[i].high;
}
cout << number << endl;
}
}