题目描述
某天,Lostmonkey发明了一种超级弹力装置,为了在他的绵羊朋友面前显摆,他邀请小绵羊一起玩个游戏。游戏一开始,Lostmonkey在地上沿着一条直线摆上n个装置,每个装置设定初始弹力系数ki,当绵羊达到第i个装置时,它会往后弹ki步,达到第i+ki个装置,若不存在第i+ki个装置,则绵羊被弹飞。绵羊想知道当它从第i个装置起步时,被弹几次后会被弹飞。为了使得游戏更有趣,Lostmonkey可以修改某个弹力装置的弹力系数,任何时候弹力系数均为正整数。
输入格式:
第一行包含一个整数n,表示地上有n个装置,装置的编号从0到n-1。
接下来一行有n个正整数,依次为那n个装置的初始弹力系数。
第三行有一个正整数m,
接下来m行每行至少有两个数i、j,若i=1,你要输出从j出发被弹几次后被弹飞,若i=2则还会再输入一个正整数k,表示第j个弹力装置的系数被修改成k。
输出格式:
对于每个i=1的情况,你都要输出一个需要的步数,占一行。
输入样例:
4 1 2 1 1 3 1 1 2 1 1 1 1
输出样例:
2
3
说明 对于100%的数据n<=200000,m<=100000
题意: 每个点x可以往后跳a[x],支持修改a[x], 问跳多少次大于n
首先,对于每个点x,我们把x,x+a[x]连一条边
表示x可以调到x+a[x]
如果x+a[x]>n 反正都出去了,我们就都向n+1连一条边
问题即为求x跳多少次到n+1 , 即以n+1为根,x的深度
我们发现 对于询问 我们先Makeroot(n+1) , 再 Access(x) , Splay(x)
因为x最深,所以x右儿子的size就是它的深度
对于操作,我们先Cut原来的,再Link就可以了
#include<bits/stdc++.h>
#define N 200005
using namespace std;
struct Node{
int ch[2],fa,size,tag;
}t[N];
int n,m,a[N];
int read(){
int cnt=0,f=1;char ch=0;
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch))cnt=cnt*10+(ch-'0'),ch=getchar();
return cnt*f;
}
bool isRoot(int x){
int fa=t[x].fa; if(fa==0) return true;
return t[fa].ch[0]!=x && t[fa].ch[1]!=x;
}
void Pushup(int x){
t[x].size=t[t[x].ch[0]].size+t[t[x].ch[1]].size+1;
}
void Pushdown(int x){
if(t[x].tag){
swap(t[x].ch[0],t[x].ch[1]);
t[t[x].ch[0]].tag^=1;
t[t[x].ch[1]].tag^=1;
t[x].tag=0;
}
}
void Pushpath(int x){
if(!isRoot(x)) Pushpath(t[x].fa);
Pushdown(x);
}
void rotate(int x){
int y=t[x].fa,z=t[y].fa;
int k=t[y].ch[1]==x;
if(!isRoot(y)) t[z].ch[t[z].ch[1]==y]=x;
t[x].fa=z;
t[y].ch[k]=t[x].ch[k^1];
t[t[x].ch[k^1]].fa=y;
t[x].ch[k^1]=y,t[y].fa=x;
Pushup(y),Pushup(x);
}
void Splay(int x){
Pushpath(x);
while(!isRoot(x)){
int y=t[x].fa,z=t[y].fa;
if(!isRoot(y))
(t[y].ch[0]==x)^(t[z].ch[0]==y)?rotate(x):rotate(y);
rotate(x);
}Pushup(x);
}
void Access(int x){
for(int y=0;x;y=x,x=t[x].fa)
Splay(x),t[x].ch[1]=y,Pushup(x);
}
void Makeroot(int x){
Access(x),Splay(x),t[x].tag^=1;
}
int Findroot(int x){
Access(x),Splay(x);
while(t[x].ch[0])Pushdown(x),x=t[x].ch[0];
return x;
}
void Link(int x,int y){
Makeroot(x);
if(Findroot(y)!=x) t[x].fa=y;
}
void Cut(int x,int y){
Makeroot(x),Access(y),Splay(y);
t[y].ch[0]=0,t[x].fa=0,Pushup(y);
}
int Quary(int x){
Makeroot(n+1),Access(x),Splay(x);
return t[t[x].ch[0]].size;
}
int main(){
n=read();
for(int i=1;i<=n;i++){a[i]=read(); int x=(i+a[i]>n)?n+1:i+a[i];Link(i,x);}
m=read();
while(m--){
int op=read(),x=read()+1;
if(op==1) printf("%d\n",Quary(x));
else{
int y=read();
if(x+a[x]>n) Cut(x,n+1);
else Cut(x,x+a[x]);
a[x]=y; int p=(x+a[x]>n)?n+1:x+a[x];
Link(x,p);
}
}
}