writer:pprp

哈夫曼树是最优二叉树,带权值的二叉树

题意大概:

给n个数,经过计算得到最优二叉树的最小权值;

代码如下:(单个测试用例)

#include <iostream>
#include <queue>
#include <vector>
//最优二叉树:带权值的二叉树
using namespace std;

priority_queue<int ,vector<int> ,greater<int> >p;

//一组数据
int main()
{
    int n;
    int tmp;
    int x,y;
    cin >> n;
    for(int i = 0 ; i < n ; i++)
    {
        cin >> tmp;
        x = tmp;
        p.push(x);

    }
    int sum = 0;

    cout << p.top() << endl;
    while(!p.empty())
    {
      
        x = p.top(); //取出一个最小值
        p.pop();
        if(n == 1)
            break;
        y = p.top();  //取出一个最小值
        p.pop();
        n--;
        x += y;
        sum += x;
        
        p.push(x);
    }

    cout << sum << endl;
    return 0;
}

 

相关文章:

  • 2021-07-03
  • 2021-07-20
猜你喜欢
  • 2021-12-09
  • 2021-04-06
  • 2021-05-21
  • 2021-05-27
  • 2021-05-10
  • 2021-05-28
  • 2021-12-25
相关资源
相似解决方案