I am solving this problem using segment tree but I get time limit error.
Below is my raw code for range minimum query and by changing min
to max
in my code the above problem can be solved . I don't know how I can improve the performance of my code. Can you help me with its performance issues ?
t = [None] * 2 * 7 # n is length of list
def build(a, v, start, end):
'''
A recursive function that constructs Segment Tree for list a.
v is the starting node
start and end are the index of array
'''
n = len(a)
if start == end:
t[v] = a[start]
else:
mid = (start + end) / 2
build(a, v * 2, start, mid) # v*2 is left child of parent v
# v*2+1 is the right child of parent v
build(a, v * 2 + 1, mid + 1, end)
t[v] = min(t[2 * v], t[2 * v + 1])
return t
print build([18, 17, 13, 19, 15, 11, 20], 1, 0, 6)
inf = 10**9 + 7
def range_minimum_query(node, segx, segy, qx, qy):
'''
returns the minimum number in range(qx,qy)
segx and segy represent the segment index
'''
if qx > segy or qy < segx: # query out of range
return inf
elif segx >= qx and segy <= qy: # query range inside segment range
return t[node]
else:
return min(range_minimum_query(node * 2, segx, (segx + segy) / 2, qx, qy), range_minimum_query(node * 2 + 1, ((segx + segy) / 2) + 1, segy, qx, qy))
print range_minimum_query(1, 1, 7, 1, 3)
# returns 13
Can this be implemented iteratively ?
can you help me with [the code's] performance issues?
Do you want hints to solve the problem yourself, or do you want analysed & coded solutions? Where dosegment
s come into the picture? (Did you read the description of the segment tag?) (upvoted for supplying docstrings - consider renamingrmq
to reflect range minimum query out of this context.) My 2cents: Your problem is not recursive vs. iterative. – Recaptionsorry for that
- I take it you know how to edit tags.) Anybody heard of a priority search tree? – Recaptionsegment-tree
, you might get doubts expressed whetherbuild()
does build a segment tree: it is more usual to have explicit coordinates for the boundaries of the atomic intervals than any valid index, and to have segments of the set overlap . Your choice to haveend
inclusive seems unconventional, and the commentquery range inside segment range
backwards. (I have no idea why your code should be more than a factor of, say, two from optimum.) – Recaptionlist
witharray.array
– Behindhand