点击打开链接
///huffman树
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include <memory.h>
#include<string.h>
#include<cstring>
#include<string>
#include<algorithm>
#include<math.h>
#include<queue>
#include<set>
#include<stack>
#include<string>
#include<map>
#define LL long long
#define inf 0x3f3f3f3f
#define maxn 205
#define mod 1e9+7
using namespace std;
struct huffmanNode
{
int leftNode,rightNode,parent;
int value;
} huffmanNodes[maxn*2];
int traverseTree(int idx, int depth)
{
int sum = 0;
int child = 0;
if (huffmanNodes[idx - 1].leftNode) {
sum += traverseTree(huffmanNodes[idx - 1].leftNode, depth + 1);
child++;
}
if (huffmanNodes[idx - 1].rightNode) {
sum += traverseTree(huffmanNodes[idx - 1].rightNode, depth + 1);
child++;
}
if (!child) {
sum = huffmanNodes[idx - 1].value * depth;
}
return sum;
}
int main()
{
int num,t,n;
int result = 0;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
memset(huffmanNodes,0,sizeof(huffmanNodes));
for (int i = 0; i < n; i++) {
scanf("%d",&num);
huffmanNodes[i].value = num;
}
for (int i = n; i < n * 2 - 1; i++) {///这棵树总共有2*n-1个节点。
int min1 = inf, min2 =inf;
int minIdx1 = -1, minIdx2 = -1;
for (int j = 0; j < i; j++) {///扫描节点
if (huffmanNodes[j].parent)continue;
if (huffmanNodes[j].value < min1) {
min2 = min1;
minIdx2 = minIdx1;
min1 = huffmanNodes[j].value;
minIdx1 = j;
} else if (huffmanNodes[j].value < min2) {
min2 = huffmanNodes[j].value;
minIdx2 = j;
}
}
huffmanNodes[minIdx1].parent = i;
huffmanNodes[minIdx2].parent = i;
huffmanNodes[i].value = min1 + min2;
huffmanNodes[i].leftNode = minIdx1 + 1;
huffmanNodes[i].rightNode = minIdx2 + 1;
}
result=0;
for (int i = 0; i <n * 2 - 1; i++) {
if (!huffmanNodes[i].parent) {
result = traverseTree(i + 1,0);
break;
}
}
printf("%d\n",result);
}
return 0;
}