loj6038「雅礼集训 2017 Day5」远行(lct+树的直径)

版权声明:转载附上原文地址即可~欢迎各位神犇来虐~ https://blog.csdn.net/Icefox_zhx/article/details/80119287

维护一下树的直径,用lct动态维护两点间距离。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 300010
inline char gc(){
    static char buf[1<<16],*S,*T;
    if(S==T){T=(S=buf)+fread(buf,1,1<<16,stdin);if(T==S) return EOF;}
    return *S++;
}
inline int read(){
    int x=0,f=1;char ch=gc();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=gc();
    return x*f;
}
int n,m,pa[N],fa[N],c[N][2],sz[N],d1[N],d2[N],lastans=0,q[N];
bool rev[N];
inline int find(int x){return pa[x]==x?x:pa[x]=find(pa[x]);}
inline bool isroot(int x){return x!=c[fa[x]][0]&&x!=c[fa[x]][1];}
inline void update(int p){sz[p]=sz[c[p][0]]+sz[c[p][1]]+1;}
inline void pushdown(int p){
    if(!rev[p]) return;rev[p]=0;swap(c[p][0],c[p][1]);
    rev[c[p][0]]^=1;rev[c[p][1]]^=1;
}
inline void rotate(int x){
    int y=fa[x],z=fa[y],l=x==c[y][1],r=l^1;
    if(!isroot(y)) c[z][y==c[z][1]]=x;
    fa[c[x][r]]=y;fa[y]=x;fa[x]=z;
    c[y][l]=c[x][r];c[x][r]=y;update(y);update(x);
}
inline void splay(int x){
    int top=0;q[++top]=x;
    for(int xx=x;!isroot(xx);xx=fa[xx]) q[++top]=fa[xx];
    while(top) pushdown(q[top--]);
    while(!isroot(x)){
        int y=fa[x],z=fa[y];
        if(!isroot(y)){
            if(x==c[y][1]^y==c[z][1]) rotate(x);
            else rotate(y);
        }rotate(x);
    }
}
inline void access(int x){
    int y=0;while(x){splay(x);c[x][1]=y;update(x);y=x;x=fa[x];}
}
inline void makeroot(int x){
    access(x);splay(x);rev[x]^=1;
}
inline int dis(int x,int y){
    makeroot(x);access(y);splay(y);return sz[y]-1;
}
inline void link(int x,int y){
    makeroot(x);fa[x]=y;int xx=find(x),yy=find(y);
    pa[xx]=yy;int x1=d1[xx],y1=d2[xx],x2=d1[yy],y2=d2[yy];
    int mx=dis(x2,y2);
    int res=dis(x1,y1);if(res>mx) mx=res,d1[yy]=x1,d2[yy]=y1;
    res=dis(x1,y2);if(res>mx) mx=res,d1[yy]=x1,d2[yy]=y2;
    res=dis(x1,x2);if(res>mx) mx=res,d1[yy]=x1,d2[yy]=x2;
    res=dis(y1,x2);if(res>mx) mx=res,d1[yy]=y1,d2[yy]=x2;
    res=dis(y1,y2);if(res>mx) mx=res,d1[yy]=y1,d2[yy]=y2;
}
int main(){
//  freopen("a.in","r",stdin);
    int type=read();n=read();m=read();
    for(int i=1;i<=n;++i) pa[i]=i,d1[i]=i,d2[i]=i;
    while(m--){
        int op=read(),x=read()^lastans;
        if(op==1) link(x,read()^lastans);
        else{
            int xx=find(x);
            int res=max(dis(x,d1[xx]),dis(x,d2[xx]));
            printf("%d\n",res);if(type) lastans=res;
        }
    }return 0;
}
展开阅读全文

没有更多推荐了,返回首页