线段树求区间最值

线段树求区间最值

入门级的线段树求区间最值,注释都在代码中了....

 #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <climits>
#include <queue> using namespace std; const int MAX = ;
struct nodes
{
int left,right,large;
}tree[MAX*]; int n,m,num[MAX]; int build(int root,int left,int right)//构建线段树
{
int mid;
tree[root].left = left;
tree[root].right = right;//当前区间
if(left == right)
return tree[root].large = num[left];//递归到最底层,把初始值赋值给当前节点 mid = (left+right)/;//划分成左右两个区间
int a,b;
a = build(*root,left,mid);//划分区间,左节点继续往下递归
b = build(*root+,mid+,right);//右节点向下递归 return tree[root].large = max(a,b);//返回当前区间最大值,并给当前节点赋值
} int find(int root ,int left,int right)//查找区间最值
{ if(tree[root].left > right || tree[root].right < left)//所查区间不在范围内,返回0
return ;
if(left <= tree[root].left && right >= tree[root].right)//刚好查到当前区间,返回区间最大值
return tree[root].large;
int a,b;
a = find(*root,left,right);//如果所查区间分布在划分区间的两边,则分开查找最大值
b = find(*root+,left,right);
return max(a,b);//比较返回最大值
} int update(int root,int pos,int val)//更新区间最值
{
if(pos <tree[root].left || pos > tree[root].right)
return tree[root].large;
if(pos == tree[root].left && pos == tree[root].right)//递归到需要修改的位置,修改节点值并返回
return tree[root].large = val; int a,b;
a = update(*root,pos,val); //递归向下修改左节点值,并返回修改后的区间最值
b = update(*root+,pos,val);//递归向下修改右节点值,并返回修改后的区间最值
tree[root].large = max(a,b); //更新节点最大值
return tree[root].large;//返回当前节点最大值
} int main(void)
{
int m,n,i,x,y;
char ch;
while(scanf("%d %d",&n,&m) != -)
{
for(i = ; i <= n; i++)
scanf("%d",&num[i]);
build(,,n);
for(i = ; i < m; i++)
{
getchar();
scanf("%c",&ch);
scanf("%d %d",&x,&y);
if(ch == 'Q')
printf("%d\n",find(,x,y));
else
{
num[x] = y;
update(,x,y);
}
}
}
return ;
}
04-21 02:49