题目大意:
超市有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;
}