HNOI 2010 弹飞绵羊 分块

来源:互联网 发布:局域网内文件传输软件 编辑:程序博客网 时间:2024/05/16 02:02

这题以前是用LCT写的,然后某考试中发现分块大法妙,要去学习,
首先来水一水题
我以前的LCT

思路
把弹簧分块,然后维护两个信息:
1.走出当前分块需要几步;
2.走出当前分块后到了哪个点。
于是修改弹簧x的时候就把本块中的起始位置到x重算一遍,
  查询弹簧x的时候就按第二个信息一直跳,一次跳出一个分块,每次加上第一个信息即可
效率O((n+m)n2)

感想
分块大法好,分块大法短,分快大法妙

代码

#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>#include<iostream>#include<algorithm>#define For(i, a, b) for(int i = (a); i <= (int)(b); ++i)#define Forr(i, a, b) for(int i = (a); i >= (int)(b); --i)#define N (200000+5)#define SN (500+5)using namespace std;int n, siz, jump[N], bnum[N], blo[SN][SN];int tot[N], pos[N];void Insert(int nc, int now){    int en = min(nc*siz, n), id = now;    tot[id] = 0;    if(now+jump[now] <= en){        now += jump[now];        tot[id] = tot[now]+1, pos[id] = pos[now]; return;    }    ++tot[id]; pos[id] = now+jump[now];}void Modify(int nc, int now){    int be = (nc-1)*siz+1;    Forr(i, now, be) Insert(nc, i);}int Query(int now){    int ans = 0;    while(now <= n){        ans += tot[now]; now = pos[now];    }    return ans;}int main(){#ifndef ONLINE_JUDGE    freopen("test.in", "r", stdin);    freopen("test.out", "w", stdout);#endif    int m;    scanf("%d", &n);    siz = (int)sqrt(n);    For(i, 1, n){        bnum[i] = (i-1)/siz+1; scanf("%d", &jump[i]);    }    Forr(i, n, 1) Insert(bnum[i], i);    scanf("%d", &m);    int op, x, y;    while(m--){        scanf("%d%d", &op, &x);        ++x;        if(op == 1) printf("%d\n", Query(x));        else{            scanf("%d", &y); jump[x] = y;            Modify(bnum[x], x);        }    }    return 0;}
0 0