拿到了70分求帮

P3372 【模板】线段树 1

jingqiuya @ 2024-08-16 15:41:44


#include<iostream>
using namespace std;
#define lc p<<1
#define rc p<<1|1
#define ll long long
#define N 100005
int n;//数据数目
int w[N];//储存数据数组
struct tr {
    int l;//区间左
    int r;//区间右
    int sum;//当前区间内的值
    int add;//懒标记
}tr[N*4];
void pushdown(int p) {
    if (tr[p].add)
    {
        tr[lc].sum += (tr[lc].r - tr[lc].l + 1) * tr[p].add;
        tr[lc].add += tr[p].add;
        tr[rc].sum += (tr[rc].r - tr[rc].l + 1) * tr[p].add;
        tr[rc].add += tr[p].add;
        tr[p].add = 0;
    }
}//向下更新
void pushup(int p) {
    tr[p].sum = tr[lc].sum + tr[rc].sum;
}//向上更新
void build(int p, int l, int r) {
    tr[p] = { l,r,w[l],0 };
    if (l == r)return;
    int m = (l + r) >> 1;
    build(lc, l, m);
    build(rc, m + 1, r);
    pushup(p);
}//构建
void update(int p, int x, int y, int k)
{
    if (x <= tr[p].l && tr[p].r <= y) {
        tr[p].sum += (tr[p].r - tr[p].l+1) * k;
        tr[p].add += k;
        return;
    }
    int m = tr[p].l + tr[p].r >> 1;
    pushdown(p);
    if (x <= m)update(lc, x, y, k);
    if (y > m)update(rc, x, y, k);
    pushup(p);
}//更新数据 区间+k
ll query(int p, int x, int y) {
    if (x <= tr[p].l && tr[p].r <= y)
    {
        return tr[p].sum;
    }
    int m = (tr[p].l + tr[p].r) >> 1;
    pushdown(p);
    ll sum = 0;
    if (x <= m) sum += query(lc, x, y);
    if (y > m) sum += query(rc, x, y);
    return sum;
}//区间加和
int main() {
    cin >> n;
    int m;
    cin >> m;
    int s;
    int c;
    int x, y, k;
    for (int i = 1; i <= n; i++)
    {
        cin >> s;
        w[i] = s;
    }
    build(1, 1, n);
    for (int i = 1; i <= m; i++)
    {

        cin >> c;
        if (c == 1)
        {
            cin >> x >> y >> k;
            update(1, x, y,k);
        }
        else if( c==2 ) {
            cin >> x >> y;
            ll add = query(1, x, y);
            cout << add << endl;
        }
    }
}
在最后三组数据wa了,是加法溢出了吗?

by UMS2 @ 2024-08-16 15:52:33

本题需要 long long

此外,线段树 build 的时候只需要 l==r 时再赋值,其余情况把 l,r 赋值即可。


by UMS2 @ 2024-08-16 15:52:46

@hr922106840416


by jingqiuya @ 2024-08-16 15:57:43

@UMS2 嗷嗷,上面tr里的sum忘记改成longlong了,顺利通过这道题了,谢谢


by 宋怡芃 @ 2024-08-19 13:28:15

不开long long见祖宗啊


|