aboutsummaryrefslogtreecommitdiff
path: root/segmenttree.c
blob: 1bf0fcd85a761e0fd185867281e2053e983e495a (plain)
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
struct SegmentTree {
	int N;
	int * seg;
}

// Build segment tree
void Build(int l, int r, int n) {
	if (l == r) {
	
	}
	int m = l + r >> 1;
	Build(l, m, n << 1);
	Build(m + 1, r, n << 1 | 1);
	seg[n] = seg[n << 1] + seg[n << 1 | 1];
}

// Update value at index x
void Update(int x, int v, int l, int r, int n) {
	if (l == r) {
		seg[n] += v;
		return;
	}
	int m = l + r >> 1;
	if (x <= m) {
		Update(x, v, l, m, n<<1);
	}
	else {
		Update(x, v, m+1, r, n<<1|1);
	}
	seg[n] = seg[n << 1] + seg[n << 1 | 1];
}

// Find element with prefix sum v
int Query(int v, int l, int r, int n) {
	if (l == r) {
		return s.seg[n], l;
	}
	int m = l + r >> 1;
	if (seg[n << 1] >= v) {
		return Query(v, l, m, n << 1);
	}
	else {
		return Query(v - s.seg[n << 1], m + 1, r, n << 1 | 1);
	}
}