HDU 1754 I Hate It (線段樹,點修改)

題目鏈接:HDU 1754 I Hate It
思路:對模板進行簡單的修改,求區間內最大值。
AC代碼講解:

#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<set>
#include<stack>
#include<ctime>
#include<queue>
#define LOCAL
#define pi 3.1415926
#define e 2.718281828459
#define mst(a,b) memset(a,b,sizeof(a))
const int  INF = 0x3f3f3f3f;
using namespace std;

#define maxn 200000
int sum[maxn<<2];
int a[maxn];

void build(int l,int r,int rt){
 if(l == r){
    sum[rt] = a[l];
    return ;
 }
 int m = (l+r)>>1;
 build(l,m,rt<<1);
 build(m+1,r,rt<<1|1);
 sum[rt] = max(sum[rt<<1] , sum[rt<<1|1]);//修改部分,將求和改成求最值
}

void update(int L,int C,int l,int r,int rt){
   if(l == r){//找到葉子節點就修改
     sum[rt] = C;
     return ;
   }
   int m = (l+r)>>1;
   if(L <= m) update(L,C,l,m,rt<<1);
   else  update(L,C,m+1,r,rt<<1|1);
   sum[rt] = max(sum[rt<<1] , sum[rt<<1|1]);//遞歸跟新有關的最值
}

int query(int L,int R, int l,int r,int rt){//重點
   if(L <=l && r <= R) return sum[rt];
   int m = (r+l)>>1;
   int nmax = 0;
   if(L <= m) nmax = max(nmax,query(L,R,l,m,rt<<1));//先設定一個最小的值,然後比較重疊部分的最值
   if(R > m)  nmax = max(nmax,query(L,R,m+1,r,rt<<1|1));
   return nmax;
}

int main(){
    int n ,m;
    while(scanf("%d%d",&n,&m) == 2){
        for(int i = 1; i <= n; i++)
            scanf("%d",&a[i]);
        build(1,n,1);
        char c; int ans , a, b;
        while(m--){
         getchar();
         scanf("%c",&c);
         if(c == 'Q'){
           scanf("%d%d",&a,&b);
           ans = query(a, b, 1, n, 1);
           printf("%d\n",ans);
         }
         else if(c == 'U'){
            scanf("%d%d",&a,&b);
            update(a, b, 1, n, 1);
         }
       }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章