线段树

此篇部分原创,不能保证绝对的正确性,如有错误,请多多指教


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
#define DF_m int m=B+(E-B)/2
#define lch node*2,B,m
#define rch node*2+1,m+1,E
const int N = 100010;
LL sum[N*4], tree[N*4], add[N*4];
int n;

void pushup(int node) {
    tree[node] = max(tree[node*2], tree[node*2+1]);
    sum[node] = sum[node*2] + sum[node*2+1];
}

void pushdown(int node, int l) {
    if(add[node]) {
        sum[node*2] += add[node] * (LL)(l - l/2);
        sum[node*2+1] += add[node] * (LL)(l/2);
        tree[node*2] += add[node];
        tree[node*2+1] += add[node];
        add[node*2] += add[node];
        add[node*2+1] += add[node];
        add[node] = 0;
    }
}

void build(int node, int B, int E) {
    if(B == E) {
        scanf("%lld", &tree[node]);
        sum[node] = tree[node];
        return ;
    }
    DF_m;
    build(lch);
    build(rch);
    pushup(node);
}

void update(int node, int B, int E, int l, int r, int w) {
    if(B > r or E < l) return ;
    if(B >= l && E <= r) {
        add[node] += w;
        sum[node] += (LL)(w * (E-B+1));
        tree[node] += w;
        return ;
    }
    pushdown(node, E-B+1);
    DF_m;
    if(l <= m)  update(lch, l, r, w);
    if(r > m)   update(rch, l, r, w);
    pushup(node);
}

LL query_sum(int node, int B, int E, int l, int r) {
    if(B > r or E < l) return 0;
    if(B >= l and E <= r) {
        return sum[node];
    }
    pushdown(node, E-B+1);
    DF_m;
    LL res = 0;
    if(l <= m)  res += query_sum(lch, l, r);
    if(r > m)   res += query_sum(rch, l, r);
    return res;
}

LL query_max(int node, int B, int E, int l, int r) {
    if(B > r or E < l) return 0;
    if(B >= l and E <= r) {
        return tree[node];
    }
    pushdown(node, E-B+1);
    DF_m;
    LL res = 0;
    if(l <= m)  res = max(res, query_max(lch, l, r));
    if(r > m)   res = max(res, query_max(rch, l, r));
    return res;
}

int main() {
    scanf("%d", &n);
    build(1, 1, n);
    int Q;
    scanf("%d", &Q);
    while(Q--) {
        int l, r;
        char st[10];
        scanf("%s", st);
        scanf("%d%d", &l, &r);
        if(st[0] == 'C') {                                                  //change
            int w;
            scanf("%d", &w);
            update(1, 1, n, l, r, w);
        }
        else {
            if(st[0] == 'M') printf("%lld\n", query_max(1, 1, n, l, r));    //max
            if(st[0] == 'S') printf("%lld\n", query_sum(1, 1, n, l, r));    //sum
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值