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 }

 

posted @ 2017-09-27 16:35  weeping  阅读(184)  评论(0编辑  收藏  举报