P4053 [JSOI2007]建筑抢修(小根堆替换任务)

小刚在玩JSOI提供的一个称之为“建筑抢修”的电脑游戏:经过了一场激烈的战斗,T部落消灭了所有z部落的入侵者。但是T部落的基地里已经有N个建筑设施受到了严重的损伤,如果不尽快修复的话,这些建筑设施将会完全毁坏。现在的情况是:T部落基地里只有一个修理工人,虽然他能瞬间到达任何一个建筑,但是修复每个建筑都需要一定的时间。同时,修理工人修理完一个建筑才能修理下一个建筑,不能同时修理多个建筑。如果某个建筑在一段时间之内没有完全修理完毕,这个建筑就报废了。你的任务是帮小刚合理的制订一个修理顺序,以抢修尽可能多的建筑。

输入格式

第一行是一个整数N,接下来N行每行两个整数T1,T2描述一个建筑:修理这个建筑需要T1秒,如果在T2秒之内还没有修理完成,这个建筑就报废了。

输出格式

输出一个整数S,表示最多可以抢修S个建筑.

输入输出样例

输入 #1
4
100 200
200 1300
1000 1250
2000 3200
输出 #1
3

说明/提示

N < 150,000; T1 < T2 < maxlongint

求最优解->贪心,暴力,dp

这道题可以用贪心算法做,先把所有事件按着T2排序,然后一个个选择,如果满足就去做,将所需时间保留下来,不满足就看所需时间是否比之前抢修用的最大时间要少,是的话就替换掉

不能直接将T2按小到大,T1按小到大排序,从小到大选择,因为如果有可能存在T2大的,但是T1特别短的抢修事件,这时应该尽量先选这些点才对

代码:

#include<iostream>
#include<string>
#include<stack>
#include<stdio.h>
#include<queue>
#include<string.h>
#include<map>
#include<unordered_map>
#include<vector>
#include<iomanip>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn =150001;
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
inline int read()
{
    int f = 1, num = 0;
    char ch = getchar();
    while (0 == isdigit(ch)) { if (ch == '-')f = -1; ch = getchar(); }
    while (0 != isdigit(ch)) num = (num << 1) + (num << 3) + ch - '0', ch = getchar();
    return num * f;
}
struct node {
    ll s, d;
    bool operator<(const node b)const {
        if (d != b.d)return d < b.d;
        else return s < b.s;
    }
}a[maxn];
ll n;
int main() {
    //freopen("test.txt", "r", stdin);
    n = read();
    priority_queue<int>Q;
    for (int i = 1; i <= n; i++) {
        a[i].s = read(), a[i].d = read();
    }
    sort(a + 1, a + n + 1);
    int t = 0,cnt=0;
    for (int i = 1; i <= n; i++) {
        if (t + a[i].s <= a[i].d) {
            cnt++;
            t += a[i].s;
            Q.push(a[i].s);
        }
        else {
            if (a[i].s < Q.top()) {//后悔
                t -= Q.top(); Q.pop();
                t += a[i].s;
                Q.push(a[i].s);
            }
        }
    }
    cout << cnt << endl;
    return 0;
}

 

posted @ 2021-02-24 09:01  cono奇犽哒  阅读(74)  评论(0)    收藏  举报