16.线段树
1.建树
const int maxn= 100005 ;
typedef struct
{
int l, r, sums;
} node;
node tree[ maxn] ;
inline void build ( int i, int l, int r)
{
tree[ i] . l= l, tree[ i] . r= r;
if ( l== r)
{
tree[ i] . sums= input[ l] ;
return ;
}
int mid= ( l+ r) >> 1 ;
build ( 2 * i, l, mid) ;
build ( 2 * i+ 1 , mid+ 1 , r) ;
tree[ i] . sums= tree[ 2 * i] . sums+ tree[ 2 * i+ 1 ] . sums;
}
2.单点修改,区间查询
inline int search ( int i, int l, int r)
{
if ( tree[ i] . l>= l&& tree[ i] . r<= r)
return tree[ i] . sums;
int s= 0 ;
if ( tree[ 2 * i] . r>= l) s+ = search ( 2 * i, l, tree[ 2 * i] . r) ;
if ( tree[ 2 * i+ 1 ] . l<= r) s+ = search ( 2 * i+ 1 , trss[ 2 * i+ 1 ] . l, r) ;
return s;
}
inline void update ( int i, int k, int dis)
{
if ( tree[ i] . r== tree[ i] . l) {
tree[ i] . sums+ = k;
}
if ( dis<= tree[ 2 * i] . r) add ( i* 2 , k, dis)
else add ( i* 2 + 1 , k, dis) ;
tree[ i] . sums= tree[ i* 2 ] . sums+ tree[ i* 2 + 1 ] . sums;
return ;
}
3.区间修改,单点查询
inline void add ( int i, int l, int r)
{
if ( tree[ i] . l>= l&& tree[ i] . r<= r)
{
tree[ i] . sums+ = k;
return ;
}
int s= 0 ;
if ( tree[ 2 * i] . r>= l) add ( 2 * i, l, tree[ 2 * i] . r) ;
if ( tree[ 2 * i+ 1 ] . l<= r) add ( 2 * i+ 1 , trss[ 2 * i+ 1 ] . l, r) ;
}
void search ( int i, int dis) {
ans+ = tree[ i] . num;
if ( tree[ i] . l== tree[ i] . r)
return ;
if ( dis<= tree[ i* 2 ] . r)
search ( i* 2 , dis) ;
if ( dis>= tree[ i* 2 + 1 ] . l)
search ( i* 2 + 1 , dis) ;
}
4.区间修改,区间查询
void pushdown ( int x)
{
if ( a[ x] . lz!= 0 )
{
a[ 2 * x] . lz+ = a[ x] . lz;
a[ 2 * x+ 1 ] . lz+ = a[ x] . lz;
int mid= ( a[ x] . r+ a[ x] . l) >> 1 ;
a[ 2 * x] . sums+ = a[ x] . lz* ( mid- a[ 2 * x] . l+ 1 ) ;
a[ 2 * x+ 1 ] . sums+ = a[ x] . lz* ( a[ 2 * x+ 1 ] . r- mid) ;
a[ x] . lz= 0 ;
}
return ;
}
void update ( int i, ll k, int l, int r)
{
if ( l<= a[ i] . l&& a[ i] . r<= r)
{
a[ i] . sums+ = k* ( a[ i] . r- a[ i] . l+ 1 ) ;
a[ i] . lz+ = k;
return ;
}
pushdown ( i) ;
if ( a[ 2 * i] . r>= l) update ( 2 * i, k, l, r) ;
if ( a[ 2 * i+ 1 ] . l<= r) update ( 2 * i+ 1 , k, l, r) ;
a[ i] . sums= a[ 2 * i] . sums+ a[ 2 * i+ 1 ] . sums;
return ;
}
ll getsum ( int i, int l, int r)
{
if ( a[ i] . l>= l&& a[ i] . r<= r)
{
return a[ i] . sums;
}
ll res= 0 ;
pushdown ( i) ;
if ( a[ 2 * i] . r>= l) res+ = getsum ( 2 * i, l, r) ;
if ( a[ 2 * i+ 1 ] . l<= r) res+ = getsum ( 2 * i+ 1 , l, r) ;
return res;
}