LA2757

18 篇文章 0 订阅
4 篇文章 0 订阅

题目大意:
超市有n件物品,每件物品有响应的利润p和保质期d,每天只能卖出一件物品,必须得在改保质期前卖出才能赚到利润,问如何卖这些物品才能使利润达到最大

思路:
按保质期升序排序,用一个cur表示时间天数,如果cur <= 保质期的话,就直接加上它的利润,当cur > 保质期的话,就不断替换成最优的。这就需要一个优先级队列,存放利润从低到高,如果发现比最低的多的就 替换掉。

代码:

WA了。。不太懂优先级队列的运算符重载。。
为什么没有排序呢。。

#include <iostream>
using namespace std;
#include <stdio.h>
#include <cstring>
#include <queue>
#include <algorithm>
struct product{
    int p,d;
    bool operator < (const product t) const {
        return p < t.p;
    }
}p[10010];
int n;
priority_queue<product> q;

int cmp(const product a,const product b) {
    return a.d < b.d;
}
int main() {
    while(scanf("%d",&n) == 1) {
        for(int i = 0 ; i < n ; i++)
            scanf("%d %d",&p[i].p,&p[i].d);
        sort(p,p+n,cmp);
        while(!q.empty()) q.pop();
        int cur = 0,ans = 0;
        for(int i = 0; i < n; i++) {
            if(cur < p[i].d) {
                ans += p[i].p;
                cur++;
            //  printf("%d %d\n",-p[i].p,p[i].p);
                q.push(p[i]);
            }
            else {
                if(!q.empty() ){
                    product x = q.top();
            //      printf("%d %d\n ",x.p,p[i].p);
                    if(x.p < p[i].p) {
                        ans += p[i].p - x.p;
                        q.pop();
                        q.push(p[i]);
                    }
                }
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

别人AC代码:

#include <iostream>
using namespace std;
#include <stdio.h>
#include <cstring>
#include <queue>
#include <algorithm>
struct product{
    int p,d;
/*  bool operator < (const product t) const {
        return p < t.p;
    }*/
}p[10010];
int n;
priority_queue<int> q;

int cmp(const product a,const product b) {
    return a.d < b.d;
}
int main() {
    while(scanf("%d",&n) == 1) {
        for(int i = 0 ; i < n ; i++)
            scanf("%d %d",&p[i].p,&p[i].d);
        sort(p,p+n,cmp);
        while(!q.empty()) q.pop();
        int cur = 0,ans = 0;
        for(int i = 0; i < n; i++) {
            if(cur < p[i].d) {
                ans += p[i].p;
                cur++;
            //  printf("%d %d\n",-p[i].p,p[i].p);
                q.push(-p[i].p);
            }
            else {
                if(!q.empty() ){
                    int x =-q.top();
                    //printf("%d %d\n ",x,p[i].p);
                    if(x < p[i].p) {
                        ans += p[i].p - x;
                        q.pop();
                        q.push(-p[i].p);
                    }
                }
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值