HDOJ 1754 ------线段树

本文介绍了一种使用线段树解决学生分数查询及更新问题的方法。通过单点更新和区间查询操作,实现了对指定范围内最高分数的有效查找。

题目大意:

       输入N,M,表示有N个学生,M次操作,操作主要有两种查询[A,B]内分数最高的学生 (2) 更新 将A学生的分数修改为 B。

算法思想:

      主要使用线段树的,单点更新,和区间查询操作。

代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>
#define lson l,m,rt<<1
#define rson m+1,r,rt << 1|1
using namespace std;
const int MAXN=222222;
int Max[MAXN<<2];
void PushUp(int rt){
   Max[rt]=max(Max[rt<<1],Max[rt<<1|1]);//孩子节点中的最大值
}
void Build(int l,int r,int rt){
     if(l==r){
         scanf("%d",&Max[rt]);
         return ;
    }  
    int m=(l+r)>>1;
    Build(lson);
    Build(rson);
    PushUp(rt);
}
int Query(int L,int R,int l,int r,int rt){
    if(L<=l&&r<=R){//包含了所有区间
         return Max[rt];     
    }
    int m=(l+r)>>1;
    int ret=0;
    if(L<=m) ret=max(ret,Query(L,R,lson));
    if(R>m) ret=max(ret,Query(L,R,rson));  
    return ret;   
}
void Update(int p,int sc,int l,int r,int rt){  
     if(l==r)//只有一个节点
     {   
        Max[rt]=sc; 
        return ;
     }
     int m=(l+r)>>1;
        if(p<=m) Update(p,sc,lson);
     else
         Update(p,sc,rson);
     PushUp(rt);
}
int main(){
    int N,M,A,B;
    char C;
    while(scanf("%d%d",&N,&M)!=EOF)
    {
         Build(1,N,1);
         while(M--){
             char op[2];
             scanf("%s%d%d",op,&A,&B);
             if(op[0]=='Q')
               printf("%d\n",Query(A,B,1,N,1));
             else
               Update(A,B,1,N,1);
         }                                            
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值