BZOJ_2002_弹飞绵羊_(LCT)

时间:2023-03-09 02:54:20
BZOJ_2002_弹飞绵羊_(LCT)

描述


http://www.lydsy.com/JudgeOnline/problem.php?id=2002

一列n个数,a[i]表示向后a[i]个,问第k个数进行多少次向后跳跃会飞出去.

分析


i连向i+a[i],那么我们建立一个森林,i是i+a[i]的一个子节点,如果i+a[i]>n,那么i连向null.这样对于节点k,问多少次飞出去,就是向上走多少个到null,也就是深度是多少,直接LCt处理.

注意:

1.这里的link并不以LCT中普遍的link.普通的link是将两个不想连的点连在一起,这样两棵树也就连在了一起.这里的link其实是改变父亲节点的意思.

 #include <bits/stdc++.h>
using namespace std; const int maxn=+;
int n,m; struct node{
node* ch[],* pa;
int s;
node(node* t){ s=; ch[]=ch[]=pa=t; }
bool d(){ return pa->ch[]==this; }
bool c(){ return pa->ch[]==this||pa->ch[]==this; }
void setc(node* x,bool d){ ch[d]=x; x->pa=this; }
void push_up(){ s=ch[]->s+ch[]->s+; }
}* null,* t[maxn];
void rot(node* x){
node* pa=x->pa; bool d=x->d();
if(pa->c()) pa->pa->setc(x,pa->d());
else x->pa=pa->pa;
pa->setc(x->ch[!d],d);
x->setc(pa,!d);
pa->push_up();
}
void splay(node* x){
while(x->c())
if(!x->pa->c()) rot(x);
else x->d()==x->pa->d()?(rot(x->pa),rot(x)):(rot(x),rot(x));
x->push_up();
}
void access(node* x){
node* t=x;
for(node* y=null;x!=null;y=x, x=x->pa){
splay(x);
x->ch[]=y;
}
splay(t);
}
void link(node* x,node* y){
access(x);
x->ch[]->pa=null; x->ch[]=null; x->pa=y; x->push_up();
}
int main(){
null=new node(NULL); null->s=;
scanf("%d",&n);
for(int i=;i<n;i++) t[i]=new node(null);
for(int i=;i<n;i++){
int k; scanf("%d",&k);
if(i+k<n) t[i]->pa=t[i+k];
}
scanf("%d",&m);
for(int i=;i<=m;i++){
int q,x,y;
scanf("%d%d",&q,&x);
if(q==){
access(t[x]);
printf("%d\n",t[x]->s);
}
else{
scanf("%d",&y);
if(x+y<n) link(t[x],t[x+y]);
else link(t[x],null);
}
}
return ;
}