HDOJ 1754 - I Hate It

Advanced Data Structures :: Segment Tree


Description

老师喜欢问,某某、某某到某某某中,分数最高的是谁。

并且有时候弄错成绩了要改成绩。

输入所有学生初始的成绩,和一些操作,操作包括改成绩和问成绩。

对所有问成绩的操作,输出询问的结果。


Type

Advanced Data Structures :: Segment Tree


Analysis

经典线段树的题目,用到了线段树区间求最值的能力,只需要单点更新。


Solution

// HDOJ 1754
// I Hate It
// by A Code Rabbit

#include <algorithm>
#include <cstdio>

using namespace std;

#define LSon(x) (x << 1) 
#define RSon(x) (x << 1 | 1) 

const int MAXN = 200002;
const int ROOT = 1;

struct Seg{
    int w;
};

struct SegTree {
    Seg node[MAXN << 2];
    void Update(int pos) { node[pos].w = max(node[LSon(pos)].w, node[RSon(pos)].w); }
    void Build(int l, int r, int pos) {
        if (l == r) { scanf("%d", &node[pos].w); return; }
        int m = l + r >> 1;
        Build(l, m, LSon(pos));
        Build(m + 1, r, RSon(pos));
        Update(pos);
    }
    void Modify(int l, int r, int pos, int x, int y) {
        if (l == r) { node[pos].w = y; return; }
        int m = l + r >> 1;
        if (x <= m) Modify(l, m, LSon(pos), x, y);
        else Modify(m + 1, r, RSon(pos), x, y);
        Update(pos);
    }
    int Query(int l, int r, int pos, int x, int y) {
        if (x <= l && r <= y) return node[pos].w;
        int m = l + r >> 1;
        int res = 0;
        if (x <= m) res = max(Query(l, m, LSon(pos), x, y), res);
        if (y > m) res = max(Query(m + 1, r, RSon(pos), x, y), res);
        return res;
    }
};

int n, m;
char c;
int a, b;

SegTree tree;

int main() {
    while (scanf("%d%d", &n, &m) != EOF) {
        tree.Build(1, n, ROOT);
        for (int i = 0; i < m; ++i) {
            getchar();
            scanf("%c%d%d", &c, &a, &b);
            if (c == 'Q')
                printf("%d\n", tree.Query(1, n, ROOT, a, b));
            else if (c == 'U')
                tree.Modify(1, n, ROOT, a, b);
        }
    }

    return 0;
}



你可能感兴趣的:(HDOJ 1754 - I Hate It)