# Python3 program to implement
# the above approach
import math
# Function to find the mid
# of start and end
def getMid(s,e):
return s + math.floor((e - s) / 2)
def updateValue(arr,st,ss,se,index,value,node):
# If index is out of range
if (index < ss or index > se):
print("Invalid Input")
return
# If a leaf node is found
if (ss == se):
# update value in array
arr[index] = value
# Update value in
# the segment tree
st[node] = value
else:
# Stores mid of ss and se
mid = getMid(ss, se)
# If index is less than or
# equal to mid
if (index >= ss and index <= mid):
# Recursively call for left subtree
updateValue(arr, st, ss, mid, index, value, 2 * node + 1)
else:
# Recursively call for right subtree
updateValue(arr, st, mid + 1, se, index, value, 2 * node + 2)
# Update st[node]
st[node] = max(st[2 * node + 1], st[2 * node + 2])
# Function to find the position of first element
# which is greater than or equal to X
def findMinimumIndex(st, ss, se, K, si):
# If no such element found in current
# subtree which is greater than or
# equal to K
if (st[si] < K):
return 1000000000
# If current node is leaf node
if (ss == se):
# If value of current node
# is greater than or equal to X
if (st[si] >= K):
return ss
return 1000000000
# Stores mid of ss and se
mid = getMid(ss, se)
l = 1000000000
# If root of left subtree is
# greater than or equal to K
if (st[2 * si + 1] >= K):
l = min(l, findMinimumIndex(st, ss, mid, K, 2 * si + 1))
# If no such array element is
# found in the left subtree
if (l == 1e9 and st[2 * si + 2] >= K):
l = min(l, findMinimumIndex(st, mid + 1, se, K, 2 * si + 2))
return l
# Function to build a segment tree
def Build(arr, ss, se, st, si):
# If current node is leaf node
if (ss == se):
st[si] = arr[ss]
return arr[ss]
# store mid of ss and se
mid = getMid(ss, se)
# Stores maximum of left subtree and rightsubtree
st[si] = max(Build(arr, ss, mid, st, si * 2 + 1), Build(arr, mid + 1, se, st, si * 2 + 2))
return st[si]
# Function to initialize a segment tree
# for the given array
def constructST(arr,n):
# Height of segment tree
x = math.ceil(math.log(n) / math.log(2))
# Maximum size of segment tree
max_size = 2 * pow(2, x) - 1
# Allocate memory
st = [0]*(max_size)
# Fill the allocated memory st
Build(arr, 0, n - 1, st, 0)
# Return the constructed segment tree
return st
def PerformQueries(arr, N, Q):
# Build segment tree for the given array
st = constructST(arr, N)
# Traverse the query array
for i in range(len(Q)):
# If query of type 1 found
if (Q[i][0] == 1):
updateValue(arr, st, 0, N - 1, Q[i][1] - 1, 5, 0)
else:
# Stores index of first array element
# which is greater than or equal
# to Q[i][1]
f = findMinimumIndex(st, 0, N - 1, Q[i][1], 0)
if (f < N):
print((f + 1 ), end = " ")
else:
print(-1, end = " ")
# Driver code
arr = [1, 3, 2, 4, 6 ]
Q= [[ 2, 5 ], [ 1, 3, 5 ], [2, 4 ], [ 2, 8 ]]
N = len(arr)
PerformQueries(arr, N, Q)
# This code is contributed by decode2207.