Line segment tree HDU1754 LG1531 I Hate It

topic

Title link:
HDU1754
LG1531

answer

Board title of the line segment tree. Note that the two questions are not the same. HDU has multiple sets of data, while LG has only one set of data.

AC code

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<string>
#include<queue>
#include<map>
#include<stack>
#include<list>
#include<set>
#include<deque>
#include<vector>
#include<ctime>

using namespace std;
//#pragma GCC optimize(2)
#define IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define ull unsigned long long
#define ll long long
#define rep(i, x, y) for(int i=x;i<=y;i++)
#define mms(x, n) memset(x, n, sizeof(x))
#define mmc(a, b) memcpy(a, b, sizeof(b))
#define INF (0x3f3f3f3f)
#define mod (ull)(1e9+7)
typedef pair<int, int> P;
const int N = 2e5 + 10;
int n, m;
int A[N], Max[N * 4];

// 更新节点
void pushUp(int rt) {
    Max[rt] = max(Max[rt << 1], Max[rt << 1 | 1]);
}

// 建树
void build(int l, int r, int rt) {
	// 碰到叶子节点时,赋值
    if (l == r) {
        Max[rt] = A[l];
        return;
    }
    int mid = (l + r) >> 1;
    // 递归建树
    build(l, mid, rt << 1);
    build(mid + 1, r, rt << 1 | 1);
    // 两个子树建立完成后更新当前节点的值
    pushUp(rt);
}

// 单点更新
// [l, r]为当前区间
void udNode(int x, int c, int l, int r, int rt) {
    if (l == r) {
        if (Max[rt] < c) Max[rt] = c;
//        Max[rt] = max(c, Max[rt]);
        return;
    }
    int mid = (l + r) >> 1;
    if (x <= mid) udNode(x, c, l, mid, rt << 1);
    else udNode(x, c, mid + 1, r, rt << 1 | 1);
    pushUp(rt);
}

//查询
// [L,R] 为目标区间, [l, r] 为当前区间
int Query(int L, int R, int l, int r, int rt) {
    if (L <= l && r <= R) return Max[rt];
    int mid = (l + r) >> 1;
    int ans = -INF;
    if (L <= mid) ans = max(ans, Query(L, R, l, mid, rt << 1));
    if (R > mid) ans = max(ans, Query(L, R, mid + 1, r, rt << 1 | 1));
    return ans;
}

int main() {
    while (scanf("%d%d", &n, &m) != EOF) {
        mms(A, 0);
        mms(Max, 0);
        for (int i = 1; i <= n; i++) scanf("%d", &A[i]);
        build(1, n, 1);
        char ch[2];
        int a, b;
        while (m--) {
            scanf("%s%d%d", ch, &a, &b);
            if (ch[0] == 'Q') {
                printf("%d\n", Query(a, b, 1, n, 1));
            } else udNode(a, b, 1, n, 1);
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_45934120/article/details/108019939