luoguP4513 小白逛公园

Posted ljc00118

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了luoguP4513 小白逛公园相关的知识,希望对你有一定的参考价值。

https://www.luogu.org/problemnew/show/P4513

题意是给你一个序列,计算一个区间内的最大字段和,支持单点修改

线段树维护左起最大字段和,右起最大字段和,区间和和最大字段和,查询时合并区间即可

#include <bits/stdc++.h>
#define Cios ios::sync_with_stdio(false);
#define For(i, a, b) for(register int i = a; i <= b; i++)
#define Forr(i, a, b) for(register int i = a; i >= b; i--)
using namespace std;

typedef unsigned long long ull;
typedef long long ll;

template <typename _T>
inline void read(_T &f) {
    f = 0; _T fu = 1; char c = getchar();
    while(c < '0' || c > '9') { if(c == '-') fu = -1; c = getchar(); }
    while(c >= '0' && c <= '9') { f = (f << 3) + (f << 1) + (c & 15); c = getchar(); }
    f *= fu;
}

template <typename T>
void print(T x) {
    if(x < 0) putchar('-'), x = -x;
    if(x < 10) putchar(x + 48);
    else print(x / 10), putchar(x % 10 + 48);
}

template <typename T>
void print(T x, char t) {
    print(x); putchar(t);
}

const int N = 5e5 + 5;

struct ele { ele () {} int lmax, rmax, maxn, sum; };
struct Node { Node () {} int l, r; ele val; } p[N << 2];

int a[N], n, m;

ele Merge(ele a, ele b) {
    ele ans; ans.sum = a.sum + b.sum;
    ans.lmax = max(a.lmax, a.sum + max(0, b.lmax));
    ans.rmax = max(b.rmax, b.sum + max(0, a.rmax));
    ans.maxn = max(max(a.maxn, b.maxn), max(a.rmax + max(0, b.lmax), max(0, a.rmax) + b.lmax));
    return ans;
}

void build(int u, int l, int r) {
    p[u].l = l, p[u].r = r;
    if(l == r) {
        p[u].val.lmax = p[u].val.rmax = p[u].val.maxn = p[u].val.sum = a[l];
        return; 
    }
    int mid = (l + r) >> 1;
    build(u << 1, l, mid); build(u << 1 | 1, mid + 1, r);
    p[u].val = Merge(p[u << 1].val, p[u << 1 | 1].val);
}

void change(int u, int x, int y) {
    if(p[u].l == p[u].r) {
        p[u].val.lmax = p[u].val.rmax = p[u].val.maxn = p[u].val.sum = y;
        return;
    }
    int mid = (p[u].l + p[u].r) >> 1;
    if(mid >= x) change(u << 1, x, y); else change(u << 1 | 1, x, y);
    p[u].val = Merge(p[u << 1].val, p[u << 1 | 1].val);
}

ele query(int u, int l, int r) {
    if(p[u].l >= l && p[u].r <= r) return p[u].val;
    int mid = (p[u].l + p[u].r) >> 1;
    if(mid >= l && mid + 1 <= r) return Merge(query(u << 1, l, r), query(u << 1 | 1, l, r));
    else if(mid >= l) return query(u << 1, l, r); else return query(u << 1 | 1, l, r);
}

int main() {
    read(n); read(m);
    for(register int i = 1; i <= n; i++) read(a[i]);
    build(1, 1, n);
    while(m--) {
        int opt, x, y;
        read(opt); read(x); read(y);
        if(opt == 1) {
            if(x > y) swap(x, y);
            print(query(1, x, y).maxn, '
');
        } else change(1, x, y);
    }
    return 0;
}

以上是关于luoguP4513 小白逛公园的主要内容,如果未能解决你的问题,请参考以下文章

luogu P4513ybtoj线段树课堂过关例题3小白逛公园

P4513 小白逛公园(线段树)

$Luogu$ $P4513$ 小白逛公园

luogu P4513 小白逛公园 2019.8.2

做题记录 Luogu P4513

TYVJ1427 小白逛公园