哈夫曼树是什么就不解释了,直接贴代码了。
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode
{
int data;
struct TreeNode *LeftChild;
struct TreeNode *RightChild;
//自定义排序规则
bool operator < (const struct TreeNode &b) const
{
return data > b.data;
}
};
int main()
{
int n;
cin >> n;
priority_queue<TreeNode *>que;
for (int i=0; i<n; i++)
{
int x;
cin >> x;
struct TreeNode *Temp = new TreeNode;
Temp->data = x;
que.push(Temp);
}
struct TreeNode *root;
while (!que.empty())
{
struct TreeNode *p = new TreeNode;
p->LeftChild = que.top();
que.pop();
p->RightChild = que.top();
que.pop();
p->data+=p->LeftChild->data + p->RightChild->data;
root = p;
if (!que.empty())
que.push(p);
}
cout << root->data << endl;
return 0;
}