求哈夫曼树的带权路径长度(WPL)
合并石子做法
例题
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
#include<vector>
using namespace std;
typedef long long LL;
LL res = 0;
int n;
int main()
{
cin >> n;
priority_queue<int,vector<int>,greater<int>> heap;
for(int i = 0; i < n; i++)
{
int x;
cin >> x;
heap.push(x);
}
while(heap.size() > 1)
{
int x = heap.top();heap.pop();
int y = heap.top();heap.pop();
res += x + y;
heap.push(x + y);
}
cout << res << endl;
return 0;
}
建树,然后求WPL
例题
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
#include<vector>
#define x first
#define y second
using namespace std;
typedef pair<int,int> PII;
const int N = 1010, M = N * 2;
int h[M],ne[M],e[M],idx;
int a[M],p[M],d[M];
int n;
int add(int a,int b)
{
e[idx] = b,ne[idx] = h[a],h[a] = idx++;
}
void bfs(int root)
{
memset(d,-1,sizeof d);
queue<int> q;
q.push(root);
d[root] = 0;
while(q.size())
{
int t = q.front(); q.pop();
for(int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if(d[j] == -1)
{
d[j] = d[t] + 1;
q.push(j);
}
}
}
}
int main()
{
cin >> n;
memset(h,-1,sizeof h);
int cnt = n;
priority_queue<PII,vector<PII>,greater<PII>> heap;
for(int i = 1; i <= n; i++)
{
int x;
cin >> x;
heap.push({x,i});
}
while(heap.size() > 1)
{
auto t1 = heap.top();heap.pop();
auto t2 = heap.top();heap.pop();
a[t1.y] = t1.x;
a[t2.y] = t2.x;
p[t1.y] = ++cnt;
p[t2.y] = cnt;
add(cnt,t1.y);
add(cnt,t2.y);
heap.push({t1.x+t2.x,cnt});
}
for(int i = 1; i <= cnt; i++)
if(!p[i])
{
bfs(i);
break;
}
long long res = 0;
for(int i = 1; i <= n; i++) res += 1ll * a[i] * d[i];
cout << res << endl;
return 0;
}