题目:http://codeup.cn/problem.php?id=21142&csrf=bvHcDf5kc87m5weAdrD1yXRXLa23xYvG

可以不用求出树形结构的哈夫曼带权路径,利用了priority_queue,代码比较简介

代码

  1. #include<algorithm>
  2. #include<queue>
  3. #include<iostream>
  4. #include<cstdio>
  5. using namespace std;
  6. typedef long long LL;
  7. priority_queue<LL, vector<LL>, greater<LL> >q;
  8. int main(){
  9. int n;
  10. LL temp, ans = 0;
  11. scanf("%d", &n);
  12. for(int i = 0; i < n; i++){
  13. scanf("%lld", &temp);
  14. q.push(temp);
  15. }
  16. while(q.size() > 1){
  17. LL a = q.top();
  18. q.pop();
  19. LL b = q.top();
  20. q.pop();
  21. q.push(a + b);
  22. ans += a + b;
  23. }
  24. printf("%lld", ans);
  25. return 0;
  26. }