from math import pow
class 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 )
版权声明:本文为u011659057原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。