0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-11-23 20:08:47 +00:00

#130. 树状数组 1 :单点修改,区间查询

https://loj.ac/s/1438029
This commit is contained in:
Baoshuo Ren 2022-04-10 21:49:19 +08:00
parent f311f6f98d
commit e8b38f4ba7
Signed by: baoshuo
GPG Key ID: 70F90A673FB1AB68

View File

@ -1,85 +1,46 @@
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
using std::cin;
using std::cout;
const char endl = '\n';
struct node {
int l, r;
long long s, d;
const int N = 1e6 + 5;
node() {
l = r = s = d = 0;
}
node(int _l, int _r) {
l = _l;
r = _r;
s = d = 0;
}
} tr[1000005 << 2];
int n, m, op, x, y, k, a[1000005];
int n, q, op, x, y;
long long c[N];
void pushup(int u) {
tr[u].s = tr[u << 1].s + tr[u << 1 | 1].s;
inline int lowbit(int x) {
return x & -x;
}
void pushdown(int u) {
if (!tr[u].d) return;
tr[u << 1].d += tr[u].d;
tr[u << 1].s += (tr[u << 1].r - tr[u << 1].l + 1) * tr[u].d;
tr[u << 1 | 1].d += tr[u].d;
tr[u << 1 | 1].s += (tr[u << 1 | 1].r - tr[u << 1 | 1].l + 1) * tr[u].d;
tr[u].d = 0;
void add(int x, int y) {
for (; x <= n; x += lowbit(x)) c[x] += y;
}
void build(int u, int l, int r) {
tr[u] = node(l, r);
if (l == r) {
tr[u].s = a[l];
return;
}
int mid = l + r >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
pushup(u);
}
void modify(int u, int l, int r, int d) {
if (tr[u].l >= l && tr[u].r <= r) {
tr[u].d += d;
tr[u].s += (tr[u].r - tr[u].l + 1) * d;
return;
}
int mid = tr[u].l + tr[u].r >> 1;
pushdown(u);
if (l <= mid) modify(u << 1, l, r, d);
if (r > mid) modify(u << 1 | 1, l, r, d);
pushup(u);
}
long long query(int u, int l, int r) {
if (tr[u].l >= l && tr[u].r <= r) {
return tr[u].s;
}
int mid = tr[u].l + tr[u].r >> 1;
long long s = 0;
pushdown(u);
if (l <= mid) s += query(u << 1, l, r);
if (r > mid) s += query(u << 1 | 1, l, r);
return s;
long long sum(int x) {
long long ans = 0;
for (; x; x -= lowbit(x)) ans += c[x];
return ans;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i];
std::ios::sync_with_stdio(false);
cin >> n >> q;
for (int i = 1, x; i <= n; i++) {
cin >> x;
add(i, x);
}
build(1, 1, n);
for (int i = 0; i < m; i++) {
while (q--) {
cin >> op >> x >> y;
if (op == 1) {
modify(1, x, x, y);
} else if (op == 2) {
cout << query(1, x, y) << endl;
add(x, y);
} else { // op == 2
cout << sum(y) - sum(x - 1) << endl;
}
}
return 0;
}
}