题解 | #【模板】线段树1#

【模板】线段树1

https://www.nowcoder.com/practice/e767b7b441ce4345aad1fac0a3633afb

#include <bits/stdc++.h>
const int N = 5e5 + 10;
const int inf = 0x3f3f3f3f;
using namespace std;
using ull = unsigned long long int;
using ll = long long int;
struct vc {
    ll x;
    ll l, r;
    ll lazy;
} tree[N << 2];
ll a[N];
void pushdown(ll p) {
    tree[p << 1].x += tree[p].lazy * (tree[p << 1].r - tree[p << 1].l + 1);
    tree[p << 1 | 1].x += tree[p].lazy * (tree[p << 1 | 1].r - tree[p << 1 | 1].l + 1);
    tree[p << 1].lazy += tree[p].lazy;
    tree[p << 1 | 1].lazy += tree[p].lazy;
    tree[p].lazy = 0;
}
void build(ll p, ll l, ll r) {
    tree[p].l = l, tree[p].r = r, tree[p].lazy = 0;
    if (l == r) {
        tree[p].x = a[l];
        return ;
    }
    ll mid = l + r >> 1;
    build(p << 1, l, mid);
    build(p << 1 | 1, mid + 1, r);
    tree[p].x = tree[p << 1].x + tree[p << 1 | 1].x;
}
void add(ll p, ll L, ll R, ll c) {
    if (L <= tree[p].l && tree[p].r <= R) {
        tree[p].x += (tree[p].r - tree[p].l + 1) * c;
        tree[p].lazy += c;
        return;
    }
    pushdown(p);
    ll mid = (tree[p].l + tree[p].r) >> 1;
    if (L <= mid) {
        add(p << 1, L, R, c);
    }
    if (R > mid) {
        add(p << 1 | 1, L, R, c);
    }
    tree[p].x = tree[p << 1].x + tree[p << 1 | 1].x;
}
ll query(ll p, ll L, ll R) {
    if (L <= tree[p].l && tree[p].r <= R) {
        return tree[p].x;
    }
    pushdown(p);
    ll mid = (tree[p].l + tree[p].r) >> 1;
    ll sum = 0;
    if (L <= mid) {
        sum += query(p << 1, L, R);
    }
    if (R > mid) {
        sum += query(p << 1 | 1, L, R);
    }
    return sum;
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    ll n, q;
    cin >> n >> q;
    for (ll i = 1; i <= n; i++) {
        cin >> a[i];
    }
    build(1, 1, n);
    for (ll i = 1; i <= q; i++) {
        ll op;
        cin >> op;
        if (op == 1) {
            // ll L, R, c;
            ll k,c;
            cin>>k>>c;
            // cin >> L >> R >> c;
            add(1, k, k, c);
        } else {
            ll L, R;
            cin >> L >> R;
            cout << query(1, L, R) << '\n';
        }
    }
    return 0;
}

线段树板子题目,直接CV

全部评论
点赞 回复 分享
发布于 11-23 22:52 湖北

相关推荐

Java抽象带篮子:安卓怎么你了
投递荣耀等公司10个岗位
点赞 评论 收藏
分享
评论
2
收藏
分享
牛客网
牛客企业服务