开发者

Segment tree implementation in Python

开发者 https://www.devze.com 2023-04-04 10:04 出处:网络
I am trying to code new data structures I learn in Python, and the following function is part of segment tree.

I am trying to code new data structures I learn in Python, and the following function is part of segment tree.

def query(root,interval,xy=ref_ll([False,False])):
    print interval,root
    if root.interval == interval or point(root.interval):
        return root.quadrant.reflect(root.xy * xy) #Is always gonna be of the form [a,b,c,d]
    a = q_list([0,0,0,0])
    if interval[0] < root.r.interval[0]:
        a = query(root.l,[interval[0],min(interval[1],root.l.interval[1])],root.xy * xy)
    if interval[1] > root.l.interval[1]:
        a = query(root.r,[max(interval[0],root.r.interval[0]), interval[1]],root.xy * xy)
    return a

I am expecting this to run in O(h) time (h is the height of the tree), but it does not, can someone point out the mistake I did. Thanks.

EDIT For an idea of the segment tree, look at http://community.topcoder.com/i/education/lca/RMQ_004.gif

The function's termination condition is if the interval is form of (1,1), i.e. it is a point and not a range. All the functions are implemented.开发者_StackOverflow Working Input: http://pastebin.com/LuisyYCY

Here is the whole code. http://pastebin.com/6kgtVWAq


It's probably because you are extending a list for every level of the tree. The average time complexity of extending a list is O(k) where k is the size of the list on the right hand side. The size of the list on the right hand side is O(h) so the average overall time complexity is then O(h2).

0

精彩评论

暂无评论...
验证码 换一张
取 消