Huffman Tree-Merged Fruit

Original title link

Parsing

This problem is a typical Huffman tree problem.
For any structure, it can be transformed into a tree. This problem is equivalent to finding the minimum weight of the follow node.
Therefore, this problem can be solved by the Huffman tree. The smaller the point is, the farther away from the root of the tree, the better, and the point with the higher the weight is closer to the root of the tree, the better.
Therefore, a small root pile can be used to achieve this process.

Code

#include <bits/stdc++.h>
using namespace std;
int n;
priority_queue<int,vector<int>,greater<int> >vis;
int main()
{
    
    
    scanf("%d",&n);
    while(n--)
    {
    
    
        int x;
        scanf("%d",&x);
        vis.push(x);
    }
    int res=0;
    while(vis.size()>1)
    {
    
    
        int a=vis.top();
        vis.pop();
        int b=vis.top();
        vis.pop();
        res+=(a+b);
        vis.push(a+b);
    }
    cout<<res<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_46126537/article/details/113103241