贪心—排序不等式——acwing

题目:排队打水

913. 排队打水 - AcWing题库

分析

题意,所有人等待时间之和最小。

当第一个人打水,后面所有人都在等待。

贪心:要让所有人等待时间之和最小,每次都得取最小。

三种存储方式均可以,目的使每次都能取最小就好:

  • 1.vector数组,sort排序
  • 2.multiset 自动排序
  • 3.priority_queue<int,vector<int>,greater<int>> 小根堆

代码

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

multiset<int> s;

int main() {
    int n;
    cin >> n;
    for(int i = 0; i < n; i ++) {
        int x; cin >> x;
        s.insert(x);
    }
    
    long long res = 0;
    for(int i = 1; i < n; i ++) {
        set<int>::iterator it = s.begin();
        res += (*it)*(n-i);
        s.erase(s.begin());
    }
    
    cout << res << endl;
    return 0;
}
相关推荐
谢白羽14 小时前
vllm抢占机制详解
算法·vllm
Hello--_--World14 小时前
Vue2的 双端 diff算法 与 Vue3 的 快速diff 算法
前端·vue.js·算法
坚持编程的菜鸟14 小时前
The Blocks Problem
数据结构·c++·算法
2301_8227032014 小时前
Flutter 框架跨平台鸿蒙开发 - 家庭时间胶囊应用
算法·flutter·华为·图形渲染·harmonyos·鸿蒙
tankeven14 小时前
HJ171 排座椅
c++·算法
2301_8227032014 小时前
成语小词典:鸿蒙Flutter实现的成语查询与管理应用
算法·flutter·华为·开源·图形渲染·harmonyos
Bczheng114 小时前
八.账号生成规则 哈希 密钥
算法·哈希算法
黎阳之光14 小时前
视频孪生领航者,以中国技术定义全球数智化新高度
大数据·人工智能·算法·安全·数字孪生
6Hzlia14 小时前
【Hot 100 刷题计划】 LeetCode 39. 组合总和 | C++ 回溯算法与 startIndex 剪枝
c++·算法·leetcode
患得患失94914 小时前
【前端WebSocket】心跳功能,心跳重置策略、双向确认(Ping-Pong) 以及 指数退避算法(Exponential Backoff)
前端·websocket·算法