-
Notifications
You must be signed in to change notification settings - Fork 28
/
horrible.cpp
125 lines (119 loc) · 2.65 KB
/
horrible.cpp
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
#include <iostream>
#include <string.h>
#define ll long long
#define SIZE 100001
using namespace std;
ll a[SIZE],segTree[4*SIZE+1],lazy[4*SIZE+1];
void constructSegTree(ll low,ll high,ll pos)
{
if(low>high)
{
return;
}
if(low==high)
{
segTree[pos]=a[low];
return;
}
ll mid=(low+high)/2;
constructSegTree(low,mid,2*pos+1);
constructSegTree(mid+1,high,2*pos+2);
segTree[pos]=segTree[2*pos+1]+segTree[2*pos+2];
}
ll queryLazy(ll qlow,ll qhigh,ll low,ll high,ll pos)
{
if(low>high)
{
return 0;
}
if(lazy[pos]!=0)
{
segTree[pos]+=(high-low+1)*lazy[pos];
if(low!=high) //Not a leaf node
{
lazy[2*pos+1]+=lazy[pos];
lazy[2*pos+2]+=lazy[pos];
}
lazy[pos]=0;
}
//No overlap
if(qlow>high||qhigh<low)
{
return 0;
}
//Total overlap
if(qlow<=low&&qhigh>=high)
{
return segTree[pos];
}
//Partial overlap
ll mid=(low+high)/2;
return queryLazy(qlow,qhigh,low,mid,2*pos+1)+queryLazy(qlow,qhigh,mid+1,high,2*pos+2);
}
void updateRangeLazy(ll startRange,ll endRange,ll delta,ll low,ll high,ll pos)
{
if(low>high)
{
return;
}
if(lazy[pos]!=0)
{
segTree[pos]+=(high-low+1)*lazy[pos];
if(low!=high)
{
lazy[2*pos+1]+=lazy[pos];
lazy[2*pos+2]+=lazy[pos];
}
lazy[pos]=0;
}
//No overlap
if(startRange>high||endRange<low)
{
return;
}
//Total overlap
if(startRange<=low&&endRange>=high)
{
segTree[pos]+=(high-low+1)*delta;
if(low!=high)
{
lazy[2*pos+1]+=delta;
lazy[2*pos+2]+=delta;
}
return;
}
//Partial overlap
ll mid=(low+high)/2;
updateRangeLazy(startRange,endRange,delta,low,mid,2*pos+1);
updateRangeLazy(startRange,endRange,delta,mid+1,high,2*pos+2);
segTree[pos]=segTree[2*pos+1]+segTree[2*pos+2];
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n,c;
cin>>n>>c;
memset(a,0,sizeof a);
memset(segTree,0,sizeof segTree);
memset(lazy,0,sizeof lazy);
ll op,p,q,v;
while(c--)
{
cin>>op;
if(op==1)
{
cin>>p>>q;
cout<<queryLazy(p-1,q-1,0,n-1,0)<<endl;
}
else
{
cin>>p>>q>>v;
updateRangeLazy(p-1,q-1,v,0,n-1,0);
}
}
}
return 0;
}