这道题的思路和求哈夫曼树的权值是一样的,哈夫曼树题目链接:https://www.nowcoder.com/practice/162753046d5f47c7aac01a5b2fcda155?tpId=67&tqId=29635&tPage=1&ru=/kaoyan/retest/1005&qru=/ta/bupt-kaoyan/question-ranking
#include <bits/stdc++.h>
#include <iostream>
#include <queue>
using namespace std;
int main() {
int n;
while(cin >> n){
if(n == 0) break;
priority_queue<int, vector<int>, greater<int>> datas;
while(n--){
int x;
cin >> x;
datas.push(x);
}
int ans = 0;
while(datas.size() > 1){
int a = datas.top();
datas.pop();
int b = datas.top();
datas.pop();
ans += a + b;
datas.push(a + b);
}
cout << ans << '\n';
}
}

京公网安备 11010502036488号