NOI2015荷马史诗

· · 题解

题目大意

给出 n 个单词出现的频次,还有该哈夫曼树支持的叉数,求出带权值的哈夫曼编码是多少,并且求出最大深度

思路描述

对于第一个问题,只要在枚举的时候枚举 k 个就可以了. 对于第二个问题,我们可以把权值放在优先队列中的时候附加一个深度,更新的时候去最大值就可以了

CODE

#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;
#define int long long
int n,k;
const int N = 1e5 + 10;
int s[N];
int w[N];
priority_queue <pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> q;

signed main()
{
    cin >> n >> k;
    for(int i = 1;i <= n;i ++)
    {
        cin >> w[i];
        q.push({w[i],1});
    }
    int sum = 0;
    while((q.size() - 1) %(k - 1) != 0) q.push({0,1});

    while(q.size() >= k)
    {
        int w = 0;
        int ans = -1;
        for(int i = 1;i <= k;i ++)
        {
            pair<int,int> t = q.top();
            q.pop();
            ans = max(ans,t.second);
            w += t.first;
        }

        sum += w;
        q.push({w,ans + 1});
    }

    cout << sum << endl;
    cout << q.top().second- 1 << endl;

    return 0;
}