Topic Link: Click to open the link
Test instructions: interval addition and subtraction, interval summation.
This problem is a template problem of the interval increment and interval summation of the segment tree. As with interval modification values, a previous plus minus value is maintained on each node, so the current node must already have all the node information at each node.
The node message is sent before each recursion, which is called the lazy sign.
See the code for details:
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include < string> #include <vector> #include <stack> #include <bitset> #include <cstdlib> #include < cmath> #include <set> #include <list> #include <deque> #include <map> #include <queue> # Define MAX (a) > (b)? ( A):(B) #define MIN (a) < (b) (
A):(B)) using namespace Std;
typedef long Long LL;
Const double PI = ACOs (-1.0);
Const double EPS = 1e-6;
const int INF = 1000000000;
const int MAXN = 100000 + 10;
int t,n,l,r,q,v;
ll sum[maxn<<2],addv[maxn<<2];
Char s[10]; void push_up (int o) {Sum[o] = sum[o<<1] + sum[o<<1|1];} void build (int l, int r, int o) {int m = (l
+ R) >> 1;
Addv[o] = 0;
if (L = = r) {scanf ("%lld", &sum[o]);
return;
} build (L, M, o<<1);
Build (M+1, R, O<<1|1);
PUSH_UP (o); } void pushdown (int o, int l, int r) {if (Addv[o]) {int m = (L + r) >> 1;
ADDV[O<<1] + = Addv[o];
ADDV[O<<1|1] + = Addv[o];
Sum[o<<1] + = (ll) (m-l + 1) * Addv[o];
Sum[o<<1|1] + = (ll) (r-m) * Addv[o];
Addv[o] = 0;
}} void Update (int l, int r, int v, int l, int r, int o) {int m = (L + R) >> 1;
if (l <= l && R <= R) {Addv[o] + = V;
Sum[o] + = (ll) v * (r-l + 1);
return;
} pushdown (O, L, R);
if (l <= m) update (L, R, V, L, M, o<<1);
if (M < R) Update (L, R, V, M+1, R, O<<1|1);
PUSH_UP (o);
} ll query (int l, int r, int l, int r, int o) {int m = (L + R) >> 1;
if (l <= l && R <= R) {return sum[o];//The current node must already have all the marks} ll ans = 0;
Pushdown (O, L, R);
if (l <= m) ans + = query (l, R, L, M, o<<1);
if (M < r) ans + = query (L, R, M+1, R, O<<1|1);
PUSH_UP (o);
return ans; } int main () {while (~sCANF ("%d%d", &n,&q)) {build (1, N, 1);
while (q--) {scanf ("%s%d%d", S,&l,&r);
if (s[0] = = ' Q ') {printf ("%lld\n", query (L, R, 1, N, 1));
} else {scanf ("%d", &v);
Update (L, R, V, 1, N, 1);
}}} return 0;
}