萌新刚学线段树,20分,急!!!

P1253 扶苏的问题

Lucky_Cloud @ 2023-04-18 11:39:03

#include <bits/stdc++.h>
#define ll long long
using namespace std;

const long long inf = -1e13;
const int N = 4e6 + 10;
int n, q, a[N];
struct tree {
    int l, r;
    ll d, lz1, lz2;//lz1传修改值, lz2传加数
} t[N];

ll read() {
    char c = getchar(); ll s = 0; short f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') {s = (s * 10) + c - '0'; c = getchar();}
    return s * f;
}

void pushup(int x) {
    t[x].d = max(t[x * 2].d, t[x * 2 + 1].d);
}

void build(int l, int r, int x) {
    t[x].l = l, t[x].r = r, t[x].lz1 = inf;
    if(l == r) {
        t[x].d = a[l];
        return;
    }
    int mid = (l + r) / 2;
    build(l, mid, x * 2);
    build(mid + 1, r, x * 2 + 1); 
    pushup(x);
}

void lazy_tag(int x) {
    if(t[x].lz1 != inf) {
        t[x * 2].lz1 = t[x * 2 + 1].lz1 = t[x].lz1;
        t[x * 2].d = t[x * 2 + 1].d = t[x].lz1;
        t[x * 2].lz2 = t[x * 2 + 1].lz2 = 0;
        t[x].lz1 = inf;
    }
    if(t[x].lz2) {
        t[x * 2].lz2 = t[x * 2 + 1].lz2 = t[x].lz2;
        t[x * 2].d += t[x].lz2;
        t[x * 2 + 1].d += t[x].lz2;
        t[x].lz2 = 0;
    }
}

void change(int l, int r, int p, ll v, int o) {
    if(l <= t[p].l && t[p].r <= r) {
        if(o == 1) {
            t[p].lz1 = v;
            t[p].d = v;
            t[p].lz2 = 0;
        }
        else {
            t[p].d += v;
            t[p].lz2 += v;
        }
        return;
    }
    lazy_tag(p);
    int mid = (t[p].l + t[p].r) >> 1;
    if(l <= mid) change(l, r, p * 2, v, o);
    if(r > mid) change(l, r, p * 2 + 1, v, o);
    pushup(p);
}

ll ask(int l, int r, int p) {
    if(l <= t[p].l && t[p].r <= r) {
        return t[p].d;
    }
    int mid = (t[p].l + t[p].r) >> 1;
    ll val = inf;
    lazy_tag(p);
    if(l <= mid) val = max(val, ask(l, r, p * 2));
    if(r > mid) val = max(val, ask(l, r, p * 2 + 1));
    return val;
}

int main() {
    cin >> n >> q;
    for(int i = 1; i <= n; i++) cin >> a[i];
    build(1, n, 1);
    while(q--) {
        int o = read(), l =read(), r = read();
        if(o == 1) {
            ll x = read();
            change(l, r, 1, x, 1);
        }//[l, r] += x
        if(o == 2) {
            ll x = read();
            change(l, r, 1, x, 2);
        }//[l, r] = x
        if(o == 3) {
            cout << ask(l, r, 1) << endl;
        }//max
    }
    return 0;
}

本蒟蒻只A了1和3,求助各位大佬


by comcopy @ 2023-04-18 12:03:26

@liao_cheng 更新加法标记的时候要用 += 而不是 = 。

if(t[x].lz2) {
        t[x * 2].lz2 += t[x].lz2,
        t[x * 2 + 1].lz2 += t[x].lz2;
        t[x * 2].d += t[x].lz2;
        t[x * 2 + 1].d += t[x].lz2;
        t[x].lz2 = 0;
    }

by Lucky_Cloud @ 2023-04-18 12:06:11

感谢,sto已A,此贴结


|