#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
typedef long long ll;
ll n, k, id, ans1, ans2 = LONG_LONG_MIN;
struct huff {
int val;
vector <int> son;
bool used; // 标记此节点是否已经被使用过
huff(): val(0), used(false) {}
};
int nodecnt = 0;
int create(int val) {
node[nodecnt].val = val;
node[nodecnt].son.clear();
node[nodecnt].used = true;
return nodecnt++;
}
int buildtree(const vector<int>& val) {
int n = val.size();
nodecnt = 0;
auto cmp = [](int a, int b) {
return node[a].val > node[b].val;
};
priority_queue <int, vector<int>, decltype(cmp)> q(cmp);
for(int i = 0; i < val.size(); i++) {
int nodeid = create(val[i]);
q.push(nodeid);
}
while((q.size() - 1) % (k - 1) != 0) {
int nodeid = create(0);
q.push(nodeid);
}
while(q.size() > 1) {
int fatherid = create(0);
for(int i = 0; i < k && !q.empty(); i++) {
int sonid = q.top();
q.pop();
node[fatherid].val += node[sonid].val;
node[fatherid].son.push_back(sonid);
}
q.push(fatherid);
}
return q.top();
}
void dfs(int id, int deepth) {
if(node[id].son.empty()) {
ans1 += deepth * node[id].val;
ans2 = max(ans2, 1ll * deepth);
return;
}
for(int i = 0; i < node[id].son.size(); i++)
dfs(node[id].son[i], deepth + 1);
}
int main() {
cin >> n >> k;
vector <int> weight;
for(int i = 1; i <= n; i++) {
int w;
cin >> w;
weight.push_back(w);
}
int root = buildtree(weight);
dfs(root, 0);
cout << ans1 << endl;
cout << ans2;
return 0;
}
RT,我想实际构造出这棵哈夫曼树,然后遍历树求结果,但只能得35分,是哪个地方有问题吗