FuZekai_ @ 2024-03-24 12:02:15
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n, m;
ll a[100005], tree[100005 << 2], mark[100005 << 2];
int build(ll l, ll r, ll p){
if(l == r){
tree[p] = a[l];
return 0;
}
ll mid = (l + r) / 2;
build(l, mid, p * 2);
build(mid + 1, r, p * 2 + 1);
tree[p] = tree[p * 2] + tree[p * 2 + 1];
return 0;
}
int push_down(ll p, ll len){
mark[p * 2] += mark[p];
mark[p * 2 + 1] += mark[p];
tree[p * 2] += (len - len / 2) * mark[p];
tree[p * 2 + 1] += (len / 2) * mark[p];
mark[p] = 0;
return 0;
}
int add(ll l, ll r, ll d, ll p, ll cl, ll cr){
if(cr < l or cl > r) return 0;
if(cr <= r and cl >= l){
tree[p] += (cr - cl + 1) * d;
if(cr > cl) mark[p] += d;
return 0;
}
ll mid = (cl + cr) / 2;
push_down(p, cr - cl + 1);
add(l, r, d, p * 2, cl, mid);
add(l, r, d, p * 2 + 1, mid + 1, cr);
tree[p] = tree[p*2] + tree[p*2+1];
}
int query(ll l, ll r, ll p, ll cl, ll cr){
if(cr < l or cl > r) return 0;
if(cr <= r and cl >= l){
return tree[p];
}
ll mid = (cl + cr) / 2;
push_down(p, cr - cl + 1);
return query(l, r, p * 2, cl, mid) + query(l, r, p * 2 + 1, mid + 1, cr);
}
int main(){
ios::sync_with_stdio(0);
cin >> n >> m;
for(int i = 1; i <= n; i ++) cin >> a[i];
build(1, n, 1);
while(m--){
short method;
cin >> method;
if(method == 2){
ll l, r;
cin >> l >> r;
cout << query(l, r, 1, 1, n) << endl;
}else{
ll l, r, k;
cin >> l >> r >> k;
add(l, r, k, 1, 1, n);
}
}
return 0;
}
by 梧桐灯 @ 2024-03-24 12:12:30
你query是int
by _wsq_ @ 2024-03-24 12:15:26
query 函数的返回值没开 long long 导致的
by _wsq_ @ 2024-03-24 12:18:16
另外你的 add 函数也有问题,返回值不为 void 的情况下没有 return,导致开 O2 过不了不开 O2 能过,建议把 add 函数返回值改成 void
by FuZekai_ @ 2024-03-24 14:21:42
@梧桐灯 感谢
by FuZekai_ @ 2024-03-24 14:24:08
@54Tiger 感谢