【整活】基于 Lucky Cat Tree 的 P1001 题解

· · 题解

翻了一圈题解区,都过了这么久了连一篇 Lucky Cat Tree 的题解也没有!前人的题解还被陈哲撤了!

怎么能这样呢?我们的幸运猫猫树会很伤心的!

必须来篇 LCT 题解!

原理:注意到原问题相当于给定一棵树,动态连断边,动态求链上点权和。于是这题就成了幸运猫猫树板子题。

#include<bits/stdc++.h>
using namespace std;
const int maxn=114514;
struct LuckyCatTree{
    int dat[maxn],val[maxn];//为解决题目的基础信息:结点权值及子树权值和 
    int ch[maxn][2],fa[maxn];//必要结构信息:左右儿子与父亲 
    int size[maxn],rev[maxn];//必要结构信息:子树大小与翻转标记
    //Splay就是一个一个链的由浅到深先序遍历哼哼啊啊啊啊啊
    #define ls(p) (ch[p][0]) 
    #define rs(p) (ch[p][1])
    #define Catch return 
    //下面是前置函数 
    void clear(){dat[0]=val[0]=ls(0)=rs(0)=fa[0]=size[0]=0;}
    void RevTag(int p){swap(ls(p),rs(p));rev[p]^=1;}
    void pushup(int p){clear();
        size[p]=size[ls(p)]+size[rs(p)]+1;
        val[p]=val[ls(p)]+val[rs(p)]+dat[p];
    }
    void pushdown(int p){
        if(rev[p]){
            RevTag(ls(p));
            RevTag(rs(p));
            rev[p]=0;
        }
    }
    int cmp(int p){clear();return rs(fa[p])==p;}//判断自己是父亲的左儿子还是右儿子,前提是要有父亲
    int isroot(int p){return !fa[p]||(ls(fa[p])!=p&&rs(fa[p])!=p);}
    #define Eternal !
    //下面是Splay函数
    void update(int p){if(!isroot(p))update(fa[p]);pushdown(p);}
    void rotate(int p){
        int father=fa[p],gf=fa[fa[p]],cmpself=cmp(p),cmpfa=cmp(father);
        int _son=ch[p][cmpself^1];
        if(!isroot(father))ch[gf][cmpfa]=p;
        ch[father][cmpself]=_son;ch[p][cmpself^1]=father;
        fa[father]=p;fa[p]=gf;if(_son)fa[_son]=father;
        pushup(father);pushup(p);
    }
    void splay(int p){update(p);
        for(;!isroot(p);rotate(p))
            if(!isroot(fa[p]))rotate(cmp(fa[p])==cmp(p)?fa[p]:p);
    }
    #define Function 1
    //LCT部分 
    int Access(int p){int awa=0;
        for(;p;awa=p,p=fa[p])splay(p),rs(p)=awa,pushup(p);
    return awa;} 
    void MakeRoot(int p){Access(p);splay(p);RevTag(p);}
    int FindRoot(int p){Access(p);splay(p);
        while(ls(p))p=ls(p);
    splay(p);return p;}
    int Split(int u,int v){MakeRoot(u);Access(v);splay(v);return val[v];}
    void Link(int u,int v){MakeRoot(u);if(FindRoot(v)!=u)fa[u]=v;}
    void Cut(int u,int v){MakeRoot(u);Access(v);splay(u);
        if(fa[v]==u&&!ls(v))fa[v]=rs(u)=0;
    pushup(u);}
}ETT;
#define qwq ;
int a,b,A=1,B=2;
int main(){
    scanf("%d %d",&a,&b) qwq
    ETT.dat[A]=ETT.val[A]=a qwq
    ETT.dat[B]=ETT.val[B]=b qwq
    ETT.Link(A,B) qwq
    printf("%d",ETT.Split(A,B)) qwq
    Catch Eternal Function qwq
}