#include<bits/stdc++.h> #define N 1000010 #define SQN 1010 typedeflonglong ll;
int st[SQN], ed[SQN], size[SQN], bel[SQN]; ll a[N], tag[N], sum[N];
voidinit(){ int sq = (int) sqrt(n); for (int i = 1; i <= sq; i++) { st[i] = sq * (i - 1) + 1; ed[i] = sq * i; size[i] = ed[i] - st[i] + 1; } ed[sq] = n; size[sq] = ed[sq] - st[sq] + 1; for (int i = 1; i <= sq; i++) { for (int j = st[i]; j <= ed[i]; j++) { bel[j] = i; sum[i] += a[j]; } } }
按照如上所述的修改原理:
1 2 3 4 5 6 7 8 9
voidupdate(int l, int r, int x){ if (bel[l] == bel[r]) { for (int i = l; i <= r; i++) a[i] += x, sum[bel[i]] += x; } else { for (int i = l; i <= ed[bel[l]]; i++) a[i] += x, sum[bel[l]] += x; for (int i = st[bel[r]]; i <= r; i++) a[i] += x, sum[bel[r]] += x; for (int i = bel[l] + 1; i < bel[r]; i++) tag[i] += x; } }
ll askSum(int l, int r){ ll res = 0; if (bel[l] == bel[r]) { for (int i = l; i <= r; i++) res += (a[i] + tag[bel[l]]); } else { for (int i = l; i <= ed[bel[l]]; i++) res += (a[i] + tag[bel[l]]); for (int i = st[bel[r]]; i <= r; i++) res += (a[i] + tag[bel[r]]); for (int i = bel[l] + 1; i < bel[r]; i++) res += (size[i] * tag[i] + sum[i]); } return res; }