# CodeChef Chef and Churu(分块)

### 题目链接

$\ \ \ \ \ \$$n$$n$个数$m$$m$个操作，操作分两种：
$1\ \ x\ \ y：$${a}_{x}赋值为y$$a_x赋值为y$
$2\ \ x\ \ y：$$\sum _{i=x}^{y}{f}_{i}$$\sum \limits_{i = x}^{y}f_i$，其中${f}_{i}=\sum _{j={l}_{i}}^{{r}_{i}}{a}_{j}$$f_i = \sum \limits_{j = l_i}^{r_i}a_j$

$\ \ \ \$可以考虑对$f$$f$分块，维护每个块内的和，统计每个下标$i$$i$在每个块中出现的次数，那么对于$1$$1$操作，假设在块$b$$b$$x$$x$出现了$t$$t$次，$x$$x$位置当前值为${a}_{x}$$a_x$，那么${b}_{x}$$b_x$的更新为：$su{m}_{b}=su{m}_{b}+ty-t{a}_{x}$$sum_b =sum_b + t y - t a_x$，对于块内的和，直接树状数组更新求值，时间复杂度$O\left(n\sqrt{n}\mathrm{log}n\right)$$O(n\sqrt n \log n)$

#include<bits/stdc++.h>
typedef unsigned long long ull;
typedef long long ll;
const int maxn = 1e5 + 10;
using namespace std;

int n, m, T, kase = 1, block_size;
int a[maxn], l[maxn], r[maxn];
ll block_sum[maxn], C[maxn];
int show[350][maxn];

void update(int x, int val) { for(; x <= n; x += x & -x) C[x] += val; }
ll get_sum(int x) { ll ans = 0; for(; x; x -= x & -x) ans += C[x]; return ans; }

void init() {
int st = 0, num = 0;
block_size = sqrt(n) + 2;
memset(block_sum, 0, sizeof block_sum);
memset(C, 0, sizeof C);
for(int i = 0; i < n; i++) {
update(l[i] + 1, 1);
update(r[i] + 2, -1);
st++;
if(st == block_size || i == n - 1) {
for(int i = 0; i < n; i++) {
show[num][i] = get_sum(i + 1);
block_sum[num] += (ll)show[num][i] * a[i];
}
memset(C, 0, sizeof C);
num++; st = 0;
}
}
for(int i = 1; i <= n; i++) update(i, a[i - 1]);
}

ull query(int x, int y) {
int b1 = (x + 1) / block_size;
int b2 = (y + 1) / block_size;
ull ans = 0;
if(b1 == b2) {
for(int i = x; i <= y; i++)
ans += get_sum(r[i] + 1) - get_sum(l[i]);
return ans;
}
for(int i = b1 + 1; i < b2; i++) ans += block_sum[i];
int l1 = (b1 + 1) * block_size;
int l2 = b2 * block_size;
for(int i = x; i < l1; i++) ans += get_sum(r[i] + 1) - get_sum(l[i]);
for(int i = l2; i <= y; i++) ans += get_sum(r[i] + 1) - get_sum(l[i]);
return ans;
}

void update(int id, int x, int y) {
a[id] = y;
update(id + 1, -x);
update(id + 1, y);
int tot = n / block_size;
if(n % block_size) tot++;
for(int i = 0; i < tot; i++) {
int tm = show[i][id];
block_sum[i] += (ll)y * tm;
block_sum[i] -= (ll)x * tm;
}
}

int main() {
while(scanf("%d", &n) != EOF) {
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
for(int i = 0; i < n; i++) {
scanf("%d %d", &l[i], &r[i]);
l[i]--; r[i]--;
}
init(); scanf("%d", &m);
while(m--) {
int op, x, y;
scanf("%d %d %d", &op, &x, &y);
if(op == 1) update(x - 1, a[x - 1], y);
else printf("%llu\n", query(x - 1, y - 1));
}
}
return 0;
}