标签:
建线段树:
1 void build ( int o , int l , int r ) 2 { 3 if ( l == r ) { 4 sum[o] = a[l] ;//也能写成sum[l] = a[l] 或 sum[r] = a[l] ; 5 return ; 6 } 7 int mid = ( l + r ) >> 1 ; 8 build ( o << 1 , l , mid ) ; 9 build ( o << 1 | 1 , mid + 1 , r ) ; 10 11 sum[o] = sum[o << 1] + sum[o << 1 | 1] ; //存储区间和 12 13 //sum[o] = max ( sum[o << 1] , sum[o << 1 | 1] ) ;//存储区间最大值 14 }
查找范围:
1 int ql , qr ; //查找[ ql , qr ] 范围 , 你在主函数里赋值 2 3 int query ( int 0 , int l ,int r ) 4 { 5 if ( ql <= l && qr >= r ) { 6 return sum[o] ; 7 } 8 int mid = ( l + r ) >> 1 ; 9 int ans = 0 ; 10 if ( ql <= l ) { 11 ans += query( o << 1 , l , mid ) ; 12 } 13 if ( qr > r ) { 14 ans += query ( o << 1 | 1 , mid + 1 , r ) ; 15 } 16 return ans ; 17 }
跟新:
1 int x , v ; //把sum[x]跟新为v 2 3 void update (int 0 , int l , int r ) 4 { 5 if ( l == r ) { 6 sum[o] = v ; 7 return; 8 } 9 int mid = ( l + r ) >> 1 ; 10 if ( x <= mid ) { 11 update ( o << 1 , l , mid ) ; 12 } 13 else { 14 update ( o << 1 , mid + 1 , r ) ; 15 } 16 sum[o] = sum[o << 1] + sum[o << 1 | 1] ; 17 }
标签:
原文地址:http://www.cnblogs.com/get-an-AC-everyday/p/4274463.html