- 2. 带权路径长度
【问题描述】 输入一串正整数,正整数之间用空格键分开,请建立一棵哈夫曼树,以输入的数字作为叶子节点,求这棵哈夫曼树的带权路径长度。
【输入形式】 首先输入正整数的个数n,然后是对应的n个正整数,正整数个数不超过10个
【输出形式】 输出创建的哈夫曼树的带权路径总长度
【样例输入】 5 4 5 6 7 8
【样例输出】 69
#include <iostream>
using namespace std;
typedef struct node
{
int weight;
int parent, lc, rc;
} huff;
void select(node v[], int n, int &s1, int &s2)
{
for (int i = 0; i < n; i++)
{
if (v[i].parent == 0)
{
s1 = i;
break;
}
}
for (int i = 0; i < n; i++)
{
if (v[i].parent == 0 && v[i].weight < v[s1].weight)
s1 = i;
}
for (int i = 0; i < n; i++)
{
if (v[i].parent == 0 && i != s1)
{
s2 = i;
break;
}
}
for (int i = 0; i < n; i++)
{
if (v[i].parent == 0 && v[i].weight < v[s2].weight && i != s1)
s2 = i;
}
}
void build_huff(int n, huff v[], int len)
{
int s1, s2;
for (int i = n; i < len; i++)
{
select(v, i, s1, s2);
v[s1].parent = i;
v[s2].parent = i;
v[i].lc = s1;
v[i].rc = s2;
v[i].weight = v[s1].weight + v[s2].weight;
}
}
int getlujin(huff v[], int n)
{
int count = 0, s = 0;
for (int i = 0; i < n; i++)
{
count = 0;
int t = i;
while (v[t].parent != 0)
{
t = v[t].parent;
count++;
}
// cout << count << endl;
s += count * v[i].weight;
}
return s;
}
int main()
{
int n;
cin >> n;
huff v[200];
for (int i = 0; i < n; i++)
{
cin >> v[i].weight;
v[i].parent = v[i].lc = v[i].rc = 0;
}
for (int i = n; i < 2 * n - 1; i++)
v[i].parent = v[i].lc = v[i].rc = v[i].weight = 0;
build_huff(n, v, 2 * n - 1);
cout << getlujin(v, n);
}