树状数组悬关求调~~~~~

P3372 【模板】线段树 1

_Coffice_ @ 2023-07-06 16:30:58

#include <iostream>
#include <cstdio>
#define int long long
using namespace std;
const int N = 100005;
int a[N], b[N], s[N];
int t[2][N];
int n, m;
int lowbit(int x) { return (x & (-x)); }
void add(int k, int x, int y)
{
    for(int i=x;i<=n;i+=lowbit(i))
        t[k][i] += y;
}
int sum(int k, int x)
{
    int ans = 0;
    for(int i=x;i>=1;i-=lowbit(i))
        ans += t[k][i];
    return ans;
}
void upd(int l, int r, int x)
{
    add(0, l, x);
    add(0, r+1, -x);
    add(1, l, l*x);
    add(1, r+1, -r*x);
}
int ask(int n)
{
    int a = sum(0, n);
    int b = sum(1, n);
    return (n+1)*a-b;
}
signed main() 
{
    cin >> n >> m;
    for(int i=1;i<=n;i++)
    {
        cin >> a[i];
        b[i] = a[i]-a[i-1];
        s[i] = s[i-1]+b[i];
        t[0][i] = s[i]-s[i-lowbit(i)];
    }
    for(int i=1;i<=n;i++)
    {
        s[i] = s[i-1]+i*b[i];
        t[1][i] = s[i]-s[i-lowbit(i)];
    }
    for(int i=1;i<=m;i++)
    {
        int op;
        cin >> op;
        if(op == 1)
        {
            int x, y, k;
            cin >> x >> y >> k;
            upd(x, y, k);
        }
        else
        {
            int x, y;
            cin >> x >> y;
            cout << ask(y)-ask(x-1) << endl;
        }
    }
    return 0;
}

记录


by wosile @ 2023-07-06 16:38:43

感觉你的upd不太对劲。


by _Coffice_ @ 2023-07-06 16:39:28

@wosile

您能具体一点吗?


by wosile @ 2023-07-06 16:41:06

@czw20110831 没事,我看错了,抱歉

没用树状数组写过


by _Coffice_ @ 2023-07-06 16:43:23

大佬教我

@wosile


by LgxTpre @ 2023-07-06 17:17:56

@czw20110831 第 27 行应该为 add(1, r+1, -(r+1)*x);


by _Coffice_ @ 2023-07-06 17:20:11

谢谢,已关注二位

@LgxTpre

@wosile


|