计蒜客习题:最甜的苹果

问题描述

蒜头君有很多苹果,每个苹果都有对应的甜度值。
蒜头君现在想快速知道从第 i 个苹果到第 j 个苹果中,最甜的甜度值是多少。
因为存放时间久了,有的苹果会变甜,有的苹果会因为腐烂而变得不甜,所以蒜头君有时候还需要修改第 iii 个苹果的甜度值。
输入格式
第一行输入两个正整数N,M(0

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

样例输出

5
6
5
9

#AC代码

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const int MAX_N=2000050;
int s[4*MAX_N];

void up(int p){
    s[p]=max(s[p*2],s[p*2+1]);
}

void modify(int p,int l,int r,int x,int v){
    if(l==r){
        s[p]=v;
        return;
    }   
    int mid=(l+r)/2;
    if(x<=mid){
        modify(p*2,l,mid,x,v);
    }else{
        modify(p*2+1,mid+1,r,x,v);
    }
    up(p);
    return;
}

int query(int p,int l,int r,int x,int y){
    if(l<=x&&y>=r){
        return s[p];
    }
    int mid=(l+r)/2;
    int res=-1;
    if(x<=mid)res=max(query(p*2,l,mid,x,y),res);
    if(y>mid)res=max(query(p*2+1,mid+1,r,x,y),res);
    return res;
}

int main(){
    int N,M;
    cin>>N>>M;
    for(int i=1;i<=N;i++){
        int d;
        cin>>d;
        modify(1,1,N,i,d);
    }
    getchar();
    for(int i=1;i<=M;i++){
        char C;
        cin>>C;
        int x,y;
        cin>>x>>y;
        if(C=='Q'){
            cout<<query(1,1,N,x,y)<<endl;
        }else{
            modify(1,1,N,x,y);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/liukairui/article/details/80905174