线段树的应用
求一个区间的最大值
View Code
#include
#include <string.h>
#define N 2000001
int n , m , bbb;
struct t_node
{
int r , l , max;
}s[3*N];
void initial(int i , int a , int b)
{
int mid = (a+b)/2;
s[i].l = a;
s[i].r = b;
s[i].max = 0;
if(a == b)
return ;
else
{
initial(2*i,a,mid); //一个满二叉树在数组中,左儿子结点的下标是父节点的两倍
initial(2*i+1,mid+1,b); //右儿子是父节点的下标的两倍加一
}
}
void update(int i , int x , int y)
{
int mid;
if(s[i].l == x && s[i].r == x)
s[i].max == y;
else
{
mid = (s[i].l+s[i].r)/2;
if(x <= mid)
update(2*i,x,y);
else
update(2*i+1,x,y);
}
if(y > s[i].max)
s[i].max = y;
}
void find(int i , int a, int b)
{
int mid;
if(s[i].l == a && s[i].r == b)
{
if(bbb < s[i].max)
bbb = s[i].max;
}
else
{
mid = (s[i].l+s[i].r)/2;
if(a > mid) //分三种情况讨论
find(i*2+1,a,b); //按照mid的位置进行讨论
else if( b <= mid )
find(2*i,a,b);
else
{
find(i*2,a,mid);
find(i*2+1,mid+1,b);
}
}
}
int main()
{
int i , s , j , k;
char str[10];
while(scanf("%d %d",&n,&m) != EOF)
{
initial(1,1,n);
for( i = 1 ; i <= n ; i++ )
{
scanf("%d",&s);
update(1,i,s);
}
for( i = 1 ; i <= m ; i++ )
{
scanf("%s",str);
scanf("%d %d",&j,&k);
if(str[0] == 'Q')
{
bbb = 0 ;
find(1,j,k);
printf("%d\n",bbb);
}
if(str[0] == 'U')
{
update(1,j,k);
}
}
}
return 0;
}