#include<algorithm>
using namespace std;
int add[1000];
int st[1000], ed[1000],pos[1000];
long long a[10000];
long long sum[1000] = { 0 };
//初始化块
void init(int n) {
int block = sqrt(n);
int t = n / block;
if (n % block) t++; //t 表示块的数量,如果不是整块,则加上最后的一小块
//遍历块,初始化块的左右端点
for (int i = 1; i <= t; i++) {
st[i] = (i - 1) * block + 1;
ed[i] = i * block;
}
ed[t] = n; //如果最后一块不是整块需要特殊计算
//初始化所有元素所在快的位置
for (int i = 1; i <= n; i++) {
pos[i] = (i - 1) / block + 1;
}
//定义与区间有关的辅助数组,如区间和
for (int i = 1; i <= t; i++) {
for (int j = st[i]; j <= ed[i]; j++) {
sum[i] += a[j];
}
}
}
//区间修改操作
void change(int L, int R, int d) {
int p = pos[L], q = pos[R];
if (p == q) {
for (int i = L; i < R; i++) a[i] += d;
sum[p] += d * (R - L + 1);
}
else {
for (int i = p + 1; i <= q - 1; i++) {
add[i] += d;
}
for (int i = L; i <= ed[p]; i++) {
a[i] += d;
}
sum[p] += d * (ed[p] - L + 1);
for (int i = st[q]; i <= R; i++) {
a[i] += d;
}
sum[q] += d * (R - st[q] + 1);
}
}
//区间查询
long long ask(int L, int R) {
int p = pos[L], q = pos[R];
long long ans = 0;
if (p == q) {
for (int i = L; i <= R; i++) ans += a[i];
//不要忘记块操作
ans += add[p] * (R - L + 1);
}
else {
for (int i = p + 1; i <= q - 1; i++) ans += sum[i] + add[i] * (ed[i] - st[i] + 1);
for (int i = L; i <= ed[p]; i++) {
ans += a[i];
}
ans += add[p] * (ed[p] - L + 1);
for (int i = st[q]; i <= R; i++) {
ans += a[i];
}
ans += add[q] * (R - st[q] + 1);
}
return ans;
}```
标签:初始化,分块,int,long,算法,block,1000
From: https://www.cnblogs.com/oQAQo/p/18402158