原题链接
简化题意:在一棵树上删去一条边,加入一条边,使得树的直径尽可能小。
要使删去一条边后树的直径尽可能小,显然一定要删去直径上的边,这样才能使直径比当前直径小。
删去一条边后,树被分成两个联通块,显然,最后的直径至少为两个连通块中直径较大者的直径。
考虑新边的两端应该选在哪个位置。
设 为点 距离自己连通块中,离自己最远的点的距离。
在两个连通块中,分别找到点 、,满足该点是自己所在的连通块中,、 最小的点。
设整棵树的直径为 ,,考虑两棵树分别从 、 开始加边,此时显然有 、 分别为两个连通块直径上的一个点(反证法:若 不是自己所在连通块直径的一端,那么一定可以找到一个点 ,使得 ,那么 应当成为 )。
另一个点的位置可以这样得出:
对于每个整棵树的直径上的点 ,预处理出 ,表示存在一个不在整棵树的直径上的点 ,使得 最大,且 、 之间的路径不经过直径上的边。
两个连通块每次加入一个直径上的点,即可用 更新直径。直径的中点可以通过深度计算得出。
时间复杂度 。
Code
#include<cstdio>
#include<cstring>
#include<algorithm>
#define mset(arr,val) memset(arr,val,sizeof(arr))
using namespace std;
const int SIZE=6e5+10,inf=0x3f3f3f3f;
inline int read()
{
int x=0,opr=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')opr=-opr;ch=getchar();}
while(ch>='0'&&ch<='9')x=(x*10)+(ch^48),ch=getchar();
return x*opr;
}
int n,head[SIZE],sizee,mid,thisa;
struct edge{int u,v,nxt;}e[SIZE];
inline void add(int u,int v){e[sizee]={u,v,head[u]},head[u]=sizee++;}
inline void add_edge(int u,int v){add(u,v),add(v,u);}
int dpth[SIZE],fst[SIZE],scd[SIZE],hvy[SIZE],fa[SIZE],tmp,root,tail,maxn,ths,ct,pnt[SIZE],len;
int ans[SIZE],part[SIZE],maxlen[SIZE],ansplace,ansct,ANS=inf,til,ctmid;
inline void update(int thisp,int v,int t)
{
if(v>fst[thisp])scd[thisp]=fst[thisp],fst[thisp]=v,hvy[thisp]=t;
else if(v>scd[thisp])scd[thisp]=v;
}
void dfs(int thisp,int lst)
{
dpth[thisp]=dpth[fa[thisp]=lst]+1;
for(int i=head[thisp];~i;i=e[i].nxt)if(e[i].v!=lst)dfs(e[i].v,thisp),update(thisp,fst[e[i].v],e[i].v);
if(fst[thisp]+scd[thisp]-2*dpth[thisp]+1>maxn)maxn=fst[thisp]+scd[thisp]-2*dpth[thisp]+1,tmp=thisp;
update(thisp,dpth[thisp],thisp);
}
int main()
{
mset(head,-1);
n=read();
for(int i=1;i<n;i++)add_edge(read(),read());
dfs(1,0),root=tmp;
while(hvy[root]!=root)root=hvy[root];
mset(hvy,0),mset(fst,0),mset(scd,0),dfs(tail=root,0);
while(hvy[tail]!=tail)pnt[dpth[tail]]=tail,tail=hvy[tail];
pnt[dpth[tail]]=tail,len=dpth[tail];
ths=ct=tail;
for(int i=1;i<=n;i++)if(!scd[i])scd[i]=dpth[i];
while(ths!=root)
{
mid=(scd[ths]+len-2*dpth[ths])/2+(scd[ths]+len-2*dpth[ths])%2;
if(len-mid<dpth[ct])ct=pnt[len-mid],ctmid=mid;
ans[ths]=ct,maxlen[ths]=ctmid,part[ths]=til=max(til,scd[ths]+len-2*dpth[ths]);
ths=fa[ths];
}
ths=ct=root,til=ctmid=0;
while(ths!=tail)
{
mid=(scd[ths]-1)/2+(scd[ths]-1)%2;
if(1+mid>dpth[ct])ct=pnt[1+mid],ctmid=mid;
thisa=max({ctmid+1+maxlen[hvy[ths]],part[hvy[ths]],til=max(til,scd[ths]-1)});
if(thisa<ANS)ANS=thisa,ansplace=ths,ansct=ct;
ths=hvy[ths];
}
printf("%d\n%d %d\n%d %d",ANS,ansplace,hvy[ansplace],ansct,ans[hvy[ansplace]]);
return 0;
}