-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsegmentTree.cpp
More file actions
68 lines (52 loc) · 1.08 KB
/
segmentTree.cpp
File metadata and controls
68 lines (52 loc) · 1.08 KB
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
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
class SegmentTree {
public:
typedef int dtype;
vector <dtype> tree;
int s;
SegmentTree(int n) {
for (s = 1; s < n; s *= 2) {}
tree.resize(s * 2);
for (int i = 1; i < s * 2; i++) tree[i] = numeric_limits<dtype>::max();
}
void insert(vector <dtype> &d) {
for (int i = s; i < s + d.size(); i++)
tree[i] = d[i - s];
for (int i = s - 1; i >= 1; i--)
tree[i] = min(tree[i * 2], tree[i * 2 + 1]);
}
dtype getMin(int Left, int Right) {
int l = Left + s - 1, r = Right + s - 1;
dtype rval = numeric_limits<dtype>::max();
while (l <= r) {
if (l % 2 == 0) l /= 2;
else {
rval = min(rval, tree[l]);
l = (l / 2) + 1;
}
if (r % 2 == 1) r /= 2;
else {
rval = min(rval, tree[r]);
r = (r / 2) - 1;
}
}
return rval;
}
};
int main() {
int n, m;
cin >> n;
SegmentTree t(n);
vector <int> v(n);
for (int i = 0; i < n; i++) cin >> v[i];
t.insert(v);
cin >> m;
while (m--) {
int a, b; cin >> a >> b;
cout << t.getMin(a, b) << endl;
}
}