aboutsummaryrefslogtreecommitdiff
path: root/segmenttree.c
blob: 449f8e75a00f8df851fcb2a8811b6c48133f5baa (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
47
48
#include <sqlite3.h>

int * seg;

/* Build segment tree */
void build(sqlite3_stmt *stmt, int l, int r, int n) {
	if (l == r) {
		sqlite3_step(stmt);
		seg[n] = sqlite3_column_int(stmt, 0);
		return;
	}
	int m = l + r >> 1;
	build(stmt, l, m, n << 1);
	build(stmt, 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 */
void query(int *res, int v, int l, int r, int n) {
	if (l == r) {
		res[0] = seg[n];
		res[1] = l;
		return;
	}
	int m = l + r >> 1;
	if (seg[n << 1] >= v) {
		query(res, v, l, m, n << 1);
	}
	else {
		query(res, v - seg[n << 1], m + 1, r, n << 1 | 1);
	}
}