修改挂了求条

P3372 【模板】线段树 1

imnoob @ 2024-08-04 20:48:05

悬关

#include <bits/stdc++.h>
using namespace std;
int n, m, a[100010];
int t[10000010], tag[10000010], cnt = 0;
void build(int l, int r, int p)
{
    if(l == r)
    {
        t[p] = a[l];
        return;
    }
    int mid = (l + r) / 2;
    build(l, mid, p * 2);
    build(mid + 1, r, p * 2 + 1);
    t[p] = t[p * 2] + t[p * 2 + 1]; 
}
void f(int l, int r, int p, int k)
{
    tag[p] += k;
    t[p] += k * (r - l - 1);
}
void push(int l, int r, int p)
{
    int mid = (l + r) / 2;
    f(l, mid, p * 2, tag[p]);
    f(mid + 1, r, p * 2 + 1, tag[p]);
    tag[p] = 0;
}
void add(int x, int y, int l, int r, int p, int k)
{
    if(x <= l && r <= y)
    {
        t[p] += k * (r - l - 1);
        tag[p] += k;
        return;
    }
    push(l, r, p);
    int mid = (l + r) / 2;
    if(x <= mid)
    {
        add(x, y, l, mid, p * 2, k);
    }
    if(mid < y)
    {
        add(x, y, mid + 1, r, p * 2 + 1, k);    
    }
    t[p] = t[p * 2] + t[p * 2 + 1];
}
int ans(int x, int y, int l, int r, int p)
{
    if(x <= l && r <= y)
    {
        return t[p];
    }
    int sum = 0, mid = (l + r) / 2;
    push(l, r, p);
    if(x <= mid)
    {
        sum += ans(x, y, l, mid, p * 2);
    }
    if(mid < y)
    {
        sum += ans(x, y, mid + 1, r, p * 2 + 1);
    }
    return sum;
}
int main()
{
    cin >> n >> m;
    for(int i = 1; i <= n; ++i)
    {
        cin >> a[i];
    }
    build(1, n, 1); 
    for(int i = 1; i <= m; ++i)
    {
        int u, x, y, k;
        cin >> u >> x >> y;
        if(u == 1)
        {
            cin >> k;
            add(x, y, 1, n, 1, k);
        }
        else
        {
            cout << ans(x, y, 1, n, 1) << '\n';
        }
    }
    return 0;
} 

by sto_yxc_orz @ 2024-08-04 21:11:49

写错了,r-l-1 改成 r-l+1


|