您的位置:首页 > 其它

link cut tree模板(LCT模板)

2017-09-27 16:35 357 查看

  update:2017.09.26

#include <bits/stdc++.h>

using namespace std;

struct Link_Cut_Tree
{
static const int MAXN = 100000 + 7;

int ch[MAXN][2], fa[MAXN], rev[MAXN], sz[MAXN];
int sk[MAXN];

bool isroot(int x)
{
return ch[fa[x]][0] != x && ch[fa[x]][1] != x;
}

void reverse(int x)
{
rev[x] ^= 1, swap(ch[x][0],ch[x][1]);
}

void update(int x)
{
sz[x] = sz[ch[x][0]] +  sz[ch[x][1]] +1;
}

void push_down(int x)
{
if(!rev[x]) return ;
if(ch[x][0]) reverse(ch[x][0]);
if(ch[x][1]) reverse(ch[x][1]);
rev[x]=0;
}

void rotate(int x)
{
int f = fa[x], gf = fa[f];
int t1 = ( x != ch[f][0]), t2 = ( f != ch[gf][0]), tmp = ch[x][1^t1];
if(!isroot(f)) ch[gf][0^t2] = x;
fa[tmp] = f, fa[x] = gf, ch[x][1^t1] = f, fa[f] = x, ch[f][0^t1] = tmp;
update(f);
}

void splay(int x)
{
int top = 0;
sk[++top] = x;
for(int i = x; !isroot(i); i = fa[i])   sk[++top] = fa[i];
while(top)  push_down(sk[top--]);
for(int f = fa[x], gf = fa[f]; !isroot(x); rotate(x), f = fa[x],gf = fa[f])
if(!isroot(f))
rotate((x==ch[f][0]) ^ (f==ch[gf][0]) ? x : f);
update(x);
}

void access(int x)
{
for(int p = 0; x; p = x, x = fa[x])
splay(x), ch[x][1] = p, update(x);
}

void makeroot(int x)
{
access(x), splay(x), reverse(x);
}

int findroot(int x)
{
access(x), splay(x);
while(ch[x][0]) x = ch[x][0];
return x;
}
void link(int x,int y)
{
makeroot(x), fa[x] = y;
}

void cut(int x,int y)
{
makeroot(x), access(y), splay(y);
if(ch[y][0] == x)   ch[y][0] = fa[x] = 0;
update(y);
}

void debug(void)
{
for(int i=1;i<=100;i++)
printf("%d %d %d %d %d %d %d\n",i,fa[i],ch[i][0],ch[i][1],rev[i],sz[i]);
}
}lct;

int main(void)
{

return 0;
}

 

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