单点修改:
#include <cstdio>
#define maxn 100005
using namespace std;
long long tree[maxn << 2];
int n, m, M;
void Add(long long s, long long val){
for (tree[s = s + M] += val; s > 1; tree[s >>= 1] += val);
}
long long Ask(long long s, long long t){
long long ans = 0;
for (s = s + M - 1, t = t + M + 1; s ^ t ^ 1; s >>= 1, t >>= 1){
if (~ s & 1) ans += tree[s ^ 1];
if (t & 1) ans += tree[t ^ 1];
}
return ans;
}
int main(){
scanf("%d%d", &n, &m);
for (M = 1; M <= n + 1; ) M <<= 1;
for (long long temp, i = 1; i <= n; i++){
scanf("%lld", &temp);
Add(i, temp);
}
while (m--){
long long opt, x, y, z;
scanf("%lld%lld%lld", &opt, &x, &y);
if (opt == 1){
scanf("%lld", &z);
for (long long i = x; i <= y; i++) Add(i, z);
}
else printf("%lld\n", Ask(x, y));
}
return 0;
}
因为这是ZKW线段树,所以x ^ 1 就是他的兄弟节点 (一开始一直没懂)
还有就是 M 是实际的数组下标->ZKW二叉树的节点的编号 要加上的值
s = s + M -1, t = t + M + 1就是把闭区间变成开区间
Add 是把要修改的节点到根节点上路径上的点全部加上val (这是因为ZKW线段树是从底向上操作的。。。)```cpp
#include <cstdio>
#define maxn 100005
using namespace std;
long long tree[maxn << 2], cover[maxn << 2];
int n, m, M, disM, dis[maxn << 2];
void Update(int k, long long val){
long long size = 1 << disM - dis[k];
while (k >>= 1) tree[k] += val * size;
}
void Add(int s, int t, long long val){
for (s = s + M - 1, t = t + M +1; s ^ t ^ 1; s >>= 1, t >>= 1){
if (~ s & 1) cover[s ^ 1] += val, Update(s ^ 1, val);
if (t & 1) cover[t ^ 1] += val, Update(t ^ 1, val);
}
}
long long Get(int k){
long long size = 1 << disM - dis[k], ans = tree[k] + cover[k] * size;
while (k >>= 1) ans += cover[k] * size;
return ans;
}
long long Ask(int s, int t){
long long ans = 0;
for (s = s + M - 1, t = t + M + 1; s ^ t ^ 1; s >>= 1, t >>= 1){
if (~ s & 1) ans += Get(s ^ 1);
if (t & 1) ans += Get(t ^ 1);
}
return ans;
}
int main(){
scanf("%d%d", &n, &m);
for (M = 1; M <= n + 1; ) M <<= 1;
for (int i = 2; i <= n + M; i++) dis[i] = dis[i >> 1] + 1;
disM = dis[M];
for (int i = 1; i <= n; i++) scanf("%lld", &tree[i + M]);
for (int i = M - 1; i; i--) tree[i] = tree[i << 1] + tree[i << 1 | 1];
while (m--){
int opt, x, y;
scanf("%d%d%d", &opt, &x, &y);
if (opt == 1){
long long z;
scanf("%lld", &z);
Add(x, y, z);
}
else printf("%lld\n", Ask(x, y));
}
return 0;
}
这里主要是用了Lazy_tag的思想,只不过是从下往上传递的
disM指的是ZKW线段树的总深度
dis[x] 指的是x节点到根的距离+1(也就是深度)