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

本文介绍了一种基于贪心策略的堆算法实现方法,通过排序和堆操作来解决特定问题。该方法首先按条件排序输入数据,然后遍历数据进行贪心选择,使用堆结构辅助更新状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

贪心 堆

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[100000],*l=buf,*r=buf;
    if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
    if (l==r) return EOF; return *l++;
}
inline int _read(){
    int x=0,f=1; char ch=readc();
    while (!isdigit(ch)) { if (ch=='-') f=-1; ch=readc(); }
    while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
    return x;
}
bool cmp(data x,data y){ return x.y<y.y; }
int main(){
    n=_read();
    for (int i=1;i<=n;i++) a[i].x=_read(),a[i].y=_read();
    sort(a+1,a+n+1,cmp);
    for (int i=1;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),0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值