HDU-1754 線段樹的節點更新,儲存區間的最大值

很多學校流行一種比較的習慣。老師們很喜歡詢問,從某某到某某當中,分數最高的是多少。 
這讓很多學生很反感。 

不管你喜不喜歡,現在需要你做的是,就是按照老師的要求,寫一個程序,模擬老師的詢問。當然,老師有時候需要更新某位同學的成績。
Input本題目包含多組測試,請處理到文件結束。 
在每個測試的第一行,有兩個正整數 N 和 M ( 0<N<=200000,0<M<5000 ),分別代表學生的數目和操作的數目。 
學生ID編號分別從1編到N。 
第二行包含N個整數,代表這N個學生的初始成績,其中第i個數代表ID爲i的學生的成績。 
接下來有M行。每一行有一個字符 C (只取'Q'或'U') ,和兩個正整數A,B。 
當C爲'Q'的時候,表示這是一條詢問操作,它詢問ID從A到B(包括A,B)的學生當中,成績最高的是多少。 
當C爲'U'的時候,表示這是一條更新操作,要求把ID爲A的學生的成績更改爲B。 
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
解題思路:代碼設置了tree數組用來存儲輸入的數據,tree【1】存儲tree【2】和tree【3】兩數的最大值,tree【2】存儲tree【2*2】和tree【2*2+1】兩數的最大值,tree【3】存儲tree【3*2】和tree【3*2+1】兩數的最大值
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 20010;

int tree[MAXN<<1+10];

void build_tree(int l,int r,int root){
    if (l == r){
        scanf("%d",&tree[root]);
         return;
    }
    int m = (l+r) >> 1;
    build_tree(l,m,root<<1);//右移運算符 相當於root*2;
    build_tree(m+1,r,root<<1|1);//右移運算符,相當於root*2+1;
    tree[root] = max(tree[root<<1],tree[root<<1|1]);
}

void update(int pos,int date,int l,int r,int root){
    if (l == r){
        tree[root] = date;
        return;
    }
    int m = (l+r) >> 1;
    if (pos <= m)
        update(pos,date,l,m,root<<1);
    else update(pos,date,m+1,r,root<<1|1);
    tree[root] = max(tree[root<<1],tree[root<<1|1]);
}

int query(int L,int R,int l,int r,int root){
    int sum = -11111111;
    if (L <= l && r <= R)
        return tree[root];
    int m = (l+r) >> 1;
    if (L <= m)
        sum = max(sum,query(L,R,l,m,root<<1));
    if (R > m)
        sum = max(sum,query(L,R,m+1,r,root<<1|1));
    return sum;
}

int main(){
    int num,que;
    char op;
    int a,b;
    while (scanf("%d%d",&num,&que) != EOF){
        build_tree(1,num,1);
        for (int i = 0; i < que; i++)
        {
            scanf("%*c%c %d %d",&op,&a,&b);
            if (op == 'U')
                update(a,b,1,num,1);
            else printf("%d\n",query(a,b,1,num,1));
        }
    }
    return 0;
}

發佈了21 篇原創文章 · 獲贊 13 · 訪問量 6856
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章