题目:谈判(蓝桥OJ 545)

题目描述:

解题思路:

        本题采用贪心的思想,与蓝桥的合并果子题思路一样。可以使用优先对列,输入进去后自动排序。将两个最小的合并再放入对列中,并将值加入到ans,最终结果即ans。如下图:x+y为4,9,18;ans为4+9+18=31。

 

题解:

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

using ll = long long ;//元素值可能超过ll。后面的x,y,ans都需要ll
priority_queue<ll, vector<ll>, greater<ll>> pp;//优先队列从小到大写法

int main()
{
  int n; cin >> n;
  for(int i = 1; i <= n; i++)
  {
    int t;cin >> t;
    pp.push(t);
  }


  ll ans = 0;
  while(pp.size() > 1)//可以使用while(size>1),也可以使用for(比较次数)
  {
    ll x,y;
    x = pp.top();pp.pop();
    y = pp.top();pp.pop();

    ans += x + y;
    pp.push(x + y);//注意:是x+y不是ans。ans是每个最小值之和的总和
  }

  cout << ans;
  return 0;
}

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2023-12-07 10:36:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-07 10:36:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-07 10:36:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-07 10:36:05       18 阅读

热门阅读

  1. linux的权限管理

    2023-12-07 10:36:05       37 阅读
  2. Nginx的缓存配置与其他配置

    2023-12-07 10:36:05       39 阅读
  3. 计算机视觉(CV)技术的优势和挑战-AI生成版

    2023-12-07 10:36:05       33 阅读
  4. Blocking_Analyzer_1.7_For_MySQL_8.0.exe

    2023-12-07 10:36:05       32 阅读
  5. 生活、工作常用API免费接口

    2023-12-07 10:36:05       26 阅读
  6. 梦想与魔法:编程之路的挑战与荣耀

    2023-12-07 10:36:05       28 阅读