马蜂良好,求条

P3372 【模板】线段树 1

da_ke @ 2023-08-03 21:56:59

#include <bits/stdc++.h>

using namespace std;

#define rep(i, l, r) for (int i = l; i <= r; i++)
#define int long long
using ll = long long;
using ull = unsigned long long;
const int INF = 1 << 30;
const long long INFL = 1LL << 60;
const int N = 1e5 + 24;
#define ok cout << "ok" << endl

int n, m;
int sumv[N], addv[N], a[N];
int y1, y2, v, _sum;
// int _min, _max, _sum;

// void init_value()
// {
//     _min = INF, _max = -INF, _sum = 0;
// }

void build(int o, int l, int r)
{
    int lc = o * 2, rc = o * 2 + 1;
    if (l == r)
    {
        sumv[o] = a[l];
        return;
    }
    int m = l + (r - l) / 2;
    build(lc, l, m);
    build(rc, m + 1, r);
}

void maintain(int o, int l, int r)
{
    int lc = o * 2, rc = o * 2 + 1;
    if (r > l)
        sumv[o] = sumv[lc] + sumv[rc];
    sumv[o] += addv[o] * (r - l + 1);
}

void update(int o, int l, int r)
{
    int lc = 2 * o, rc = 2 * o + 1;
    if (y1 <= l && y2 >= r)
        addv[o] += v;
    else
    {
        int m = l + (r - l) / 2;
        if (y1 <= m)
            update(lc, l, m);
        if (y2 > m)
            update(rc, m + 1, r);
    }
    maintain(o, l, r);
}

void query(int o, int l, int r, int add)
{
    if (y1 <= l && y2 >= r)
        _sum += sumv[o] + add * (r - l + 1);
    else
    {
        int m = l + (r - l) / 2;
        if (y1 <= m)
            query(o * 2, l, m, add + addv[o]);
        if (y1 > m)
            query(o * 2, m + 1, r, add + addv[o]);
    }
}

signed main()
{
    ios::sync_with_stdio(false);
    cin >> n >> m;
    rep(i, 1, n)
            cin >>
        a[i];
    // ok;
    build(1, 1, n);
    // ok;
    rep(i, 1, m)
    {
        // ok;
        int opt, x, y, k;
        cin >> opt >> x >> y;
        if (opt == 1)
        {
            cin >> k;
            y1 = x, y2 = y, v = k;
            update(1, 1, n);
        }
        if (opt == 2)
        {
            _sum = 0;
            y1 = x, y2 = y;
            query(0, x, y, 0);
            cout << _sum << endl;
        }
    }
}

by da_ke @ 2023-08-03 21:57:32

@cq_zry


by cq_zry @ 2023-08-03 21:58:31

@WA_Coding_Duck 题目啥意思


by da_ke @ 2023-08-03 21:59:22

@cq_zry 没意思


by liangbowen @ 2023-08-03 21:59:51

草你这写的啥啊......这种基础的模板还是对着题解写比较好吧......


by cq_zry @ 2023-08-03 22:00:57

@WA_Coding_Duck 懒标记搞错了


by cq_zry @ 2023-08-03 22:04:04

@WA_Coding_Duck sumv[o] += addv[o] * (r - l + 1);这么写的话你修改一个区间再查询一个单点(单点在区间内)就会错掉,因为你的懒标记在没到单点就被卡住了


by cq_zry @ 2023-08-03 22:05:11

@cq_zry add数组是需要下放的,目的只是一个暂时收集起来,在必须下放的时候统一下放


by cq_zry @ 2023-08-03 22:09:07

@WA_Coding_Duck 欸不对,你怎么每个都加一遍啊


by cq_zry @ 2023-08-03 22:09:53

@cq_zry 你这玩意add不是懒标记吧,是加的值


by cq_zry @ 2023-08-03 22:10:40

@cq_zry a我也搞不懂你的代码,但是还是觉得就是你add的问题


| 下一页