思路:
线段树区间修改,需要使用两个懒标记set和add。处理好两个标记的优先级即可(set之前的set和add是没有作用的)。
实现:
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 const int N = 100005; 5 6 int tree[N << 2], lazy_set[N << 2], lazy_add[N << 2], a[N], n, q; 7 8 void build(int num, int l, int r) 9 { 10 if (l == r) { tree[num] = a[l]; return; } 11 int m = l + r >> 1; 12 build(num << 1, l, m); 13 build(num << 1 | 1, m + 1, r); 14 tree[num] = tree[num << 1] + tree[num << 1 | 1]; 15 } 16 17 void pushdown(int num, int cl, int cr) 18 { 19 if (lazy_set[num]) 20 { 21 tree[num << 1] = lazy_set[num] * cl; 22 tree[num << 1 | 1] = lazy_set[num] * cr; 23 lazy_set[num << 1] = lazy_set[num]; 24 lazy_set[num << 1 | 1] = lazy_set[num]; 25 lazy_add[num << 1] = 0; 26 lazy_add[num << 1 | 1] = 0; 27 lazy_set[num] = 0; 28 } 29 if (lazy_add[num]) 30 { 31 tree[num << 1] += lazy_add[num] * cl; 32 tree[num << 1 | 1] += lazy_add[num] * cr; 33 lazy_add[num << 1] += lazy_add[num]; 34 lazy_add[num << 1 | 1] += lazy_add[num]; 35 lazy_add[num] = 0; 36 } 37 } 38 39 void update(int num, int l, int r, int x, int y, int p, int t) 40 { 41 if (x <= l && y >= r) 42 { 43 if (t == 0) 44 { 45 tree[num] += (r - l + 1) * p; 46 lazy_add[num] += p; 47 } 48 else 49 { 50 tree[num] = (r - l + 1) * p; 51 lazy_set[num] = p; 52 lazy_add[num] = 0; 53 } 54 return; 55 } 56 int m = l + r >> 1; 57 pushdown(num, m - l + 1, r - m); 58 if (x <= m) update(num << 1, l, m, x, y, p, t); 59 if (y >= m + 1) update(num << 1 | 1, m + 1, r, x, y, p, t); 60 tree[num] = tree[num << 1] + tree[num << 1 | 1]; 61 } 62 63 int query(int num, int l, int r, int x, int y) 64 { 65 if (x <= l && y >= r) return tree[num]; 66 int m = l + r >> 1; 67 pushdown(num, m - l + 1, r - m); 68 int ans = 0; 69 if (x <= m) ans += query(num << 1, l, m, x, y); 70 if (y >= m + 1) ans += query(num << 1 | 1, m + 1, r, x, y); 71 return ans; 72 } 73 74 int main() 75 { 76 ios::sync_with_stdio(false); 77 cin >> n >> q; 78 for (int i = 1; i <= n + 1; i++) cin >> a[i]; 79 build(1, 1, n + 1); 80 int x, y, t, p; 81 for (int i = 1; i <= q; i++) 82 { 83 cin >> t >> x >> y >> p; 84 x++; y++; 85 update(1, 1, n + 1, x, y, p, t); 86 cout << query(1, 1, n + 1, 1, n + 1) << endl; 87 } 88 return 0; 89 }