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

来源:互联网 发布:网络电话录音 编辑:程序博客网 时间:2024/05/01 13:47

考试时的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.csdn.net/loi_peacefuldog

0 0
原创粉丝点击