题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=2002
题目描述:有n个弹簧排成一列,每个弹簧有一个系数k(k>0),表示可以从当前位置 i弹到 i+k的位置。
有两个操作:1. 修改弹簧 i的弹性系数 2. 询问从 i 位置弹到没有弹簧的位置需要的次数
解题思路:这是一道动态树(link-cut-tree)的入门题目(本弱渣刚刚学会。。。)动态树的思想和树链剖分的思想是相同的,但是树链剖分只能解决静态的树,就是说不能修改树的结构,主要是线段树不够灵活。。。现在同样是维护树链,用的是splay(伸展树)。感觉splay有很多种写法,但是思想都是一样的,主要是splay操作,将某一个节点旋转到这一条链的根节点。动态树的主要操作是access,将某个节点旋转到全局的根。其实还有一点没有说明白,在一开始的时候,一个节点就是一条链!!!也就是在伸展树中没有任何的边,只有n个节点(其实是n+2个)但是在实际的树中这些节点之间是有关系的用一个fa数组来记录。因为access操作是从下往上串起一条链,恩恩
我看了好多博客,一开始都不太明白,一是对splay不了解,另一个是不知道该维护那条链(实际上一开始是没有链让你维护的!!!有了操作之后才进行维护,维护偏爱路径)偏爱路径就是指一个节点被最后一次操作。。好吧,我摘抄一点别人的定义
偏爱子节点(preferred child):如果最后被访问的点在X的儿子P中,那么P为X的偏爱子节点,如果一个点被访问,那么他的偏爱子节点为空
偏爱边(preferred edge):节点到偏爱子节点的边
偏爱路径(preferred path):由偏爱边组成的不可延伸的路径
感觉该说的都说了,建议仔细看一下代码,推荐kuangbin的博客:http://www.cnblogs.com/kuangbin/archive/2013/09/04/3300281.html
还有这个博客:http://www.360doc.com/content/14/0109/09/10504424_343770969.shtml
//#pragma comment(linker,"/STACK:102400000,102400000")
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<string>
#define ll long long
#define db double
#define PB push_back
#define lson k<<1
#define rson k<<1|1
using namespace std;
const int N = 200005;
int ch[N][2],fa[N],a[N],sz[N];
bool rt[N];
void pushup(int k)
{
sz[k]=sz[ch[k][0]]+sz[ch[k][1]]+1;
}
void rotate(int x)
{
int f=fa[x],d=ch[f][1]==x;
ch[f][d]=ch[x][!d],fa[ch[x][!d]]=f;
fa[x]=fa[f],fa[f]=x,ch[x][!d]=f;
if(rt[f]) rt[x]=true,rt[f]=false;
else ch[fa[x]][ch[fa[x]][1]==f]=x;
pushup(f);
}
void Splay(int x)
{
while(!rt[x])
{
int f=fa[x],ff=fa[f];
if(rt[f])
{
rotate(x);
}else
{
if((ch[f][1]==x)==(ch[ff][1]==f)) rotate(f),rotate(x);
else rotate(x),rotate(x);
}
}
pushup(x);
}
void Access(int x)
{
int y=0;
for(;x;x=fa[y=x])
{
Splay(x);
rt[ch[x][1]]=true,rt[ch[x][1]=y]=false;
pushup(x);
}
}
int main()
{
#ifdef PKWV
freopen("in.in","r",stdin);
#endif // PKWV
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
for(int i=0;i<=n+1;i++)
{
ch[i][0]=ch[i][1]=0;
rt[i]=true;
sz[i]=1;
if(i<=n) fa[i]=(i+a[i]>n)?n+1:i+a[i];
}
sz[0]=0;
int m;
scanf("%d",&m);
while(m--)
{
int op,u,v;
scanf("%d%d",&op,&u);
u++;
if(op==1)
{
Access(u);
Splay(u);
printf("%d\n",sz[u]-1);
}else
{
scanf("%d",&v);
Access(u),Splay(u);
fa[ch[u][0]]=fa[u];
rt[ch[u][0]]=true;
ch[u][0]=0;
fa[u]=u+v>n?n+1:u+v;
pushup(u);
}
}
return 0;
}