码迷,mamicode.com
首页 > 其他好文 > 详细

线段树板子

时间:2018-02-05 14:18:47      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:uil   query   val   col   can   round   while   div   gpo   

# 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 ) ;
		}
	}
}

  

线段树板子

标签:uil   query   val   col   can   round   while   div   gpo   

原文地址:https://www.cnblogs.com/ganster/p/8416856.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!