• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
村雨sup
自己选的路,跪着也要走完 XD
博客园    首页    新随笔    联系   管理    订阅  订阅
初涉“优先队列”

大概意思是将最小的两个pop出队列后相加push入队,类似哈夫曼树算法最后求和。

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

struct cmp1{
    bool operator ()(int &a,int &b){
        return a>b;//最小值优先
    }
};

int main()
{
    priority_queue<int,vector<int>,cmp1>que1;//最小值优先

    int n;
    cin >> n;
    int a[n];
    for(int i=0;i < n;i++)
    {
        cin >> a[i];
        que1.push(a[i]);
    }

    int sum = 0;
    while(!que1.empty())
    {
        int x = que1.top();
        que1.pop();
        int y = que1.top();
        que1.pop();
        int hehe = x + y;
        sum += hehe;
        if(!que1.empty())
        {
            que1.push(hehe);
        }
        else break;
    }

    cout << sum << endl;

    return 0;
}

默认是最大值优先度最高,这里对操作符 “<” 进行了重载。

posted on 2018-01-27 20:57  村雨sup  阅读(154)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3