-
Notifications
You must be signed in to change notification settings - Fork 2
/
segment_tree_rmq.cpp
83 lines (77 loc) · 1.65 KB
/
segment_tree_rmq.cpp
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
//segment tree
//range minimum query
//utube video
#include<bits/stdc++.h>
using namespace std;
#define inf 1000000000
int a[10000];
int seg[20000];
int x,y;
int getsize(int n)
{
int s=1;
for(;s<n;s<<=1);
return s<<1;
}
void create_tree(int low,int high,int pos)
{
if(low==high)
{
seg[pos]=a[low];
cout<<pos<<" "<<low<<endl;
return;
}
int mid=(low+high)/2;
create_tree(low,mid,2*pos+1);
create_tree(mid+1,high,2*pos+2);
seg[pos]=min(seg[2*pos+1],seg[2*pos+2]);
}
int rmq(int low,int high,int pos,int x,int y)
{
if(x>high||y<low)
return inf;
else if(x<=low&&y>=high)
return seg[pos];
int mid=(low+high)/2;
return min(rmq(low,mid,2*pos+1,x,y),rmq(mid+1,high,2*pos+2,x,y));
}
void update(int low,int high,int val,int pla,int pos)
{
if(low==high)
{
seg[pos]=val;
return ;
}
int mid=(low+high)/2;
if(pla<=mid)
{
update(low,mid,val,pla,2*pos+1);
seg[pos]=min(seg[2*pos+1],seg[2*pos+2]);
}
else
{
update(mid+1,high,val,pla,2*pos+2);
seg[pos]=min(seg[2*pos+1],seg[2*pos+2]);
}
}
int main()
{
int n,i,q,ch;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
create_tree(0,n-1,0);
for(i=0;i<getsize(n);i++)
printf("%d ",seg[i]);
printf("\n");
scanf("%d",&q);
while(q--)
{
scanf("%d%d%d",&ch,&x,&y);
if(ch==1) //ch == print min
printf("%d\n",rmq(0,n-1,0));
else //update for ch==2 x is new value
update(0,n-1,x,y,0);
}
return 0;
}