天天看點

BUPT-哈夫曼樹

題目連結

​​https://www.nowcoder.com/practice/162753046d5f47c7aac01a5b2fcda155?tpId=67&tqId=29635&tPage=1&ru=/kaoyan/retest/1005&qru=/ta/bupt-kaoyan/question-ranking​​

題目描述

哈夫曼樹,第一行輸入一個數n,表示葉結點的個數。需要用這些葉結點生成哈夫曼樹,根據哈夫曼樹的概念,這些結點有權值,即weight,題目需要輸出所有結點的值與權值的乘積之和。

輸入描述:

輸入有多組資料。
每組第一行輸入一個數n,接着輸入n個葉節點(葉節點權值不超過100,2<=n<=1000)。      

輸出描述:

輸出權值。      

示例1

輸入

複制

5  
1 2 2 5 9      

輸出

複制

37      
#include <iostream>
#include <queue>
using namespace std;
priority_queue<int, vector<int>, greater<int>> q;
int main(){
  int n;
  while(cin >> n){
    while(q.empty() == false){
      q.pop();
    }
    for(int i = 0; i < n; i++){
      int x;
      cin >> x;
      q.push(x);
    }
    int ans = 0;
    while(q.size() > 1){
      int a = q.top();
      q.pop();
      int b = q.top();
      q.pop();
      ans += a + b;
      q.push(a + b);
    }
    cout << ans << endl;
  }
  return 0;
}