P3372 【模板】线段树 1

#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int N = 1e5 + 10;
int n, m;
LL w[N];
struct node {
    int l, r;
    LL sum, add;
}tr[N << 2];
void pushup(int u)
{
    tr[u].sum = tr[u << 1].sum + tr[u << 1 | 1].sum;
}
void build(int u, int l, int r)
{
    if (l == r) tr[u] = {l, r, w[l], 0};
    else {
        tr[u] = {l, r};
        int mid = l + r >> 1;
        build(u << 1, l, mid);
        build(u << 1 | 1, mid + 1, r);
        pushup(u);
    }
}
void pushdown(int u)
{
    auto &root = tr[u], &left = tr[u << 1], &right = tr[u << 1 | 1];
    if (root.add) {
        left.add += root.add, left.sum += (LL)(left.r - left.l + 1) * root.add;
        right.add += root.add, right.sum += (LL)(right.r - right.l + 1) * root.add;
        root.add = 0;
    }
}
LL query(int u, int l, int r)
{
    if (tr[u].l >= l && tr[u].r <= r)   return tr[u].sum;
    pushdown(u);
    LL sum = 0;
    int mid = tr[u].l + tr[u].r >> 1;
    if (l <= mid)   sum = query(u << 1, l, r);
    if (r > mid)    sum += query(u << 1 | 1, l, r);
    return sum;
}
void modify(int u, int l, int r, LL d)
{
    if (tr[u].l >= l && tr[u].r <= r) {
        tr[u].sum += (LL)(tr[u].r - tr[u].l + 1) * d;
        tr[u].add += d;
    }
    else {
        pushdown(u);
        int mid = tr[u].l + tr[u].r >> 1;
        if (l <= mid)   modify(u << 1, l, r, d);
        if (r > mid)    modify(u << 1 | 1, l, r, d);
        pushup(u);
    }
}
int main() {
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i ++ )  scanf("%lld", &w[i]);
    build(1, 1, n);
    while (m -- ) {
        int t, l, r;
        scanf("%d%d%d", &t, &l, &r);
        if (t == 1) {
            LL d;
            scanf("%lld", &d);
            modify(1, l, r, d);
        }
        else 
            printf("%lld\n", query(1, l, r));
    }
    return 0;
}
上一篇:【树形结构】训练题A - Can you answer these queries I


下一篇:Can you answer these queries III?