线段树 9 pts 求助

P4513 小白逛公园

root357 @ 2022-05-25 17:30:52

如题目,只有测试点 #1 AC, 本人怀疑是在 pushup 或 Query() 的最后部分有错,找了半天没找着,求助各位。

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

const int N = 500010;
const int Inf = 1e4 + 10;

struct SegTree {
    int sum;
    int val, lv, rv;
};

int a[N] = {0};

SegTree T[N << 2];

void pushup (int k) {
    int ls = (k << 1);
    int rs = (k << 1) | 1;

    T[k].sum = T[ls].sum + T[rs].sum;
    T[k].val = max({T[ls].val, T[rs].val, T[ls].rv + T[rs].lv});
    T[k].lv = max(T[ls].lv, T[ls].sum + T[rs].lv);
    T[k].rv = max(T[rs].rv, T[ls].lv + T[rs].sum);

}

void Build (int k, int l, int r) {
    T[k].sum = T[k].val = T[k].lv = T[k].rv = -Inf;

    if (l == r) {
        T[k].sum = T[k].val = a[l];
        T[k].lv = T[k].rv = a[l];
        return;
    }

    int Mid = (l + r) >> 1;

    Build(k << 1, l, Mid);
    Build((k << 1) | 1, Mid + 1, r);

    pushup(k);

} 

void Update (int k, int l, int r, int x, int v) {
    if (l == r) {
        T[k].sum = T[k].val = v;
        T[k].lv = T[k].rv = v;
        return;
    }

    int Mid = (l + r) >> 1;

    if (x <= Mid) Update(k << 1, l, Mid, x, v);
    else Update((k << 1) | 1, Mid + 1, r, x, v);

    pushup(k);

}

SegTree Query (int k, int l, int r, int x, int y) {
    if (x <= l && r <= y) 
        return T[k];

    int Mid = (l + r) >> 1;

    if (y <= Mid) return Query(k << 1, l, Mid, x, y);
    if (x >  Mid) return Query((k << 1) | 1, Mid + 1, r, x, y);

    SegTree res;
    SegTree ls, rs;

    ls = Query(k << 1, l, Mid, x, y);
    rs = Query((k << 1) | 1, Mid + 1, r, x, y);

    res.lv = max(ls.lv, ls.sum + rs.lv);
    res.rv = max(rs.rv, ls.rv + rs.sum);
    res.val = max({ls.val, rs.val, ls.rv + rs.lv});

    return res;

}

int main()
{
    int n, m;
    scanf("%d%d", &n, &m);

    for (int i = 1; i <= n; i ++) 
        scanf("%d", &a[i]);

    Build(1, 1, n);

    for (int i = 1; i <= m; i ++) {
        int k, a, b;
        scanf("%d%d%d", &k, &a, &b);

        if (k == 1) {
            if (a > b) swap(a, b);

            SegTree res = Query(1, 1, n, a, b);

            printf("%d\n", res.val);
        }
        else {
            Update(1, 1, n, a, b);
        }

    }

    return 0;
}

by Eason2009 @ 2022-05-25 17:38:01

@root357 pushdown顺序错了


by root357 @ 2022-05-25 17:39:31

啊我只有 pushup


by Eason2009 @ 2022-05-25 17:40:07

@root357 说错了,pushup顺序错了


by root357 @ 2022-05-25 17:41:19

啊明白了,是在 pushup T[k].rv 那里,谢谢朋友


by root357 @ 2022-05-25 17:42:11

AC 了,谢谢朋友


|