考研机试真题--搬水果(吉林大学)--哈夫曼树

题目链接:
https://www.nowcoder.com/practice/e4c775b0f3ee42a4bb72c26d2e1eef8a?tpId=40&tqId=21510&tPage=1&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

代码:

#include 
#include 
#include 
#include 
using namespace std;
priority_queue<int, vector<int>, greater<int>> q;

void clear(){
    while(!q.empty()){
        q.pop();
    }
}

int main(){
//    freopen("a.txt", "r", stdin);
    int n, x;
    while(cin >> n){
        clear();
        for(int i = 0; i < n; ++i){
            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;
}

你可能感兴趣的:(算法,树,机试)