天天看点

BZOJ1029 [JSOI2007]建筑抢修(洛谷P4053)贪心 堆

贪心 堆

BZOJ题目传送门

洛谷题目传送门

首先按照T2从小到大排序,然后扫一遍过去进行贪心。

如果当前时间能抢修的就抢修,并把T1加到堆里。否则和堆顶比较,如果堆顶>T1就把堆顶拿出来,把T1加进去。这么做是为了减少时间。

代码:

#include<queue>
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 150005
using namespace std;
typedef long long LL;
struct data{ int x,y; }a[N];
int n,ans; LL t;
priority_queue <int> q;
inline char readc(){
    static char buf[],*l=buf,*r=buf;
    if (l==r) r=(l=buf)+fread(buf,,,stdin);
    if (l==r) return EOF; return *l++;
}
inline int _read(){
    int x=,f=; char ch=readc();
    while (!isdigit(ch)) { if (ch=='-') f=-; ch=readc(); }
    while (isdigit(ch)) x=(x<<)+(x<<)+(ch^),ch=readc();
    return x;
}
bool cmp(data x,data y){ return x.y<y.y; }
int main(){
    n=_read();
    for (int i=;i<=n;i++) a[i].x=_read(),a[i].y=_read();
    sort(a+,a+n+,cmp);
    for (int i=;i<=n;i++)
        if (a[i].y>=a[i].x+t) ans++,t+=a[i].x,q.push(a[i].x);
        else if (!q.empty()&&q.top()>a[i].x)
            t+=a[i].x-q.top(),q.pop(),q.push(a[i].x);
    return printf("%d\n",ans),;
}