树状数组
参考博客 https://blog.csdn.net/bestsort/article/details/80796531
单点更新 区间查询
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;
#define maxn 2000010
#define lowbit(a) ((a) & (-a))
int n, m, tree[maxn];
void add(int x, int k) {
while (x <= n) tree[x] += k, x += lowbit(x);
return ;
}
int get_sum(int x) {
int ret = 0;
while (x != 0) ret += tree[x], x -= lowbit(x);
return ret;
}
int main() {
int a, b, c;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a;
add(i, a);
}
for (int i = 0; i < m; i++) {
cin >> a >> b >> c;
if (a == 1) add(b, c);
else cout << get_sum(c) - get_sum(b - 1) << endl;
}
return 0;
}
区间更新 单点查询
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
using namespace std;
#define maxn 2000010
#define lowbit(a) ((a) & (-a))
int n, m;
int tree[maxn];
void add(int x, int k) { //这个函数用来在树状数组中直接修改
while(x <= n) tree[x] += k, x += lowbit(x);
}
void range_add(int l, int r, int k) { //给区间[l, r]加上x
add(l, k), add(r + 1, -k);
}
int ask(int x) { //单点查询
int res = 0;
while(x) res += tree[x], x -= lowbit(x);
return res;
}
int main() {
int op, x, y, z, last = 0, now;
cin >> n >> m;
for (int i = 1; i <= n; i++) { // 差分思想
scanf("%d", &now);
add(i, now - last);
last = now;
}
for (int i = 1; i <= m; i++) {
cin >> op;
if (op == 1) {
cin >> x >> y >> z;
range_add(x, y, z);
} else {
cin >> x;
cout << ask(x) << endl;
}
}
return 0;
}
区间修改 区间查询
#include <iostream>
using namespace std;
#define lowbit(a) ((a) & (-a))
#define maxn 2000010
typedef long long LL;
int n, m;
LL sum1[maxn], sum2[maxn];
void add(LL x, LL k) {
for(LL i = x; i <= n; i += lowbit(i)) {
sum1[i] += k, sum2[i] += x * k;
}
}
void range_add(LL l, LL r, LL x) {
add(l, x), add(r + 1, -x);
}
LL ask(LL x) {
LL res = 0;
for (LL i = x; i; i -= lowbit(i)) {
res += (x + 1) * sum1[i] - sum2[i];
}
return res;
}
LL range_ask(LL l, LL r) {
return ask(r) - ask(l - 1);
}
int main() {
int op, x, y, z;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> x;
range_add(i, i, x);
}
for (int i = 0; i < m; i++) {
cin >> op;
if (op == 1) {
cin >> x >> y >> z;
range_add(x, y, z);
} else {
cin >> x >> y;
cout << range_ask(x, y) << endl;
}
}
return 0;
}
文章评论