(困了不想写了,直接上代码吧)有时间再来完善
【STL优先队列的哈夫曼树】
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main()
{
priority_queue<int,vector<int>,greater<int>>heap;
int n;
scanf("%d", &n);
while (n -- )
{
int x;
cin>>x;
heap.push(x);
}
int res=0;
while(heap.size()>1)
{
int a=heap.top();heap.pop();
int b=heap.top();heap.pop();
res+=a+b;
heap.push(a+b);
}
cout<<res;
return 0;
}
【手动模拟小根堆实现哈夫曼】
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 100010;
int h[N], cnt;
void down(int x)
{
int t = x;
if (2 * x <= cnt && h[t] > h[2 * x])t = 2 * x;
if (2 * x + 1 <= cnt && h[t] > h[2 * x + 1])t = 2 * x + 1;
if (t != x)
{
swap(h[t], h[x]);
down(t);
}
}
void up(int x)
{
while (x / 2 && h[x] < h[x / 2])
{
swap(h[x],h[x / 2]);
x >>= 1;
}
}
void hpush(int x)
{
cnt++;
h[cnt] = x;
up(x);
}
void hpop()
{
h[1] = h[cnt];
cnt--;
down(1);
}
int htop()
{
return h[1];
}
//全手动模拟哈夫曼树
int main()
{
int n;
cin >> n;
while (n--)
{
int x;
cin >> x;
hpush(x);
}
int res = 0;
while (cnt > 1)
{
int a = htop(); hpop();
int b = htop(); hpop();
res += a + b;
hpush(a + b);
}
cout << res << endl;
return 0;
}