线段树维护最大值

题意如题面

#include
#include
#include
#include
using namespace std;
#define N 200005
int n,m;
int t[4*N],d[N];
void up(int x)
{
	t[x] = max(t[x * 2],t[x * 2 + 1]); 
}
void build(int x,int l,int r)
{
	if(l == r)
	{
		t[x] = d[l];
		return;
	}
	int mid = (l + r)/2;
	build(x * 2,l,mid);
	build(x * 2 + 1,mid + 1,r);
	up(x);
}
void change(int x,int l,int r,int k,int v)
{
	if(l == r)
	{
		t[x] = v;
		return ;
	}
	int mid = (l + r) / 2;
	if(k <= mid)change(x * 2,l,mid,k,v);
	else change(x * 2 + 1,mid + 1,r,k,v);
	up(x);
}
int ans(int x,int l,int r,int k,int y)
{
	if(k <= l && r <= y)return t[x];
	int maxn = 0;
	int mid = (l + r)/2;
	if(k <= mid)maxn = max(maxn,ans(x * 2,l,mid,k,y));
	if(y > mid)maxn = max(maxn,ans(x * 2 + 1,mid + 1,r,k,y));
	return maxn;
}
int main()
{
	scanf("%d%d",&n,&m);
	for(int i = 1;i <= n;i++)scanf("%d",&d[i]);
	build(1,1,n);
	while(m--)
	{
		int a,b,c; 
		scanf("%d%d%d",&a,&b,&c);
		if(a == 1)printf("%d\n",ans(1,1,n,b,c));
		else change(1,1,n,b,c);
	}
	return 0;
} 
/*
4 3
1 2 3 4
1 1 2
2 1 5
1 1 2
*/

 

你可能感兴趣的:(线段树)