线段树0分求助,悬赏关注

P3372 【模板】线段树 1

Lienqwq @ 2022-11-26 18:19:18

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

const int _ = 1e5 + 5;
typedef long long ll;
int n ,m;
ll a[_];
struct Node
{
    int l ,r ,tag;
    ll val;
}tree[_ * 4];

inline void build(int i ,int l ,int r)
{
    tree[i].tag = 0 ,tree[i].l = l ,tree[i].r = r;
    if(l == r)
    {
        tree[i].val = a[l];
        return;
    }
    int mid = (l + r) >> 1 ,p = i << 1;
    build(p ,l ,mid);
    build(p | 1 ,mid + 1 ,r);
    tree[i].val = tree[p].val + tree[p | 1].val;
}

inline void push_down(int i)
{
    if(tree[i].tag)
    {
        int p = tree[i].tag ,q = i << 1;
        tree[q].tag += p ,tree[q | 1].tag += p;
        int mid = (tree[i].l + tree[i].r) >> 1;
        tree[q].val += p * (mid - tree[q].l + 1);
        tree[q | 1].val += p * (tree[q | 1].r - mid);
        tree[i].tag = 0;
    }
    return;
} 

inline void update(int i ,int l ,int r ,ll k)
{
    if(tree[i].l >= l && tree[i].r <= r)
    {
        tree[i].val += (ll)k * (tree[i].l - tree[i].r + 1);
        tree[i].tag += k;
        return;
    }
    push_down(i);
    int p = i << 1;
    if(tree[p].r >= l) update(p ,l ,r ,k);
    if(tree[p | 1].l <= r) update(p | 1 ,l , r ,k);
    tree[i].val = tree[p].val + tree[p | 1].val;
    return;
}

inline ll query(int i ,int l ,int r)
{
    if(tree[i].l >= l && tree[i].r <= r)
        return tree[i].val;
    if(tree[i].l > r || tree[i].r < l) return 0;
    push_down(i);
    ll ans = 0;
    int p = i << 1;
    if(tree[p].r >= l) ans += query(p ,l ,r);
    if(tree[p | 1].l <= r) ans += query(p | 1 ,l ,r);
    return ans;
}

int main()
{
    scanf("%d%d" ,&n ,&m);
    for(int i = 1;i <= n;++i)
        scanf("%d" ,&a[i]);
    build(1 ,1 ,n);
    while(m--)
    {
        int t ,x ,y;
        scanf("%d%d%d" ,&t ,&x ,&y);
        if(t == 1)
        {
            ll k;
            scanf("%lld" ,&k);
            update(1 ,x ,y ,k);
        }
        else if(t == 2)
            printf("%lld\n" ,query(1 ,x ,y));
    }
    return 0;
}

rt


by cmeet @ 2022-11-26 18:24:55

tree[i].val += (ll)k * (tree[i].l - tree[i].r + 1);


by Lienqwq @ 2022-11-26 18:28:21

@cmeet ?不是和原来一样吗?


by cmeet @ 2022-11-26 18:32:43

r-l


by Lienqwq @ 2022-11-26 19:20:41

@cmeet 谢谢,已关


|