-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamic Segment Tree.cpp
110 lines (92 loc) · 2.02 KB
/
Dynamic Segment Tree.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
Solution to SPOJ problem - HORRIBLE
#include <bits/stdc++.h>
using namespace std;
using llint = long long;
#define np nullptr
struct Node
{
llint sum, lazy;
Node *c[2];
Node()
{
sum = lazy = 0;
c[0] = c[1] = np;
}
};
void pd(Node *x, int l, int r)
{
if (x != np && x->lazy)
{
if (l != r)
{
if (x->c[0] == np) x->c[0] = new Node;
if (x->c[1] == np) x->c[1] = new Node;
x->c[0]->lazy += x->lazy;
x->c[1]->lazy += x->lazy;
}
x->sum += (llint(r-l+1)*x->lazy);
x->lazy = 0;
}
}
inline llint sum(Node *&x)
{
return (x == np) ? 0:x->sum;
}
Node* Add(Node *root, int sl, int sr, int &l, int &r, int &v)
{
pd(root, sl, sr);
if (sl > r || sr < l) return root;
if (root == np) root = new Node;
if (sl >= l && sr <= r)
{
root->lazy = v;
pd(root, sl, sr);
return root;
}
int mid = (sl+sr)>>1;
root->c[0] = Add(root->c[0], sl, mid, l, r, v);
root->c[1] = Add(root->c[1], mid+1, sr, l, r, v);
root->sum = sum(root->c[0]) + sum(root->c[1]);
return root;
}
llint Query(Node *root, int sl, int sr, int &l, int &r)
{
if (root == np) return 0;
if (sl > r || sr < l) return 0;
pd(root, sl, sr);
int mid = (sl+sr)>>1;
if (sl >= l && sr <= r) return root->sum;
return Query(root->c[0], sl, mid, l, r) +
Query(root->c[1], mid+1, sr, l, r);
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int tc;
cin >> tc;
while (tc)
{
--tc;
int n, q;
cin >> n >> q;
Node *root = np;
while (q)
{
--q;
bool opt;
int a, b;
cin >> opt >> a >> b;
--a, --b;
if (opt)
cout << Query(root, 0, n-1, a, b) << '\n';
else
{
int v;
cin >> v;
root = Add(root, 0, n-1, a, b, v);
}
}
}
return 0;
}