反悔贪心

P4053 [JSOI2007] 建筑抢修

题意

  • 有 n 个建筑需要修理,第 i 个建筑需要 leni 时间修理,且一定需要在 ti 时刻前完成
  • 在任意时刻你只能选择修理某一个建筑,且一旦开始就不能停下
  • 现在是 0 时刻,请你求出最多能够修复好几个建筑
  • n≤1.5×105;  1≤leni<ti<231n\le 1.5\times 10^5;\ \ 1\le len_i < t_i < 2^{31}

思路

  • 经典反悔贪心
  • 按照结束时刻排序,然后在结束时刻考虑是否要修复当前建筑
    • 如果当前剩余时间足以修复当前建筑,就将其修复并记录
    • 否则,考虑以前修复的建筑中需要时间最长的那个
      • 如果当前修复时间小于它,就将以前最贵的那个换成当前这个建筑的时间
      • 否则不做任何操作
  • 这个过程需要堆参与维护
  • 反悔体现在把以前的一些决策撤销,替换成当前的更优决策

code

struct node {
	int len, t;
} no[N];
bool operator < (node a, node b) {
	return a.t < b.t;
}

void solved() {
	
	int n;	cin >> n;
	_for(i, 1, n) cin >> no[i].len >> no[i].t;
	sort(no + 1, no + n + 1);
	
	priority_queue<int> pq;
	ll s = 0;
	
	_for(i, 1, n) {
		if(s + no[i].len > no[i].t && no[i].len < pq.top()) s -= pq.top(), pq.pop();
		if(s + no[i].len < no[i].t) pq.push(no[i].len), s += no[i].len;
	}
	
	cout << pq.size();
	
	return ;
}

练习题

1 条评论

  • @ 2026-6-30 17:59:29
    #include <bits/stdc++.h>
    using namespace std;
    const int N=15e4;
    struct node{
        long long ed,t;//代表结束时间及耗费时间 
    }a[N];
    bool cmp(node x ,node y){
        return x.ed<y.ed;
    }
    int n;
    int main(){
        cin>>n;
        for(int i=1;i<=n;i++)cin>>a[i].t>>a[i].ed;
        sort(a+1,a+n+1,cmp);//依据结束时间进行排序 
        priority_queue <long long> pq;//定义一个大根堆 
        long long s=0;//总时间
        for(int i=1;i<=n;i++){
            if(s<a[i].ed){ 
                if(s+a[i].t<a[i].ed){
                    s+=a[i].t;//直接贪心 
                    pq.push(a[i].t);
                }
                else if(!pq.empty()&&a[i].t<pq.top()){
                    s-=pq.top();//若是有更优秀选择,反悔贪心,把最大的那一次给移除掉 
                    pq.pop();
                    pq.push(a[i].t);
                    s+=a[i].t;
                }
            }else if(s>=a[i].ed){
                if(!pq.empty()&&s-pq.top()<a[i].ed&&a[i].t<pq.top()){//大于的情况下,考虑能否反悔贪心 
                    s-=pq.top();
                    pq.pop();
                    pq.push(a[i].t);
                    s+=a[i].t;
                }
            }//这一步贪不了,不是最优就不管他 
        } 
        cout<<pq.size();//输出有多少个元素代表修了几个建筑 
        return 0;
    }
    

    要多久才能和教练的代码一样优美

    • 1