看电影升级版

/**************************************************************
    Problem: 1029
    User: lxy8584099
    Language: C++
    Result: Accepted
    Time:612 ms
    Memory:3556 kb
****************************************************************/
 
/*
    有点像看电影。。 
    贪心 开始时间不确定 但是修理时间是固定的 
    先按结束时间排序 
    把修理的维护一个大根堆。。。不是和上次的比较 
    每次能修就修  不能修就询问对顶的建筑
    要是对顶T1较大 就不修对顶 改修本次 
     
*/
#include<cstdio>
#include<queue> 
#include<algorithm> 
#define ll long long 
using namespace std;
const int N=1e5+5e4+50;
struct pp {ll t1,t2;} a[N]; 
bool cmp(pp a,pp b) {return a.t2<b.t2;} 
int n;
priority_queue< int > q;
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%lld%lld",&a[i].t1,&a[i].t2);
    sort(a+1,a+n+1,cmp);
    ll now=0;int ans=0;
    for(int i=1;i<=n;i++)
    {
        if(now+a[i].t1<=a[i].t2) 
            now+=a[i].t1,q.push(a[i].t1),ans++;
        else
        {
            if(q.empty()) continue;
            int t=q.top();
            if(t>a[i].t1)
            {
                q.pop();q.push(a[i].t1);
                now=now-t+a[i].t1;
            }
        }
    }
    printf("%d\n",ans);
    return 0;
}