[Algorithm Fundamentals] AcWing 148. Merge Fruits (Huffman Tree | Priority Queue | Small Root Heap)

insert image description here


Topic description

topic link

ideas

insert image description here

The small root heap of the priority queue needs to be used to ensure that the smallest heap is merged each time, and it supports deletion and insertion exchange operations, so that the value on the left side of each time is the smallest.

C++ code

#include <bits/stdc++.h>
using namespace std;

int main () {
    
    
    int n;
    cin >> n;
    priority_queue<int, vector<int>, greater<int>> heap;
    while (n --) {
    
    
        int x;
        cin >> x;
        heap.push(x);
    }
    int res = 0;
    while (heap.size() > 1) {
    
    
        int x = heap.top();
        heap.pop();
        int y = heap.top();
        heap.pop();
        res += x + y;//合并
        heap.push(x + y);
    }
    cout << res << endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_49486457/article/details/124005631