RT, tle

P4513 小白逛公园

hanss6 @ 2024-07-23 20:55:18

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define ls (p << 1) 
#define rs (ls | 1)
#define len(p) (t[p].r - t[p].l + 1)

const int N = 5e5 + 5;

int n, m, a[N];

struct Info{
    int l, r, sum, lmx, rmx, ans;

} t[N << 2];
Info operator + (const Info &lhs, const Info &rhs) {
    Info res;
    res.ans = max(max(lhs.ans, rhs.ans), lhs.rmx + rhs.lmx);
    res.lmx = max(lhs.lmx, lhs.sum + rhs.lmx);
    res.rmx = max(rhs.rmx, rhs.sum + lhs.rmx);
    res.sum = lhs.sum + rhs.sum;
    return res;
}
void pushup(int p) {
    t[p] = t[ls] + t[rs];
//  cout << p << " "<<endl;
}

void build(int p, int l, int r) {
    t[p].l = l, t[p].r = r;
//  cout << p << ' ' << t[p].l << ' '<< t[p].r << endl;
    if (l == r) {
        t[p].sum = t[p].lmx = t[p].rmx = t[p].ans = a[l];
        return;
    }
    int mid = (l + r) >> 1;
    build(ls, l, mid);
    build(rs, mid + 1, r);
    pushup(p);
}

void change(int p, int pos, int x) {
    if (t[p].l == t[p].r) {
        t[p].sum = t[p].lmx = t[p].rmx = t[p].ans = x;
        return;
    }
    int mid = (t[p].l + t[p].r) >> 1;
    if (mid >= pos) change(ls, pos, x);
    if (mid < pos) change(rs, pos ,x);
    pushup(p);
}

Info query(int p, int l, int r) {
    if (t[p].l >= l && t[p].r <= r) return t[p];
    int mid = (t[p].l + t[p].r) >> 1;
    if (mid >= l && mid < r) return query(ls, l, r) + query(rs, l, r);
    if (l <= mid) return query(ls, l, r);
    return query(rs, l, r);
}
signed main() {
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    build(1, 1, n);
    while (m--) {
        int k;
        cin >> k;
        if (k == 1) {
            int l, r;
            cin >> l >> r;
            cout << query(1, min(l, r), max(l, r)).ans << endl;
        } else {
            int p, x;
            cin >> p >> x;
            change(1, p, x);
        }
    }
    return 0;
}

by ericloo0921 @ 2024-07-30 20:32:44

题目说可能出现a大于b的情况,在1操作时需要判断 if (l>r) swap(l,r);


by hanss6 @ 2024-08-04 12:43:13

@ericloo0921 我调用函数的时候注意到了,l取的min(l,r) r取的max(l,r)


|