我的分块 代码,在 query 中没有特判 L=R 的情况,却拿到了满分。
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 5e5 + 5;
const int M = 7e2 + 10;
int a[N], id[N], l[M], r[M], sum[M];
int n, m;
void add(int x, int k){
a[x] += k;
sum[id[x]] += k;
}
int query(int x, int y){
int L = id[x], R = id[y], res = 0;
for (int i = x; i <= r[L]; i ++){
res += a[i];
}
for (int i = l[R]; i <= y; i ++){
res += a[i];
}
for (int i = L + 1; i < R; i ++){
res += sum[i];
}
return res;
}
signed main(){
cin >> n >> m;
for (int i = 1; i <= n; i ++){
cin >> a[i];
}
int t = sqrt(n), tot = 0;
for (int i = 1; i * t <= n; i ++){
l[i] = (i - 1) * t + 1;
r[i] = i * t;
for (int j = l[i]; j <= r[i]; j ++){
sum[i] += a[j];
id[j] = i;
}
tot = i;
}
if (r[tot] < n){
tot ++;
l[tot] = (tot - 1) * t + 1;
r[tot] = n;
for (int j = l[tot]; j <= r[tot]; j ++){
sum[tot] += a[j];
id[j] = tot;
}
}
// for (int i = 1; i <= tot; i ++){
// cout << l[i] << " " << r[i] << " " << sum[i] << "\n";
// }
while (m --){
int op, x, y;
cin >> op >> x >> y;
if (op == 1){
add(x, y);
}
else{
cout << query(x, y) << "\n";
}
}
return 0;
}
hack:
5 1
1 1 1 1 1
2 1 2
正确输出应该是 2,我的代码输出了 4。