-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSegment tree basic
More file actions
96 lines (84 loc) · 1.4 KB
/
Copy pathSegment tree basic
File metadata and controls
96 lines (84 loc) · 1.4 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// querying and finding min value;
//1
//7
//1 2 0 3 4 1 2
//3
//0 3
//1 4
//4 6
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define F first
#define S second
#define ii pair<int,int>
#define endl "\n"
#define mod 1000000007
#define all(v) (v).begin(),(v).end()
#define SQ(a) (a)*(a)
#define MP make_pair
const int inf = 1e9 + 7;
void build(int ind, int low , int high, int arr[], int seg[])
{
if(low==high)
{
seg[ind] = arr[low];
return;
}
int mid = (low+high)/2;
build(2*ind+1,low,mid,arr,seg);
build(2*ind+2,mid+1,high,arr,seg);
seg[ind]= min(seg[2*ind+1],seg[2*ind+2]);
}
int query(int ind,int low,int high, int l,int r,int seg[])
{
// no overlap
// l r low high or low high l r
if(r<low || high< l)
{
return INT_MAX;
}
//complete overlap
//l low high r
if(low>=l && high<=r)
{
return seg[ind];
}
// partial overlap
int mid = (low+high)/2;
int left = query(2*ind+1,low,mid,l,r,seg);
int right = query(2*ind+2,mid+1,high,l,r,seg);
return min(left,right);
}
void solve()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int seg[4 * n];
build(0,0,n-1,arr,seg);
int q;
cin>>q;
while(q--)
{
int l, r;
cin>>l>>r;
cout<<query(0,0,n-1,l,r,seg)<<endl;
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
ll t;
cin>>t;
while(t--)
{
solve();
}
}