HDU 1754 I Hate It

这是一道简单的入门的线段树的题目:

#include<cstdio>
#include<iostream>
#include<cstdlib>
using namespace std;
class Node
{
public:
int l,r,mid;
int max,count;
};
Node tree[800024];
int num[200024];
class Tree
{
public:
int Max( int a,int b )
{ return a>b?a:b; }
int Qestion( int l,int r,int cnt );
void Maketree( int l,int r,int cnt );
void Change( int n,int m,int cnt );
};
void Tree::Change( int n,int m,int cnt )
{
tree[cnt].max =Max(tree[cnt].max,m);
if( tree[cnt].l==n&&tree[cnt].r==n )
{
tree[cnt].count =tree[cnt].max= m;
return;
}
else
{
if( n > tree[cnt].mid )
Change( n,m,cnt*2+1 );
else Change( n , m ,cnt*2 );
}
}
void Tree::Maketree(int l,int r,int cnt)
{
if( l == r )
{
tree[cnt].l=tree[cnt].r=tree[cnt].mid=l;
tree[cnt].count=num[l];
tree[cnt].max = num[l];

return ;
}
else
{
tree[cnt].mid = ( l+r )>>1;
tree[cnt].l = l;
tree[cnt].r = r;
Maketree( l , tree[cnt].mid ,cnt*2 );
Maketree( tree[cnt].mid +1 , r, cnt*2+1 );
tree[cnt].max = Max( tree[cnt*2].max , tree[cnt*2+1].max ) ;
}
}
int Tree::Qestion(int l,int r,int cnt)
{
if( tree[cnt].l==l&&tree[cnt].r==r )
{
return tree[cnt].max;
}
else
{
if( l>tree[cnt].mid )
return Qestion( l , r , cnt*2+1 );
else if( r <= tree[cnt].mid )
return Qestion( l , r , cnt*2 );
else
return Max(Qestion( l , tree[cnt].mid , cnt*2 ),Qestion( tree[cnt].mid+1 , r , cnt*2+1 ));
}
}
int main( )
{
int n,m,l,r;
char c[10];
while( scanf( "%d%d",&n,&m )==2 )
{
Tree e;
for( int i=1; i<= n; i++ )
scanf( "%d",&num[i] );
e.Maketree( 1 , n ,1 );
for( int i=1; i<=m; i++ )
{
scanf( "%s%d%d",c , &l ,&r );
if( c[0]=='Q' )
printf( "%d\n",e.Qestion( l,r,1 ) );
else e.Change( l ,r, 1 );
}
}
return 0;
}

 

你可能感兴趣的:(HDU)