Python 线段树

来源:互联网 发布:知乎专栏 kindle 推送 编辑:程序博客网 时间:2024/06/05 20:03



from math import powclass SegmentTree( object ):    def __init__( self, left, right ):        self.left = int( left )        self.right = int( right )        self.count = 0        self.left_son, self.right_son = None, None        if left < right:            mid = ( left + right ) >> 1            self.left_son = SegmentTree( left, mid )            self.right_son = SegmentTree( mid + 1, right )    def show_tree_struct( self ):        import Queue        Q = Queue.Queue( -1 )        print( 'Tree Struct ==> [left, right, count]' )        line = 1        Q.put( [self,line] )        while Q.empty() is False:            item = Q.get()            newline = False            if item[1] != line:                newline = True                line = item[1]            if newline:                print                print item[0],            else:                print item[0],            son_line = item[1] + 1            if item[0].left_son:                Q.put( [item[0].left_son, son_line] )            if item[0].right_son:                Q.put( [item[0].right_son, son_line] )            def insert( self, x, y ):        if x == self.left and y == self.right:            self.count += 1            return        if self.left == self.right: return        mid = ( self.left + self.right ) / 2        if mid < x:            self.right_son.insert( x, y )        elif mid >= y:            self.left_son.insert( x, y )        else:            self.left_son.insert( x, mid )            self.right_son.insert( mid + 1, y )    def query( self, x ):        total_count = 0        total_count += self.count        if self.left == self.right:            return total_count        mid = ( self.left + self.right ) / 2        if x <= mid:            total_count += self.left_son.query( x )        if x > mid:            total_count += self.right_son.query( x )        return total_count    def __str__( self ):        return '[%s,%s,%s]'%( self.left, self.right, self.count )


 

0 0