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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| #include <bits/stdc++.h>
using namespace std;
typedef long long ll; typedef pair<int, int> pii; const int N = 1e5 + 10, Log = 20, inf = 0x3f3f3f3f;
int a[N];
struct Info{ ll sum, lz; int h, cnt; void merge(Info &p1, Info &p2){ sum = p1.sum + p2.sum; h = min(p1.h, p2.h); cnt = p1.cnt + p2.cnt; } }info[N << 2];
void apply(int k, ll lz){ info[k].sum -= lz * info[k].cnt; info[k].lz += lz; info[k].h -= lz; if(info[k].sum == 0){ info[k].cnt = 0; } }
void pd(int k){ if(!info[k].lz) return; apply(k << 1, info[k].lz); apply(k << 1 | 1, info[k].lz); info[k].lz = 0; }
void build(int k, int l, int r){ if(l == r){ info[k] = {a[l], 0, a[l], 1}; return; } int mid = (l + r) >> 1; build(k << 1, l, mid); build(k << 1 | 1, mid + 1, r); info[k].lz = 0; info[k].merge(info[k << 1], info[k << 1 | 1]); }
void upd(int k, int l, int r, int ql, int qr, int x){ if(r < ql || l > qr) return; if(info[k].cnt == 0) return; if(l >= ql && r <= qr){ if(info[k].h >= x){ info[k].sum -= 1ll * x * info[k].cnt; info[k].lz += x; info[k].h -= x; if(info[k].sum == 0){ info[k].cnt = 0; info[k].h = inf; } return; } if(l == r){ info[k] = {0, 0, inf, 0}; return; } } pd(k); int mid = (l + r) >> 1; upd(k << 1, l, mid, ql, qr, x); upd(k << 1 | 1, mid + 1, r, ql, qr, x); info[k].merge(info[k << 1], info[k << 1 | 1]); }
ll qry(int k, int l, int r, int ql, int qr){ if(l > qr || r < ql) return 0; if(l >= ql && r <= qr){ return info[k].sum; } pd(k); int mid = (l + r) >> 1; return qry(k << 1, l, mid, ql, qr) + qry(k << 1 | 1, mid + 1, r, ql, qr); }
void solve() { int n, q; cin >> n >> q; for(int i = 1; i <= n; i++) cin >> a[i]; build(1, 1, n); while(q--){ int op, l, r, x; cin >> op >> l >> r; if(op == 1){ ll sum = 0; if(l <= r){ sum = qry(1, 1, n, l, r); }else{ sum = qry(1, 1, n, l, n) + qry(1, 1, n, 1, r); } cout << sum << '\n'; }else{ cin >> x; if(l <= r){ upd(1, 1, n, l, r, x); }else{ upd(1, 1, n, l, n, x); upd(1, 1, n, 1, r, x); } } } }
int main() { int T = 1; ios::sync_with_stdio(false); while (T--) solve(); return 0; }
|