BZOJ 2002: [Hnoi2010]Bounce 弹飞绵羊(分块)

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值