A Simple Problem with Integers POJ - 3468(线段树模板,区间修改,区间查询)

A Simple Problem with Integers

POJ - 3468

code

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>

using namespace std;
typedef long long ll;
const int N = 100005, INF = 0x3f3f3f3f;
ll tree[N << 2];
ll lazy[N << 2];

#define ls(rt) (rt << 1)
#define rs(rt) (rt << 1 | 1)

void push_up(int root) { tree[root] = tree[ls(root)] + tree[rs(root)]; }

void push_down(int root, int len) {
    if (lazy[root]) {
        lazy[ls(root)] += lazy[root]; // 这里都是增加 +=
        lazy[rs(root)] += lazy[root];
        tree[ls(root)] += lazy[root] * (len - (len >> 1));
        tree[rs(root)] += lazy[root] * (len >> 1);
        lazy[root] = 0;
    }
}

void build_tree(int l, int r, int root) {
    lazy[root] = 0;
    if (l == r) {
        scanf("%lld", &tree[root]);
        return;
    }
    int mid = (l + r) >> 1;
    build_tree(l, mid, ls(root));
    build_tree(mid + 1, r, rs(root));
    push_up(root);
}

void update(int l, int r, int root, int L, int R, int val) {
    if (L <= l && r <= R) {
        tree[root] += (r - l + 1) * val; // 增加 +=
        lazy[root] += val; // 增加 +=
        return;
    }
    push_down(root, r - l + 1);
    int mid = (l + r) >> 1;
    if (L <= mid) update(l, mid, ls(root), L, R, val);
    if (mid < R) update(mid + 1, r, rs(root), L, R, val);
    push_up(root);
}

ll query(int l, int r, int root, int L, int R) {
    if (L <= l && r <= R) {
        return tree[root];
    }
    push_down(root, r - l + 1);
    ll res = 0;
    int mid = (l + r) >> 1;
    if (L <= mid) res += query(l, mid, ls(root), L, R);
    if (R > mid) res += query(mid + 1, r, rs(root), L, R);
    return res;
}

int main() {
    int n, q;
    while (scanf("%d%d", &n, &q) != EOF) {
        build_tree(1, n, 1);
        while (q--) {
            char s[5];
            int x, y, z;
            scanf("%s", s);
            if (s[0] == 'Q') {
                scanf("%d%d", &x, &y);
                printf("%lld\n", query(1, n, 1, x, y));
            } else {
                scanf("%d%d%d", &x, &y, &z);
                update(1, n, 1, x, y, z);
            }
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值