【贪心】接水问题

【贪心】接水问题

题面

学校里有一个水房,水房里一共装有m个龙头可供同学们打开水,每个龙头每秒钟的供水量相等,均为1。

现在有n名同学准备接水,他们的初始接水顺序已经确定。将这些同学按接水顺序从1到n编号,i号同学的接水量为wi。接水开始时,1到m号同学各占一个水龙头,并同时打开水龙头接水。当其中某名同学j完成其接水量要求wj后,下一名排队等候接水的同学k马上接替j同学的位置开始接水。这个换人的过程是瞬间完成的,且没有任何水的浪费。即j同学第x秒结束时完成接水,则k同学第x+1秒立刻开始接水。若当前接水人数n’不足m,则只有n’个龙头供水,其它m−n’个龙头关闭。

现在给出n名同学的接水量,按照上述接水规则,问所有同学都接完水需要多少秒。

思路

一共m个水龙头,遍历n个人,每次把人安排在接水时间最少的一个水龙头。
使用:优先队列

代码

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

const int N = 1e4 + 10;

priority_queue<int, vector<int>,greater<int>> pq;
//小根序优先队列

int main() {
    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= m; i++) {
        int t = 0;
        pq.push(t);
        //输入初始数据,每个水龙头均为0
    }
    for(int i = 1; i <= n; i++) {
        int t;
        cin >> t;
        t += pq.top();//加在时间最少的水龙头上
        pq.pop();
        pq.push(t);
    }
    while(pq.size() > 1) {
        pq.pop();
        //只留下最大的那个水龙头
    }
    cout<<pq.top();
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的 C 语言菜单程序,可用于模拟问题: ```c #include <stdio.h> int main() { int choice; int current_water = 0; int max_capacity = 10; while (1) { printf("\n"); printf("1. 加\n"); printf("2. \n"); printf("3. 查看当前量\n"); printf("4. 退出程序\n"); printf("\n"); printf("请输入您的选择(1-4): "); scanf("%d", &choice); switch (choice) { case 1: if (current_water < max_capacity) { int add_water; printf("请输入要加的量:"); scanf("%d", &add_water); if (current_water + add_water > max_capacity) { printf("桶已满,加失败!\n"); } else { current_water += add_water; printf("成功加了 %d 升,当前量为 %d 升。\n", add_water, current_water); } } else { printf("桶已满,加失败!\n"); } break; case 2: if (current_water > 0) { int get_water; printf("请输入要量:"); scanf("%d", &get_water); if (get_water > current_water) { printf("不够,失败!\n"); } else { current_water -= get_water; printf("成功了 %d 升,当前量为 %d 升。\n", get_water, current_water); } } else { printf("已经被完了,失败!\n"); } break; case 3: printf("当前量为 %d 升。\n", current_water); break; case 4: printf("程序已退出!\n"); return 0; default: printf("无效的选项,请重新输入!\n"); break; } } } ``` 这个程序使用了一个无限循环,每次循环都会显示一个菜单供用户选择:加、查看当前量以及退出程序。根据用户的选择,程序会执行相应的操作,并输出结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值