线段树板子

Posted ganster

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线段树板子相关的知识,希望对你有一定的参考价值。

# include <cstdio>
# include <algorithm>

# define N 100010

int a [N] ;
int vmax [N << 2] ;

void build ( int o, int lf, int rg )  {
	if ( lf == rg )  {
		vmax [o] = a [lf] ;
		return ;
	}

	int mid = ( lf + rg ) >> 1 ;
	build ( o * 2, lf, mid ) ;
	build ( o * 2 + 1,  mid + 1, rg ) ;
	
	vmax [o] = std :: max ( vmax [o * 2], vmax [o * 2 + 1] ) ;
}

int query ( int o, int lf, int rg, const int L, const int R )  {
	if ( L <= lf && rg <= R )  {
		return vmax [o] ;
	}
	int mid = ( lf + rg ) >> 1 ;
	int rt = -0x3f3f3f3f ;
	if ( L <= mid )  rt = std :: max ( rt, query ( o * 2, lf, mid, L, R ) ) ;
	if ( R > mid )  rt = std :: max ( rt, query ( o * 2 + 1, mid + 1, rg, L, R ) ) ;
	return rt ;
}

void modify ( int o, int lf, int rg, const int pos, const int val )  {
	if ( lf == rg )  {
		vmax [o] = val ;
		return ;
	}
	int mid = ( lf + rg ) >> 1 ;
	if ( pos <= mid )  modify ( o * 2, lf, mid, pos, val ) ;
	if ( pos > mid )  modify ( o * 2 + 1, mid + 1, rg, pos, val ) ;
	
	vmax [o] = std :: max ( vmax [o * 2], vmax [o * 2 + 1] ) ;
}

int main ( )  {
	int n ;
	scanf ( "%d", & n ) ;
	for ( int i = 1 ; i <= n ; ++ i )  scanf ( "%d", a + i ) ;
	
	build ( 1, 1, n ) ;
	int m ;
	scanf ( "%d", & m ) ;
	while ( m -- )  {
		int opt ;
		scanf ( "%d", & opt ) ;
		if ( opt == 0 )  {
			int l, r ;
			scanf ( "%d%d", & l, & r ) ;
			printf ( "%d\n", query ( 1, 1, n, l, r ) ) ;
		}  else  {
			int pos, val ;
			scanf ( "%d%d", & pos, & val ) ;
			modify ( 1, 1, n, pos, val ) ;
		}
	}
}

  

以上是关于线段树板子的主要内容,如果未能解决你的问题,请参考以下文章

线段树1板子

线段树板子

7.8集训模拟赛(忘记板子)

权值线段树板子题

线段树二分板子

poj2777(线段树)