洛谷P1531 I Hate It題解

題目背景

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

題目描述

無論你喜不喜歡,如今須要你作的是,就是按照老師的要求,寫一個程序,模擬老師的詢問。固然,老師有時候須要更新某位同窗的成績ui

輸入格式

第一行,有兩個正整數 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'的時候,表示這是一條更新操做,若是當前A學生的成績低於B,則把ID爲A的學生的成績更改成B,不然不改動。code

輸出格式

對於每一次詢問操做,在一行裏面輸出最高成績ci

輸入輸出樣例

輸入 #1 複製

5 6get

1 2 3 4 5string

Q 1 5it

U 3 6io

Q 3 4stream

Q 4 5map

U 2 9

Q 1 5

輸出 #1 複製

5

6

5

9

解析:

單點修改,區間查詢。

明顯的線段樹。

#include <cstdio>
#include <cmath>
#include <iostream>
#include <cstdlib>
#include <vector>
#include <map>
#include <cstring>
#include <queue>
#include <stack>
#include <algorithm>
#define re register
#define Max 400100
#define gc getchar
#define lson x<<1
#define rson x<<1|1
int max(int a, int b) {return a > b ? a : b;}
struct HATE {
    int l, r, max;
}t[Max << 1];
int m, n, pts[Max >> 1];
void up(int x) {t[x].max = max(t[lson].max, t[rson].max);}
void build(int l, int r, int x) {
    t[x].l = l; t[x].r = r;
    if(l == r) {
        t[x].max = pts[l];
        return ;
    }
    int mid = l + r >> 1;
    build(l, mid, lson); build(mid+1, r, rson);
    up(x);
}
void data(int f, int x, int k) {
    if(t[x].l == f && t[x].r == f) {
        if(t[x].max < k) t[x].max = k;
        return ;
    }
    int mid = t[x].l + t[x].r >> 1;
    if(f <= mid) data(f,lson,k);
    if(f > mid) data(f,rson,k);
    up(x);
}
int Ask(int l, int r, int x) {
    if(t[x].l >= l && t[x].r <= r)
        return t[x].max;
    int mid = t[x].l + t[x].r >> 1;
    int ans = - 9999999;
    if(l <= mid) ans = max(ans, Ask(l,r,lson));
    if(r > mid) ans = max(ans, Ask(l,r,rson));
    return ans;
}
int main() {
    scanf("%d%d",&n,&m);
    for(re int i = 1; i <= n; ++ i) scanf("%d", &pts[i]);
    build(1, n, 1); int l, r; char opt;
    for(re int i = 1; i <= m; ++ i) {
        std :: cin >> opt;
        scanf("%d %d",&l,&r);
        if(opt == 'U') data(l,1,r);
        else printf("%d\n",Ask(l,r,1));
    }
    return 0;
}
相關文章
相關標籤/搜索