10f,求助

P3372 【模板】线段树 1

Jiji2012 @ 2024-10-30 13:27:03

#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll s[100005];
int n ,m;
ll d[270000], b[270000];
void build(ll l, ll r, ll t){
    if(r == l){
        d[t] = s[l];
        return ;
    }
    ll m = (r + l) >> 1;
    build(l, m, t << 1);
    build(m + 1, r, (t << 1) | 1);
    d[t] = d[t << 1] + d[(t << 1) | 1];
    return;
}
void update(ll x, ll y, ll k, ll l, ll r, ll t){
    if(x <= l && r <= y){
        d[t] += (r - l + 1) * k;
        b[t] = k;
        return ;
    }
    ll m = (r + l) >> 1;
    if(b[t]){
        d[t << 1] += b[t] * (m - l + 1);
        d[(t << 1) | 1] += b[t] * (r - m);
        b[t << 1] += b[t];
        b[(t << 1) | 1] += b[t];
    }
    b[t] = 0;
    if(y > m){
        update(x, y, k, m + 1, r, (t << 1) | 1);
    }
    if(x <= m){
        update(x, y, k, l, m, t << 1);
    }
    d[t] = d[t << 1] + d[(t << 1) | 1];
}
ll getsum(ll x, ll y, ll l, ll r, ll t){
    if(x <= l && r <= y){
        return d[t];
    }
    ll m = (r + l) >> 1;
    if(b[t]){
        d[t << 1] += b[t] * (m - l + 1);
        d[(t << 1) | 1] += b[t] * (r - m);
        b[t << 1] += b[t];
        b[(t << 1) | 1] += b[t]; 
    }
    b[t] = 0;
    ll sum = 0;
    if(y > m){
        sum += getsum(x, y, m + 1, r, (t << 1) | 1);
    }
    if(x <= m){
        sum += getsum(x, y, l, m, t << 1);
    }
    return sum;
}
int main(){
    cin >> n >> m;
    for(int i = 1; i <= n; i++){
        cin >> s[i]; 
    }
    build(1, n, 1);
    ll x, y, k;
    while(m--){
        int a;
        cin >> a;
        if(a == 1){
            cin >> x >> y >> k;
            update(x, y, k, 1, n, 1);
        }else{
            cin >> x >> y;
            cout << getsum(x, y, 1, n, 1) << endl;
        }
    }
    return 0;
}

by Karl_Aldrich @ 2024-10-30 13:54:59

区间修改函数挂了,应该是懒标加上修改值而不是让懒标直接等于修改值


|