马蜂良好,求条

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 cq_zry @ 2023-08-03 22:11:05

@cq_zry 你对着蓝书上的代码在看看呢


by cq_zry @ 2023-08-03 22:12:34

@cq_zry 没打过这种代码,但是你这个需要加懒标记,一般范围大的都要的,建议往后面看看


by da_ke @ 2023-08-03 22:15:28

@cq_zry query的问题y1->y2


上一页 |