解法:用tag数组维护区间最左端的数即可
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define ls(p) p << 1 #define rs(p) p << 1 | 1 const int M = 2e5 + 10; ll ans[M << 2], tag[M << 2]; int a[M]; void push_up(int p) { ans[p] = ans[ls(p)] + ans[rs(p)]; } void build(int p, int l, int r) { tag[p] = 0; if(l == r) { ans[p] = a[l]; return; } int mid = l + r >> 1; build(ls(p), l, mid); build(rs(p), mid + 1, r); push_up(p); } void push_down(int p, int p_l, int p_r) { if(!tag[p]) return; int mid = p_l + p_r >> 1; tag[ls(p)] = tag[p]; ans[ls(p)] = 1ll * (mid - p_l + 1ll) * (1ll * 2 * tag[ls(p)] + (ll)mid - p_l) / 2; tag[rs(p)] = tag[p] + mid - p_l + 1; ans[rs(p)] = 1ll * ((ll)p_r - mid) * (1ll * 2 * tag[rs(p)] + (ll)p_r - mid - 1) / 2; tag[p] = 0; } void add(int p, int p_l, int p_r, int l, int r, int x) { if(p_l >= l && p_r <= r) { tag[p] = p_l - l + x; ans[p] = 1ll * (p_r - p_l + 1ll) * (1ll * 2 * tag[p] + (ll)p_r - p_l) / 2; return; } push_down(p, p_l, p_r); int mid = p_l + p_r >> 1; if(l <= mid) add(ls(p), p_l, mid, l, r, x); if(r > mid) add(rs(p), mid + 1, p_r, l, r, x); push_up(p); } ll query(int p, int p_l, int p_r, int l, int r) { ll sum = 0; if(p_l >= l && p_r <= r) { return ans[p]; } push_down(p, p_l, p_r); int mid = p_l + p_r >> 1; if(l <= mid) sum += query(ls(p), p_l, mid, l, r); if(r > mid) sum += query(rs(p), mid + 1, p_r, l, r); return sum; } int main(){ int n, m; scanf("%d%d", &n, &m); for(int i = 1; i <= n; i++) scanf("%d", &a[i]); build(1, 1, n); while(m--) { int opt, l, r, x; scanf("%d", &opt); if(opt == 1) { scanf("%d%d%d", &l, &r, &x); add(1, 1, n, l, r, x); } else { scanf("%d%d", &l, &r); printf("%lld ", query(1, 1, n, l, r)); } } return 0; }