SP8791 解题报告

· · 题解

前言

LCT 题单里的,刚好我的总结文章里把这题当做了练习题,就写篇题解吧。

思路分析

LCT 是可以求 LCA 的!

那怎么求 LCA 呢?

先对其中的一个点 access(这里假定为 x),这样的话这个点到根的路径都变成了实边。

不难得到的是,x,y 的 LCA 一定在 x 到根的路径上。

所以 x,y 的 LCA 指向 x 的路径已经变成了实边,那么指向 y 的路径就是虚边了。

这个时候我们只需要 access 一下 y,那么在这条路径上的最后一条虚边的父亲即为 LCA。

但是唯一需要注意的是求 LCA 的时候,link 和 cut 不能用 makert 写,不然的话父子关系会变。

代码

#include <bits/stdc++.h>
#define ls son[x][0]
#define rs son[x][1]
#define int long long
using namespace std;
const int N=100010,mod=1e9+7,INF=0x3f3f3f3f3f3f3f3f,M=200010,S=N+M;
int n;
int f[S],s[S],son[S][2],st[S],w[S],r[S],mp[S];
static char buf[1000000],*paa=buf,*pd=buf;
#define getchar() paa==pd&&(pd=(paa=buf)+fread(buf,1,1000000,stdin),paa==pd)?EOF:*paa++
inline int read(void){
    int u(0),t(1);char fc(getchar());
    while(!isdigit(fc)){if(fc=='-') t=-1;fc=getchar();}
    while(isdigit(fc)) u=(u<<1)+(u<<3)+(fc^48),fc=getchar();
    return u*t;
}
inline void print(int u)
{
    if(u<0) putchar('-'),u=-u;
    if(u>9) print(u/10);
    putchar(u%10+'0');
}
inline int ksm(int a,int b,int mod)
{
    int u=a%mod,res=1;
    while(b)
    {
        if(b&1) res=res*u%mod;
        b>>=1;u=u*u%mod;
    }
    return res;
}
bool ntrt(int x){return son[f[x]][1]==x||son[f[x]][0]==x;}
void pushson(int x){swap(ls,rs),r[x]^=1;}
void pushdown(int x)
{
    if(r[x])
    {
        if(ls) pushson(ls);
        if(rs) pushson(rs);
        r[x]=0;
    }
}
void rotate(int x)
{
    int y=f[x],z=f[y],k=(son[y][1]==x),w=son[x][!k];
    if(ntrt(y)) son[z][son[z][1]==y]=x;son[x][!k]=y;son[y][k]=w;
    if(w) f[w]=y;f[y]=x;f[x]=z;
}
void Splay(int x)
{
    int y=x,tot=0;st[++tot]=y;
    while(ntrt(y)) st[++tot]=y=f[y];
    while(tot) pushdown(st[tot--]);
    while(ntrt(x))
    {
        y=f[x];int z=f[y];
        if(ntrt(y)) rotate((son[y][0]==x)^(son[z][0]==y)?x:y);
        rotate(x);
    }
}
int access(int x){int y;for(y=0;x;x=f[y=x]) Splay(x),rs=y;return y;}
void makert(int x){access(x);Splay(x);pushson(x);}
int findrt(int x)
{
    access(x);Splay(x);
    while(ls) pushdown(x),x=ls;
    Splay(x);return x;
}
void split(int x,int y){makert(x);access(y);Splay(y);}
void link(int x,int y){makert(x);if(findrt(y)!=x)f[x]=y;}
void cut(int x)
{
    access(x);Splay(x);
    ls=f[ls]=0;
}
signed main()
{
    n=read(),n=read();
    for(int i=1,u,v;i<=n;i++)
    {
        char op=getchar();if(op!='l'&&op!='c') op=getchar();
        if(op=='c') u=read(),cut(u);
        else
        {
            op=getchar();u=read(),v=read();
            if(op=='i') link(u,v);
            else access(u),print(access(v)),puts("");
        }
    }
    return 0;
}