-
Notifications
You must be signed in to change notification settings - Fork 10
/
mergesorttree.sublime-snippet
executable file
·51 lines (51 loc) · 1.73 KB
/
mergesorttree.sublime-snippet
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
<snippet>
<content><![CDATA[
const int MAX = 1e5 + 5;
const int LIM = 3e5 + 5; //equals 2 * 2^ceil(log2(n))
int a[MAX];
vector<int> seg[LIM];
//Complexity : O(n logn)
void build(int t, int i, int j) {
seg[t].clear();
if (i == j) {
seg[t].push_back(a[i]);
return ;
}
int left = t << 1, right = left | 1;
int mid = (i + j) / 2;
build(left, i, mid);
build(right, mid+1, j);
merge(seg[left].begin(), seg[left].end(), seg[right].begin(), seg[right].end(), back_inserter(seg[t]));
}
//Returns count of i, A[i] <= val, l <= i <= r
//Complexity : O(log^2 n)
int query1(int t, int i, int j, int l, int r, int val) {
if (i > r || j < l) return 0;
if (l <= i && j <= r) {
int pos = upper_bound(seg[t].begin(), seg[t].end(), val) - seg[t].begin();
return pos;
}
int left = t << 1, right = left | 1;
int mid = (i + j) / 2;
return query1(left, i, mid, l, r, val) + query1(right, mid+1, j, l, r, val);
}
//Returns count of i, A[i] >= val, l <= i <= r
//Complexity : O(log^2 n)
int query2(int t, int i, int j, int l, int r, int val) {
if (i > r || j < l) return 0;
if (l <= i && j <= r) {
int pos = lower_bound(seg[t].begin(), seg[t].end(), val) - seg[t].begin();
return (int)seg[t].size() - pos;
}
int left = t << 1, right = left | 1;
int mid = (i + j) / 2;
return query2(left, i, mid, l, r, val) + query2(right, mid+1, j, l, r, val);
}
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>mergesorttree</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<scope>source.cpp, source.c++, source.c</scope>
<!-- Optional: Description to show in the menu -->
<description>Merge Sort Segment Tree</description>
</snippet>