LOJ 数列分块入门4
题目:
题解:
- 深刻理解分块中tag和val的含义。
- 暴力修改时直接修改原数组 + 修改val
- 块修改时修改tag和val
- 暴力查询时查询原数组+tag的和
- 块查询时直接查询val
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#define N 50005
#define LL long long
using namespace std;
struct Blo {LL l, r, tag, val;} blo[N];
LL n, num, size;
LL a[N], bel[N];
LL read() {
LL x = 0, f = 1; char c = getchar();
while (c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
while (c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
return x *= f;
}
void build() {
size = (LL)sqrt(n), num = n / size;
if(n % size) num++;
for (LL i = 1; i <= n; i++) bel[i] = (i - 1) / size + 1;
for (LL i = 1; i <= num; i++) {
blo[i].l = (i - 1) * size + 1;
blo[i].r = i * size;
}
blo[num].r = n;
for (LL i = 1; i <= num; i++)
for (LL j = blo[i].l; j <= blo[i].r; j++)
blo[i].val += a[j];
}
void update(LL l, LL r, LL c) {
if(bel[l] == bel[r]) {
for (LL i = l; i <= r; i++) a[i] += c;
blo[bel[l]].val += (r - l + 1) * c;
return;
}
for(LL i = l; i <= blo[bel[l]].r; i++) a[i] += c;
for(LL i = r; i >= blo[bel[r]].l; i--) a[i] += c;
for(LL i = bel[l] + 1; i < bel[r]; i++) {
blo[i].tag += c;
blo[i].val += (blo[i].r - blo[i].l + 1) * c;
}
blo[bel[l]].val += (blo[bel[l]].r - l + 1) * c;
blo[bel[r]].val+= (r - blo[bel[r]].l + 1) * c;
}
LL ask(LL l, LL r, LL mod) {
LL ans = 0;
if(bel[l] == bel[r]) {
for(LL i = l; i <= r; i++) {
ans += a[i], ans %= mod;
ans += blo[bel[l]].tag, ans %= mod;
}
return ans;
}
for(LL i = l; i <= blo[bel[l]].r; i++) {
ans += a[i], ans %= mod;
ans += blo[bel[l]].tag, ans %= mod;
}
for(LL i = r; i >= blo[bel[r]].l; i--) {
ans += a[i], ans %= mod;
ans += blo[bel[r]].tag, ans %= mod;
}
for(LL i = bel[l] + 1; i < bel[r]; i++) {
ans += blo[i].val;
ans %= mod;
}
return ans;
}
int main() {
cin >> n;
for (LL i = 1; i <= n; i++) a[i] = read();
build();
for (LL i = 1; i <= n; i++) {
LL op = read(), l = read(), r = read(), c = read();
if(!op) update(l, r, c);
else printf("%lld\n", ask(l, r, c + 1));
}
return 0;
}