CF455C Civilization (diameter of tree + union search)

First find the diameter of each connected subtree, note that it is recorded on the root, and it can be merged in a direction.
Then it's a merge check. Merge two connected subtrees so that the new diameter is the smallest. Considering that if the new diameter spans two blocks, the optimal one is obviously to connect the midpoints of the diameters of the two blocks.
So the minimum diameter after the merger is max(max(d1,d2),(d1+1)/2+(d2+1)/2+1)

#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,q,h[N],num=0,fa[N],mx[N],d[N],ans;bool vis[N];
struct edge{
    int to,next;
}data[N<<1];
inline int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
inline void merge(int x,int y){
    int xx=find(x),yy=find(y);if(xx>yy) swap(xx,yy);fa[yy]=xx;
}
inline void dp(int x,int Fa){
    vis[x]=1;
    for(int i=h[x];i;i=data[i].next){
        int y=data[i].to;if(y==Fa) continue;dp(y,x);
        ans=max(ans,mx[x]+mx[y]+1);mx[x]=max(mx[x],mx[y]+1);
    }
}
int main(){
//  freopen("a.in","r",stdin);
    n=read();m=read();q=read();
    for(int i=1;i<=n;++i) fa[i]=i;
    while(m--){
        int x=read(),y=read();merge(x,y);
        data[++num].to=y;data[num].next=h[x];h[x]=num;
        data[++num].to=x;data[num].next=h[y];h[y]=num;
    }for(int i=1;i<=n;++i){
        if(vis[i]) continue;ans=0;dp(i,0);d[i]=ans;
    }while(q--){
        int op=read(),x=read();
        if(op==1) printf("%d\n",d[find(x)]);
        else{
            int y=read();
            int xx=find(x),yy=find(y);if(xx==yy) continue;
            fa[yy]=xx;d[xx]=max(max(d[xx],d[yy]),(d[xx]+1)/2+(d[yy]+1)/2+1);
        }
    }return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324384248&siteId=291194637