求哈夫曼树的带权路径长度(WPL)

求哈夫曼树的带权路径长度(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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值