luogu1083【2012提高】借教室(二分答案+差分前缀和)

二分答案是精髓,差分前缀和代替线段树,好写又精简!

#include 
using namespace std;
#define N 1000100
#define ll long long
#define inf 0x3f3f3f3f
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x*f;
}
int n,m,a[N];
struct node{
    int val,st,ed;
}b[N];
ll sum[N];
bool jud(int x){
    memset(sum,0,sizeof(sum));
    for(int i=1;i<=x;++i)
        sum[b[i].st]+=b[i].val,sum[b[i].ed+1]-=b[i].val;
    for(int i=1;i<=n;++i){
        sum[i]+=sum[i-1];
        if(sum[i]>a[i]) return 0;
    }
    return 1;
}
int main(){
//  freopen("a.in","r",stdin);
    n=read();m=read();
    for(int i=1;i<=n;++i) a[i]=read();
    for(int i=1;i<=m;++i) b[i].val=read(),b[i].st=read(),b[i].ed=read();
    int l=1,r=m,ans=0;
    if(jud(m)){puts("0");return 0;}
    while(l<=r){
        int mid=l+r>>1;
        if(jud(mid)) l=mid+1,ans=mid;
        else r=mid-1;
    }
    printf("%d\n%d\n",-1,ans+1);
    return 0;
}

你可能感兴趣的:(二分答案,其他oj,差分)