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 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
| const int N = 2e5 + 10; typedef long long ll;
ll n, q, x[N];
struct info{ ll sum, sz; info(){sum = 0; sz = 1;} info(ll sum, ll sz):sum(sum), sz(sz){} };
struct tag{ ll d; tag(){d = -1;} tag(ll d):d(d){} };
info operator+(const info &l, const info &r){ return {l.sum + r.sum, l.sz + r.sz}; }
info operator+(const info &v, const tag &t){ return {v.sz * t.d, v.sz}; }
tag operator+(const tag &t1, const tag &t2){ return {t2.d}; }
struct Node{ tag t; info val; } seg[N * 4];
void settag(int id, tag t){ seg[id].val = seg[id].val + t; seg[id].t = seg[id].t + t; }
void pushdown(int id){ if (seg[id].t.d != -1){ settag(id * 2, seg[id].t); settag(id * 2 + 1, seg[id].t); seg[id].t.d = -1; } }
void update(int id){ seg[id].val = seg[id * 2].val + seg[id * 2 + 1].val; }
void build(int id, int l, int r){ if (l == r){ seg[id].val = info(x[l], 1); seg[id].t = tag(-1); } else{ int mid = (l + r) / 2; build(id * 2, l, mid); build(id * 2 + 1, mid + 1, r); update(id); } }
info query(int id, int l, int r, int ql, int qr){ if (l == ql && r == qr){ return seg[id].val; } int mid = (l + r) / 2; pushdown(id); if (qr <= mid) return query(id * 2, l, mid, ql, qr); else if (ql > mid) return query(id * 2 + 1, mid + 1, r, ql, qr); else return query(id * 2, l, mid, ql, mid) + query(id * 2 + 1, mid + 1, r, mid + 1, qr); }
void modify(int id, int l, int r, int ql, int qr, tag t){ if (l == ql && r == qr) { settag(id, t); return; } int mid = (l + r) / 2; pushdown(id); if (qr <= mid) modify(id * 2, l, mid, ql, qr, t); else if (ql > mid) modify(id * 2 + 1, mid + 1, r, ql, qr, t); else { modify(id * 2, l, mid, ql, mid, t); modify(id * 2 + 1, mid + 1, r, mid + 1, qr, t); } update(id); }
void solve() { cin >> n; for (int i = 1; i <= n; i ++ ) cin >> x[i], x[i] -= i; build(1, 1, n); cin >> q; ll ans = 0; while (q -- ){ ll t, g; cin >> t >> g; g -= t; ll xt = query(1, 1, n, t, t).sum; if (xt <= g){ int l = t, r = n; while (l < r){ int mid = (l + r + 1) / 2; if (query(1, 1, n, mid, mid).sum <= g) l = mid; else r = mid - 1; } ans += g * (r - t + 1) - query(1, 1, n, t, r).sum; modify(1, 1, n, t, r, tag(g)); }else{ int l = 1, r = t; while (l < r){ int mid = (l + r) / 2; if (query(1, 1, n, mid, mid).sum >= g) r = mid; else l = mid + 1; } ans += query(1, 1, n, l, t).sum - g * (t - l + 1); modify(1, 1, n, l, t, tag(g)); } } cout << ans; }
signed main() { IOS; int t = 1;
while (t--) { solve(); } return 0; }
|