1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| #include<bits/stdc++.h>
using namespace std;
const int N = 1e5+5; int a[N]; struct Node{ int l,r,sum,add; }tree[N<<2]; void up(int i){ tree[i].sum = tree[i<<1].sum+tree[i<<1|1].sum; } void down(int i){ if(tree[i].add){ tree[i<<1].sum += (tree[i<<1].r-tree[i<<1].l+1)*tree[i].add; tree[i<<1|1].sum += (tree[i<<1|1].r-tree[i<<1|1].l+1)*tree[i].add; tree[i<<1].add += tree[i].add; tree[i<<1|1].add += tree[i].add; tree[i].add = 0; } } void build(int l,int r,int i){ if(l == r){ tree[i] = {l,r,a[l],0}; } else{ int mid = (l+r) >> 1; build(l,mid,i << 1); build(mid+1,r,i<<1 | 1); tree[i].l = tree[i<<1].l; tree[i].r = tree[i<<1|1].r; tree[i].add = 0; up(i); } } void update(int i,int p,int x){ if(tree[i].l == p && tree[i].r == p){ tree[i].sum += x; return; } int mid = (tree[i].l+tree[i].r) >> 1; if(p <= mid) update(i<<1,p,x); else update(i<<1|1,p,x); up(i);
} void update(int i,int jobl,int jobr,int x){ if(jobl <= tree[i].l && tree[i].r <= jobr){ tree[i].sum += (tree[i].r-tree[i].l+1)*x; tree[i].add += x; return; } int mid = (tree[i].l+tree[i].r)>>1; down(i); if(jobl<=mid) update(i<<1,jobl,jobr,x); if(jobr>mid) update(i<<1|1,jobl,jobr,x); up(i); } int query(int i,int jobl,int jobr){ if(jobl <= tree[i].l && tree[i].r <= jobr){ return tree[i].sum; } down(i); int mid = (tree[i].l+tree[i].r) >> 1; int sum = 0; if(jobl <= mid) sum+=query(i<<1,jobl,jobr); if(jobr>mid) sum+=query(i<<1|1,jobl,jobr); return sum; }
|