Link-Cut-Trees 模板
Aaron_Romeo · · 算法·理论
#include <iostream>
const int N = 1e5;
inline int read() {int x; return scanf("%d", &x), x;}
int fath[N + 5], son[N + 5][2], val[N + 5], sum[N + 5], lazy[N + 5]; // lazy[u] 表示 u 的信息对了, u 儿子的信息不对
inline int is_root(int u) {return son[fath[u]][0] != u && son[fath[u]][1] != u;} // u 是否是 splay 的根
inline void push_up(int u) {sum[u] = sum[son[u][0]] + sum[son[u][1]] + val[u];}
inline void exchange(int u) {if (!u) return ; std :: swap(son[u][0], son[u][1]), lazy[u] ^= 1;} // 使 u 信息正确, 在 lazy[u] 上打标记
inline void push_down(int u) {if (!lazy[u]) return ; exchange(son[u][0]), exchange(son[u][1]), lazy[u] = 0;} // 使 u 的儿子信息正确
inline int get_type(int u) {return son[fath[u]][1] == u;} // u 是根则返回 0
inline void rotate(int u) {int v = fath[u], w = fath[v], t = get_type(u); fath[u] = w; !is_root(v) && (son[w][get_type(v)] = u); son[v][t] = son[u][!t]; son[u][!t] && (fath[son[u][!t]] = v); son[u][!t] = v, fath[v] = u; push_up(v), push_up(u);}
inline void splay(int u) {static int p[N + 5], idx, now; p[ ++ idx] = now = u; while (!is_root(now)) p[ ++ idx] = now = fath[now]; while (idx) push_down(p[idx -- ]); int f = fath[u]; for ( ; !is_root(u); rotate(u), f = fath[u]) if (!is_root(f)) rotate(get_type(u) == get_type(f) ? f : u);} // 必定 push_down(u)
inline void access(int u) {for (int v = 0; u; u = fath[v = u]) splay(u), son[u][1] = v, push_up(u);}
inline void change_root(int u) {access(u), splay(u), exchange(u);} // 使 u 变成 splay 的根, u 在 splay 上没有左儿子
inline int get_root(int u) {access(u), splay(u); while (son[u][0]) push_down(u = son[u][0]); return splay(u), u;} // 获得 u 到树根的路径, 使树根变成 splay 的根, u 在 splay 上没有右儿子
inline int is_connect(int u, int v) {return change_root(u), get_root(v) == u;} // 连通则 u 成为树根, 获得 u 到 v 的路径, 使 u 变成 splay 的根, u 在 splay 上没有左儿子 ; 不连通则 u 成为树根, 获得 v 到树根的路径, 使树根变成 splay 的根, v 在 splay 上没有右儿子
inline int split(int u, int v) {return !is_connect(u, v) ? 0 : sum[u];} // 连通则 u 成为树根, 获得 u 到 v 的路径, 使 u 变成 splay 的根, u 在 splay 上没有左儿子 ; 不连通则 u 成为树根, 获得 v 到树根的路径, 使树根变成 splay 的根, v 在 splay 上没有右儿子
inline int link(int u, int v) {return is_connect(u, v) ? 0 : (fath[u] = v, 1);} // 连通则 u 成为树根, 获得 u 到 v 的路径, 使 u 变成 splay 的根, u 在 splay 上没有左儿子 ; 不连通则获得 v 到树根的路径, 使树根变成 splay 的根, v 在 splay 上没有右儿子
inline int cut(int u, int v) {return !is_connect(u, v) || fath[v] != u || son[v][0] ? 0 : (fath[v] = son[u][1] = 0, push_up(u), 1);} // 成功则 v 成为树根, u 和 v 成为 splay 的根且没有儿子 . 失败则 连通则 u 成为树根, 获得 u 到 v 的路径, 使 u 变成 splay 的根, u 在 splay 上没有左儿子 ; 不连通则 u 成为树根, 获得 v 到树根的路径, 使树根变成 splay 的根, v 在 splay 上没有右儿子
int main()
{
int n = read();
for (int i = 1; i <= n; i ++ ) val[i] = read();
int m = read();
while (m -- )
{
char s[15];
scanf("%s", s + 1);
int x = read(), y = read();
if (s[1] == 'b')
{
if (link(x, y)) puts("yes");
else puts("no");
}
if (s[1] == 'p') splay(x), val[x] = y;
if (s[1] == 'e')
{
int t = split(x, y);
if (t) printf("%d\n", t);
else puts("impossible");
}
}
return 0;
}