这是一道经典的贪心。
我们需要分析一下它的贪心策略:
显然,我们应该先给 升序排序,即优先修容易报废的,然后遍历,能修就尽量修,然后进队,把总时间存起来。如果遍历到修不完的呢?直接跳过吗?不一定,那样就可能错过一些更优解。那怎么去做呢?
即使不修,我们也把它进队,然后在队列里选出一个需要的时间最长的出队,也就是不修,不会影响到其它本来就在队列里的建筑。
需要注意一点:虽然题目说数据不超过 int,但总时间也可能会溢出。如果是先加再减的,就得开 long long 或者 unsigned int。十年 OI 一场空,不开 long long 见祖宗!
附上 AC Code:
#include <bits/stdc++.h>
using namespace std;
int n;
struct building {
int t1, t2;
} arr[150005];
bool cmp(building x, building y) {
return x.t2 < y.t2;
}
struct Cmp {
bool operator () (int x, int y) {
return arr[x].t1 < arr[y].t1;
}
};
priority_queue<int, vector<int>, Cmp> q;
long long ti=0;
int ans=0;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d %d", &arr[i].t1, &arr[i].t2);
}
sort(arr+1, arr+1+n, cmp);
for (int i = 1; i <= n; i++) {
ti += arr[i].t1;
q.push(i);
if (ti <= arr[i].t2) {
ans++;
} else {
ti -= arr[q.top()].t1;
q.pop();
}
}
printf("%d", ans);
return 0;
}