Skip to content

Commit 69e04d4

Browse files
Merge pull request matthewsamuel95#919 from Es7evam/ImplicitSegTree
Add Implicit Segment Tree C++ code
2 parents 802df54 + f0c3ae4 commit 69e04d4

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
#define pb push_back
6+
#define mk make_pair
7+
#define fi first
8+
#define se second
9+
10+
typedef long long ll;
11+
typedef pair<int, int> ii;
12+
const int INF = 0x3f3f3f3f;
13+
const double PI = acos(-1.0);
14+
15+
struct node {
16+
node *l, *r;
17+
ll val, lazy;
18+
19+
node () {
20+
l = r = 0;
21+
val = lazy = 0;
22+
}
23+
};
24+
25+
void prop (node *at, int i, int j) {
26+
at->val += at->lazy * (j - i + 1);
27+
28+
if (i != j) {
29+
if (!at->l) at->l = new node();
30+
if (!at->r) at->r = new node();
31+
32+
at->l->lazy += at->lazy;
33+
at->r->lazy += at->lazy;
34+
}
35+
36+
at->lazy = 0;
37+
}
38+
39+
ll query (node *at, int i, int j, int a, int b, int val) {
40+
prop (at, i, j);
41+
if (j < a or i > b) return 0;
42+
43+
if (i >= a and j <= b) {
44+
at->lazy += val;
45+
prop (at, i, j);
46+
return at->val;
47+
} else {
48+
int mid = (i + j)>>1;
49+
50+
if (!at->l) at->l = new node();
51+
if (!at->r) at->r = new node();
52+
53+
ll L = query (at->l, i, mid, a, b, val);
54+
ll R = query (at->r, mid + 1, j, a, b, val);
55+
at->val = at->l->val + at->r->val;
56+
return L + R;
57+
}
58+
}
59+
60+
int main (void) {
61+
ios_base::sync_with_stdio(false);
62+
63+
int T; cin >> T;
64+
while (T--) {
65+
node *root = new node();
66+
67+
int n, q; cin >> n >> q;
68+
69+
while (q--) {
70+
int c, l, r; cin >> c >> l >> r;
71+
l--; r--;
72+
if (l > r) swap (l, r);
73+
if (c == 0) {
74+
int v; cin >> v;
75+
query (root, 0, n - 1, l, r, v);
76+
} else {
77+
cout << query (root, 0, n - 1, l, r, 0) << endl;
78+
}
79+
}
80+
}
81+
82+
return 0;
83+
}

0 commit comments

Comments
 (0)