HDU1754线段树求取区间最大值

来源:互联网 发布:期房还是二手房 知乎 编辑:程序博客网 时间:2024/06/06 06:58

很多学校流行一种比较的习惯。老师们很喜欢询问,从某某到某某当中,分数最高的是多少。
这让很多学生很反感。

不管你喜不喜欢,现在需要你做的是,就是按照老师的要求,写一个程序,模拟老师的询问。当然,老师有时候需要更新某位同学的成绩。

Input

本题目包含多组测试,请处理到文件结束。
在每个测试的第一行,有两个正整数 N 和 M ( 0

Output

对于每一次询问操作,在一行里面输出最高成绩。

Sample Input

5 6
1 2 3 4 5
Q 1 5
U 3 6
Q 3 4
Q 4 5
U 2 9
Q 1 5

Sample Output

5
6
5
9
主要就是Update函数要特别注意

//https://vjudge.net/contest/197554#problem/B#include<iostream>#include<cstdio>#include<string.h>#include<cmath>#include<algorithm>#define lson l,m,i<<1#define rson m+1,r,i<<1|1#define pre(a) for(int i=1;i<=a;i++)using namespace std;const int maxn=200005;struct node{    int left;    int right;    int big;//存储区间最大值}tree[maxn<<2];int fa[maxn];int N;void Pushup(int i){//将当前结点的big根据子结点的值更新    tree[i].big=max(tree[i<<1].big,tree[i<<1|1].big);}void Build(int l,int r,int i){    tree[i].left=l;    tree[i].right=r;    tree[i].big=0;      if(l==r)      {          scanf("%d",&tree[i].big);          fa[l]=i;          return ;      }      int m=(l+r)>>1;      Build(lson);      Build(rson);      Pushup(i);}void Update(int i,int e){     if(i==1)     {         tree[i].big=max(tree[i<<1].big,tree[i<<1|1].big);         return ;     }     if(tree[i].left==tree[i].right)     tree[i].big=e;//点区间重新赋值     else        Pushup(i);//其他区间Pushup更新     Update(i>>1,e);}int Query(int L,int R,int l,int r,int i){//每次取区间的最大值    if(L<=l&&r<=R)    {        return tree[i].big;    }    int ans=-0x3ffffff;    int m=(l+r)>>1;    if(L<=m)        ans=max(ans,Query(L,R,lson));    if(R>m)        ans=max(ans,Query(L,R,rson));    return ans;}int main(){    int m;    while(~scanf("%d%d",&N,&m))    {        memset(tree,0,sizeof(tree));        memset(fa,0,sizeof(fa));        Build(1,N,1);        char str;        pre(m)        {            cin>>str;            int a,b;            scanf("%d%d",&a,&b);            if(str=='Q')                    printf("%d\n",Query(a,b,1,N,1));            if(str=='U')                    Update(fa[a],b);        }    }    return 0;}