http://www.lydsy.com/JudgeOnline/problem.php?id=2002
学习分块的时候找到的一道比较模板的题目。
一开始我都想不懂如何分块。后来看到别人的,是说,每个块里面的元素都记录下它需要几步才能离开这个块,并且到达的下一个坐标是多少。
这样的话,对于第一个问题,给定一个坐标问多少步弹飞,最坏的运算量是走完全部分块,也就是sqrt(n)。
对于第二个问题,一开始我这里写错了。在修改一个点的弹力系数的时候,如果是别的区间跳到这个点的话,对别的区间的数字没有影响,但是,如果是同样一个区间的跳点到这个坐标的话,你就要更新该点需要多少步离开这个分块,并且到达的下一个分块的坐标是什么。而我一开始没有更新,所以WA了一发。这里是修改一个分块里面的所有元素,复杂度sqrt(n)。
代码如下:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
int n, a[maxn], cnt[maxn], next[maxn], m;
struct node {
int l, r, sum, lazy;
}block[500];
void change(int x, int val) {
int key = (x - 1) / m;
a[x] = val;
for(int i = block[key].r; i >= block[key].l; i--) {
if(i + a[i] <= block[key].r) {
cnt[i] = cnt[i + a[i]] + 1;
next[i] = next[i + a[i]];
} else {
cnt[i] = 1;
next[i] = i + a[i];
}
}
}
int query(int x) {
int ans = 0;
while(x <= n) {
ans += cnt[x];
x = next[x];
}
return ans;
}
int main() {
scanf("%d", &n);
m = sqrt(n);
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]);
for(int i = 0; i < m; i++) {
block[i].l = i * m + 1;
block[i].r = block[i].l + m - 1;
block[i].sum = 0;
block[i].lazy = 0;
}
if(m * m < n) {
block[m].l = m * m + 1;
block[m].r = n;
block[m].sum = 0;
block[m].lazy = 0;
}
for(int i = n; i > 0; i--) {
int key = (i - 1) / m;
if(i + a[i] <= block[key].r) {
cnt[i] = cnt[i + a[i]] + 1;
next[i] = next[i + a[i]];
} else {
cnt[i] = 1;
next[i] = i + a[i];
}
}
int q, ope, s, val;
scanf("%d", &q);
while(q--) {
scanf("%d", &ope);
if(ope == 1) {
scanf("%d", &s);
printf("%d\n", query(s + 1));
} else {
scanf("%d%d", &s, &val);
change(s + 1, val);
}
}
return 0;
}