洛谷 P2107 小Z的AK计划(反悔贪心)

传送门


解题思路

还是反悔贪心。按照位置从左到右排序,每走到一个新的机房就m减去走的路程,然后判断剩下的时间够不够ak此机房,如果够,就ak,并把时间加入到大根堆中,如果不够,就比较堆顶,若当前更优,就弹出堆顶,把新元素加入堆。

AC代码

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<queue>
 5 #include<algorithm>
 6 using namespace std;
 7 const int maxn=100005;
 8 int n,ans;
 9 long long m;
10 struct node{
11     long long x,t;
12 }a[maxn];
13 bool cmp(node a,node b){
14     return a.x<b.x;
15 }
16 priority_queue<long long> q;
17 int main(){
18     cin>>n>>m;
19     for(int i=1;i<=n;i++) scanf("%lld%lld",&a[i].x,&a[i].t);
20     sort(a+1,a+n+1,cmp);
21     for(int i=1;i<=n;i++){
22         m-=a[i].x-a[i-1].x;
23         if(m>=a[i].t){
24             m-=a[i].t;
25             q.push(a[i].t);
26             ans++;
27         }else{
28             if(!q.empty()&&q.top()>a[i].t){
29                 m+=q.top()-a[i].t;
30                 q.pop();
31                 q.push(a[i].t);
32             }
33         }
34     }
35     cout<<ans;
36     return 0;
37 }

 

posted @ 2020-11-04 21:33  尹昱钦  阅读(106)  评论(0编辑  收藏  举报