link cut tree模板(LCT模板)

  update:2017.09.26

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 struct Link_Cut_Tree
 6 {
 7     static const int MAXN = 100000 + 7;
 8 
 9     int ch[MAXN][2], fa[MAXN], rev[MAXN], sz[MAXN];
10     int sk[MAXN];
11 
12     bool isroot(int x)
13     {
14         return ch[fa[x]][0] != x && ch[fa[x]][1] != x;
15     }
16 
17     void reverse(int x)
18     {
19         rev[x] ^= 1, swap(ch[x][0],ch[x][1]);
20     }
21 
22     void update(int x)
23     {
24         sz[x] = sz[ch[x][0]] +  sz[ch[x][1]] +1;
25     }
26 
27     void push_down(int x)
28     {
29         if(!rev[x]) return ;
30         if(ch[x][0]) reverse(ch[x][0]);
31         if(ch[x][1]) reverse(ch[x][1]);
32         rev[x]=0;
33     }
34 
35     void rotate(int x)
36     {
37         int f = fa[x], gf = fa[f];
38         int t1 = ( x != ch[f][0]), t2 = ( f != ch[gf][0]), tmp = ch[x][1^t1];
39         if(!isroot(f)) ch[gf][0^t2] = x;
40         fa[tmp] = f, fa[x] = gf, ch[x][1^t1] = f, fa[f] = x, ch[f][0^t1] = tmp;
41         update(f);
42     }
43 
44     void splay(int x)
45     {
46         int top = 0;
47         sk[++top] = x;
48         for(int i = x; !isroot(i); i = fa[i])   sk[++top] = fa[i];
49         while(top)  push_down(sk[top--]);
50         for(int f = fa[x], gf = fa[f]; !isroot(x); rotate(x), f = fa[x],gf = fa[f])
51         if(!isroot(f))
52             rotate((x==ch[f][0]) ^ (f==ch[gf][0]) ? x : f);
53         update(x);
54     }
55 
56     void access(int x)
57     {
58         for(int p = 0; x; p = x, x = fa[x])
59             splay(x), ch[x][1] = p, update(x);
60     }
61 
62     void makeroot(int x)
63     {
64         access(x), splay(x), reverse(x);
65     }
66 
67     int findroot(int x)
68     {
69         access(x), splay(x);
70         while(ch[x][0]) x = ch[x][0];
71         return x;
72     }
73     void link(int x,int y)
74     {
75         makeroot(x), fa[x] = y;
76     }
77 
78     void cut(int x,int y)
79     {
80         makeroot(x), access(y), splay(y);
81         if(ch[y][0] == x)   ch[y][0] = fa[x] = 0;
82         update(y);
83     }
84 
85     void debug(void)
86     {
87         for(int i=1;i<=100;i++)
88             printf("%d %d %d %d %d %d %d\n",i,fa[i],ch[i][0],ch[i][1],rev[i],sz[i]);
89     }
90 }lct;
91 
92 int main(void)
93 {
94 
95 
96     return 0;
97 }

 

转载于:https://www.cnblogs.com/weeping/p/7602506.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值