FJUT 3876 priority queue to go back greedy

moxin recently so poor, so poor that only she would sell, and moxin bought some dishes, each dish has an expiration time ti and the corresponding price wi, due moxin it is not selling vegetables, rich woman moxin poor brother, so decided to buy a day to moxin kind of dish, moxin so there are unscrupulous people will not sell expired food, assuming that time is infinite, then ask how much value moxin up to sell food? (Time from the beginning)

Input
input a n, representatives vegetables n (1 <= n <= 105 ) a plurality of sets of input data

Next n lines, each line has two numbers wi, ti (1 <= wi, ti <= 105)

Output
Output the total value

SampleInput
1
1 1
SampleOutput
1

The meaning of problems: there are N vegetables, vegetables every deadline and have his weight, assuming the sale of infinite length of time, up to ask how much benefit.
Thinking: This is a question I WA six rounds, did not take into account the priority queue maintained by the answer as to why the column with priority, because at the back of the dish you might better before than you are, on the whole idea is to sort greedy + + priority queue maintenance.
I offer the following codes to force the low specific look at the code comments

#include <queue>
#include <algorithm>
#include <cstdio>

using namespace std;
typedef long long LL;
const int N = 2e5+5;

struct node
{
    int t,v;
}a[N];///结构体存每种菜的期限和价值

bool cmp(node a,node b)///先以时间排 再以权值排
{
    if(a.t!=b.t)
        return a.t < b.t;
    return a.v > b.v;
}

int main()
{
    int n;

    while(~scanf("%d",&n))
    {
        priority_queue<int,vector<int>,greater<int> >que;///小根堆使得更小的排在前

        for(int i=1;i<=n;i++)
            scanf("%d%d",&a[i].v,&a[i].t);


        sort(a+1,a+1+n,cmp);

        LL res=0;

        for(int i=1;i<=n;i++)
        {
            if(que.size() < a[i].t)///满足时间条件的输入
            {
                res+=a[i].v;
                que.push(a[i].v);
            }
            else
            {
                if(a[i].v > que.top())///同一时间如果我的权值比你的大,则交换
                {
                    res-=que.top();
                    que.pop();
                    res+=a[i].v;
                    que.push(a[i].v);
                }
            }
        }

        printf("%lld\n",res);
    }
    
    return 0;
}
Published 54 original articles · won praise 0 · Views 1238

Guess you like

Origin blog.csdn.net/weixin_44144278/article/details/98504816