线段树复习打卡——1318: 借教室

http://61.139.95.227:82/problem.php?id=1318

线段树区间修改模版

#include <bits/stdc++.h>
#define read read()
#define up(i,l,r) for(int i = (l);i <= (r);i++)
#define down(i,l,r) for(int i = (l);i >= (r);i--)
#define ll long long
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
using namespace std;
int read
{
    int x = 0; char ch = getchar();
    while(ch < 48 || ch > 57) ch = getchar();
    while(ch >=48 && ch <= 57){x = 10 * x + ch - 48; ch = getchar();}
    return x;
}
const int N = 1e6 + 5;
int n,m,a[N];
int MIN[N<<2],lazy[N<<2];

void pushup(int rt)
{
    MIN[rt] = min(MIN[rt<<1] , MIN[rt<<1|1]);
}

void buildtree(int l,int r,int rt)
{
    if(l == r)
    {
        MIN[rt] = a[l];
        return;
    }
    int mid = (l + r)>>1;
    buildtree(lson);
    buildtree(rson);
    pushup(rt);
}

void pushdown(int rt)
{
    if(!lazy[rt]) return;
    lazy[rt<<1] += lazy[rt];
    lazy[rt<<1|1] += lazy[rt];
    MIN[rt<<1] -= lazy[rt];//rt
    MIN[rt<<1|1] -= lazy[rt];//rt
    lazy[rt] = 0;
}

void update(int L,int R,int d,int l,int r,int rt)
{
    if(L <= l && R >= r)
    {
        lazy[rt] += d;
        MIN[rt] -= d;
        return;
    }
    pushdown(rt);
    int mid = (l + r)>>1;
    if(L <= mid) update(L,R,d,lson);
    if(R >  mid) update(L,R,d,rson);
    pushup(rt);
}

int main()
{
//    freopen("input.txt","r",stdin);
    n = read; m = read;
    up(i,1,n) a[i] = read;
    buildtree(1,n,1);
    up(i,1,m)
    {
        int d = read,s = read, t = read;
        update(s,t,d,1,n,1);
        if(MIN[1] < 0) printf("-1
%d",i) , exit(0);
    }
    printf("0");
    return 0;
}
原文地址:https://www.cnblogs.com/mzg1805/p/10333058.html