题目
https://www.luogu.org/problemnew/show/P3093
FJ有N(1 <= N <= 10,000)头牛要挤牛奶,每头牛需要花费1单位时间。
奶牛很厌烦等待,奶牛i在它的截止时间d_i (1 <= d_i <= 10,000)前挤g(1 <= g_i <= 1000)的奶,否则将不能挤奶。时间t开始时为0,即在时间t=x时,最多可以挤x头奶牛。
请计算FJ的最大挤奶量。
输入输出格式
输入格式:
Line 1: The value of N.
Lines 2..1+N: Line i+1 contains the integers g_i and d_i.
输出格式:
Line 1: The maximum number of gallons of milk Farmer John can obtain.
输入输出样例
输入样例#1: 复制
4
10 3
7 5
8 1
2 1
输出样例#1: 复制
25
题解
贪心
先按照时间排序,维护一个当前时间,如果当前时间小于截止时间,那么就挤奶【雾】,丢入小跟堆,如果当前时间大于截止时间(最多大1,因为按时间排序后,前一个最少比当前这个小1,而在给定时间内,最多能对相同数量的奶牛进行操作),那么就在小根堆中找到之前最小的一个,和现在的比较,如果之前的那个比现在这个小,那么选择当前这个显然是更优的。
代码
#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int N=10000+500;
struct node{
int g,d;
}a[N];
priority_queue<node> Q;
int n,now,ans;
bool operator < (node a,node b){
return a.g>b.g;
}
bool cmp(node a,node b){
if(a.d==b.d){
return a.g>b.g;
}
return a.d<b.d;
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d%d",&a[i].g,&a[i].d);
}
sort(a+1,a+n+1,cmp);
for(int i=1;i<=n;i++){
if(now<a[i].d){
now++;
Q.push(a[i]);
}
else {
node u=Q.top();
if(u.g<a[i].g){
Q.pop();
Q.push(a[i]);
}
}
}
while(!Q.empty()){
node u=Q.top();
Q.pop();
ans+=u.g;
}
printf("%d",ans);
return 0;
}