HDU1754 I hate it 线段树模板

题目链接:hdu1754
题意:线段树单点修改和查询区间最大值打模板题。
code:

#include <bits/stdc++.h>

using namespace std;
#define mid ((l+r)>>1)
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r

const int maxn = 2e5 + 20;

int tree[maxn << 2];
int val[maxn];


void build(int rt, int l, int r) {
    if (l == r) {
        scanf("%d",&tree[rt]);
        return;
    }
    build(lson);
    build(rson);
    tree[rt] = max(tree[rt << 1], tree[rt << 1 | 1]);
}

void update(int rt, int l, int r, int val, int pos) {
    if (l == r) {
        tree[rt] = val;
        return;
    }
    if (pos <= mid) update(lson, val, pos);
    else update(rson, val, pos);
    tree[rt] = max(tree[rt << 1], tree[rt << 1 | 1]);
}

int query(int rt, int l, int r, int L, int R) {
    if (L <= l && R >= r) {
        return tree[rt];
    }
    int ans1 = 0, ans2 = 0;
    if (L <= mid) ans1 = query(lson, L, R);
    if (R > mid)ans2 = query(rson, L, R);
    return max(ans1, ans2);
}

int main() {
    int n, m;
    while (~scanf("%d%d", &n, &m)) {
        memset(tree, 0, sizeof(tree));
        int i;
        build(1, 1, n);
        char cmd[2];
        int a, b;

        for (i = 0; i < m; i++) {
            scanf("%s%d%d", cmd, &a, &b);
            //   printf("%c %d %d\n", cmd, a, b);
            if (cmd[0] == 'Q') {
                printf("%d\n", query(1, 1, n, a, b));
            } else {
                update(1, 1, n, b, a);
            }
        }
    }

    return 0;
}

发布了50 篇原创文章 · 获赞 52 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_43058685/article/details/104070812