【贪心】CODE[VS] 3377 [Mz]接水问题2 (模拟+优先队列(堆))

本文介绍了一种使用小根堆和贪心算法解决模拟接水问题的方法。通过维护一个表示当前水龙头接水时间的小根堆,并按顺序为每个学生分配接水时间最短的水龙头,确保了整体接水时间最优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


考试时的T1
水题,当时晚上没睡好,把m写成3(样例里面m == 3)
然后就非常帅气地一分没有
很水的一道模拟(贪心),模拟接水过程,由于接完水最终时间一定,所以我们不需要管接完了多少,我们只需要知道当前所有水龙头中,总接水时间最短的是哪一个( 用小根堆维护),然后将所有已排好序中最小的哪一个接上去就行了,虽然原题中还特别声明“特别地,同学们在打水前排好了队,接水所用时间更长的先接。”但这其实没用,因为总的接水时间一定,每次贪心将最小的接上,则最后将最大的接上时,其当前所在序列的总接水时间一定是最小的(小根堆性质)

STL优先队列_小根堆的定义:priority_queue< type , vector< type >, greater< type > >;
( type,填你想向优先队列里添加元素的类型 )

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;
typedef long long LL;

LL n,m;
LL xx;
LL w[1000002];

priority_queue<LL,vector<LL >,greater<LL > > xq;

inline LL read()
{
    char ch;
    LL data = 0;
    LL f = 1;
    while(ch < '0'||ch > '9')
    {
        ch = getchar(); 
        if(ch == '-')
            f = -1;
    }
    do{
        data = data*10 + ch-'0';
        ch = getchar();
    }while(ch >= '0'&&ch <= '9');

return data*f;
}

inline void search()
{
    while(n--)
    {
        LL x = xq.top();
        xq.pop();
        //cout<<xq.top()<<endl; 
        xq.push(x + w[n+1]);
    }
    while(!xq.empty())
    {
        xx = max(xq.top(),xx);
        xq.pop();
        //cout<<"xx: "<<xx<<endl;
    }
}

int main()
{
    n = read();
    m = read();
    //cout<<n<<" "<<m<<endl;
    for(LL i =1;i<=n;i++) 
    {
        w[i] = read();
        //cout<<"w of "<<i<<" is "<<w[i]<<endl;
    }
    sort(w+1,w+1+n);
    if(n <= m)
    {
        printf("%lld\n",w[n]);
    return 0;
    }
    for(LL i = 1;i <= min(n,m);i++) 
        xq.push(0);
    search();
    printf("%lld\n",xx);
    return 0;
}

THE END

By Peacefuldoge

http://blog.youkuaiyun.com/loi_peacefuldog

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值