hdu1754线段树

#include "iostream"
#include <cstdio>
#define MAX 200005
#define lc(x) ((x)<<1)
#define rc(x) (((x)<<1)+1)
using namespace std;
struct node
{
 int l,r,m;
};
int score[MAX];
node tree[MAX*3];
int N,M,p,q;
char cmd[2];

int mmax(int x,int y)
{
 return x>y? x:y;
}

int build(int l,int r,int i)//从下到上建树
{
 tree[i].l=l;
 tree[i].r=r;
 if(l==r)
 {
  tree[i].m=score[l];
  return 0;
 }
 int mid=(l+r)>>1;
 build(l,mid,lc(i));//左儿子节点
 build(mid+1,r,rc(i));//右儿子节点
 tree[i].m=mmax(tree[lc(i)].m,tree[rc(i)].m);//父亲节点是其左右儿子中的大的
 return 0;
}

int renew(int i ,int num, int newv)//从下向上更新树
{
 if(tree[i].r==num&&tree[i].l==num)
  tree[i].m=newv;
 else
 {
  if(num<=tree[lc(i)].r)
   renew(lc(i),num,newv);
  else
   renew(rc(i),num,newv);   
  tree[i].m=mmax(tree[lc(i)].m,tree[rc(i)].m);
 }
 return 0;
}

int finds(int a,int b,int i)//查找
{
 if(a<=tree[i].l&&tree[i].r<=b)
  return tree[i].m;
 if(b<=tree[lc(i)].r)
  return finds(a,b,lc(i));
 if(a>=tree[rc(i)].l)
  return finds(a,b,rc(i));
 return mmax(finds(a,tree[lc(i)].r,lc(i)),finds(tree[rc(i)].l,b,rc(i)));
}

int main()
{
 int i;
 while(scanf("%d %d",&M,&N)!=EOF)
 {
  for(i=1;i<=M;i++)
   scanf("%d",&score[i]);
  build(1,M,1);
  for(i=1;i<=N;i++)
  {
   scanf("%s %d %d",cmd,&p,&q);
   if(cmd[0]=='Q')
    printf("%d\n",finds(p,q,1));
   else if(cmd[0]=='U')
    renew(1,p,q);
  }
 }
 return 0;
}

posted @ 2011-09-21 15:51  qijinbiao1  阅读(179)  评论(0编辑  收藏  举报