您的位置:首页 > 其它

BZOJ_2002_弹飞绵羊_(LCT)

2016-05-27 22:59 260 查看

描述

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=200000+5;
int n,m;

struct node{
node* ch[2],* pa;
int s;
node(node* t){ s=1; ch[0]=ch[1]=pa=t; }
bool d(){ return pa->ch[1]==this; }
bool c(){ return pa->ch[0]==this||pa->ch[1]==this; }
void setc(node* x,bool d){ ch[d]=x; x->pa=this; }
void push_up(){ s=ch[0]->s+ch[1]->s+1; }
}* 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[1]=y;
}
splay(t);
}
void link(node* x,node* y){
access(x);
x->ch[0]->pa=null; x->ch[0]=null; x->pa=y; x->push_up();
}
int main(){
null=new node(NULL); null->s=0;
scanf("%d",&n);
for(int i=0;i<n;i++) t[i]=new node(null);
for(int i=0;i<n;i++){
int k; scanf("%d",&k);
if(i+k<n) t[i]->pa=t[i+k];
}
scanf("%d",&m);
for(int i=1;i<=m;i++){
int q,x,y;
scanf("%d%d",&q,&x);
if(q==1){
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 0;
}
View Code

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: