悬赏关注,离谱!求助,优先队列哪里错了

P1478 陶陶摘苹果(升级版)

RingTouSou @ 2023-10-28 21:39:27

#include<iostream>
#include<queue>
using namespace std;

struct cuntomcomparator{

    bool operator()(const pair<int,int> &a,const pair<int,int> &b) const{
            return a.second < b.second;
    }   
};
int main()
{
    priority_queue<pair<int,int>,vector<pair<int,int>>,cuntomcomparator> p;
    int n,s;
    cin>>n>>s;
    int a,b;
    cin>>a>>b;
    int k=a+b;
    int ans=0;
    for(int i=1;i<=n;++i)
    {
        int x,y;
        cin>>x>>y;
        p.push({x,y});
    }
    for(int i=1;i<=n;++i)
    {
        auto t=p.top();
        p.pop();
        if(s>=t.second&&k<=t.first)
        {
            ans++;
            s-=t.second;
        }
    }
    cout<<ans;
}

by heyx0201 @ 2023-10-28 21:47:54

@RingTouSou a这题要优先队列?


by zhuoxingmu @ 2023-10-28 21:50:33

    bool operator()(const pair<int,int> &a,const pair<int,int> &b) const{
            return a.second > b.second;
    }   

by zhuoxingmu @ 2023-10-28 21:52:00


        if(s>=t.second&&k>=t.first)
        {
            ans++;
            s-=t.second;
        }

by zhuoxingmu @ 2023-10-28 21:52:19

这两个地方改了就行了


by RingTouSou @ 2023-10-28 22:47:33

@heyx0201 正好最近在练,看到这题就想起来了


by RingTouSou @ 2023-10-28 22:50:52

@zhuoxingmu 上面那个明白,下面这个为什么return a.second > b.second;才是升序排列?


by zhuoxingmu @ 2023-10-28 22:54:44

是的,priority_queue中的排序是和你写的cmp函数相反的,意思是优先级低的在堆顶


by RingTouSou @ 2023-10-28 23:31:56

@zhuoxingmu 已关谢谢


|