Description
Input
Output
Sample Input
6 4
1 2
2 3
2 4
4 5
5 6
4 5 6
6 3 1
2 4 4
6 6 6
1 2
2 3
2 4
4 5
5 6
4 5 6
6 3 1
2 4 4
6 6 6
Sample Output
5 2
2 5
4 1
6 0
HINT
Source
只有3个点可能取到最优解,分别是3个点中任选两个点的lca,枚举并计算即可(想一想,为什么)。
#include<cstdio> #include<cctype> #include<queue> #include<cmath> #include<cstring> #include<algorithm> #define rep(i,s,t) for(int i=s;i<=t;i++) #define dwn(i,s,t) for(int i=s;i>=t;i--) #define ren for(int i=first[x];i;i=next[i]) using namespace std; inline int read() { int x=0,f=1;char c=getchar(); for(;!isdigit(c);c=getchar()) if(c=='-') f=-1; for(;isdigit(c);c=getchar()) x=x*10+c-'0'; return x*f; } const int maxn=500010; int n,m,first[maxn],next[maxn<<1],to[maxn<<1],fa[maxn][20],dep[maxn],e; void AddEdge(int u,int v) { to[++e]=v;next[e]=first[u];first[u]=e; to[++e]=u;next[e]=first[v];first[v]=e; } void dfs(int x) { dep[x]=dep[fa[x][0]]+1; rep(i,1,19) fa[x][i]=fa[fa[x][i-1]][i-1]; ren if(to[i]!=fa[x][0]) fa[to[i]][0]=x,dfs(to[i]); } int lca(int x,int y) { if(dep[x]<dep[y]) swap(x,y); dwn(i,19,0) if(dep[x]-dep[y]>=(1<<i)) x=fa[x][i]; dwn(i,19,0) if(fa[x][i]!=fa[y][i]) x=fa[x][i],y=fa[y][i]; return x==y?x:fa[x][0]; } int dist(int x,int y) { return dep[x]+dep[y]-2*dep[lca(x,y)]; } int ans,p,u,v,w; void relax(int x) { int res=dist(x,u)+dist(x,v)+dist(x,w); if(res<ans) p=x,ans=res; } int main() { n=read();m=read(); rep(i,2,n) AddEdge(read(),read()); dfs(1); while(m--) { u=read(),v=read(),w=read(); ans=1<<30;relax(lca(u,v));relax(lca(u,w));relax(lca(v,w)); printf("%d %d ",p,ans); } return 0; }