forked from 13toast/moban
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSegment Tree.cpp
More file actions
90 lines (85 loc) · 1.81 KB
/
Copy pathSegment Tree.cpp
File metadata and controls
90 lines (85 loc) · 1.81 KB
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
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#define rep(i,a,b) for (int i=a;i<=b;++i)
#define per(i,a,b) for (int i=a;i>=b;--i)
#define mst(a,b) memset(a,b,sizeof(a))
typedef long long ll;
typedef double db;
using namespace std;
const int MAXN = 1e5+5;
int n,m;
ll a[MAXN];
struct segment_tree {
#define ls id<<1
#define rs id<<1|1
struct node {
ll sum, lazy;
}tr[4*MAXN];
void Update(int id) {
tr[id].sum = tr[ls].sum + tr[rs].sum;
}
void pushdown(int id,int l,int r) {
int mid = (l+r)/2;
if (tr[id].lazy) {
tr[ls].sum += tr[id].lazy*(mid-l+1); tr[ls].lazy += tr[id].lazy;
tr[rs].sum += tr[id].lazy*(r-mid); tr[rs].lazy += tr[id].lazy;
tr[id].lazy = 0;
}
}
void BuildTree(int id,int l,int r) {
tr[id].lazy = 0;
if (l == r) {
tr[id].sum = a[l];
return;
}
int mid = (l+r) >> 1;
BuildTree(ls,l,mid); BuildTree(rs,mid+1,r);
Update(id);
}
void Change(int id,int l,int r,int cl,int cr,int k) {
if (cl <= l && r <= cr) {
tr[id].lazy += k;
tr[id].sum += (r-l+1)*k;
return;
}
pushdown(id,l,r);
int mid = (l+r) >> 1;
if (cl <= mid) Change(ls,l,mid,cl,cr,k);
if (cr > mid) Change(rs,mid+1,r,cl,cr,k);
Update(id);
}
ll Query(int id,int l,int r,int ql,int qr) {
if (ql <= l && r <= qr) {
return tr[id].sum;
}
pushdown(id,l,r);
int mid = (l+r) >> 1;
ll ret = 0;
if (ql <= mid) ret += Query(ls,l,mid,ql,qr);
if (qr > mid) ret += Query(rs,mid+1,r,ql,qr);
return ret;
}
#undef ls
#undef rs
}sgt;
int main() {
cin >> n >> m;
rep(i,1,n) scanf("%lld",&a[i]);
sgt.BuildTree(1,1,n);
rep(i,1,m) {
int ty; scanf("%d",&ty);
int x,y;ll k;
if (ty == 1) {
scanf("%d%d%lld",&x,&y,&k);
sgt.Change(1,1,n,x,y,k);
}
else {
scanf("%d%d",&x,&y);
printf("%lld\n",sgt.Query(1,1,n,x,y));
}
}
return 0;
}