6 4
1 2
2 3
2 4
4 5
5 6
4 5 6
6 3 1
2 4 4
6 6 6
标签:
水题,随便倍增一下求LCA就可以
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; inline int read() { int x=0,f=1; char ch=getchar(); while (ch<‘0‘ || ch>‘9‘) {if (ch==‘-‘) f=-1; ch=getchar();} while (ch>=‘0‘ && ch<=‘9‘) {x=x*10+ch-‘0‘; ch=getchar();} return x*f; } #define maxn 500010 int n,m,deep[maxn],father[maxn][21]; struct EdgeNode{int next,to;}edge[maxn<<1]; int head[maxn],cnt; void add(int u,int v) {cnt++; edge[cnt].next=head[u]; head[u]=cnt; edge[cnt].to=v;} void insert(int u,int v) {add(u,v); add(v,u);} void DFS(int now,int last) { for (int i=1; i<=20; i++) if (deep[now]>=(1<<i)) father[now][i]=father[father[now][i-1]][i-1]; else break; for (int i=head[now]; i; i=edge[i].next) if (edge[i].to!=last) { father[edge[i].to][0]=now; deep[edge[i].to]=deep[now]+1; DFS(edge[i].to,now); } } int LCA(int x,int y) { if (deep[x]<deep[y]) swap(x,y); int dd=deep[x]-deep[y]; for (int i=0; i<=20; i++) if ((1<<i)&dd) x=father[x][i]; for (int i=20; i>=0; i--) if (father[x][i]!=father[y][i]) x=father[x][i],y=father[y][i]; if (x==y) return x; return father[x][0]; } int Dist(int u,int v) { int lca=LCA(u,v); return deep[u]+deep[v]-(deep[lca]<<1); } int ans,rt; int main() { n=read(); m=read(); for (int u,v,i=1; i<=n-1; i++) u=read(),v=read(),insert(u,v); DFS(1,0); for (int x,y,z,i=1; i<=m; i++) { x=read(),y=read(),z=read(); int fxy=LCA(x,y),fyz=LCA(y,z),fxz=LCA(x,z); rt=(fxy==fyz)? fxz : fxy==fxz? fyz : fxy; ans=Dist(x,rt)+Dist(y,rt)+Dist(z,rt); printf("%d %d\n",rt,ans); } return 0; }
在学校被***毒的不能自拔,感觉已经不想在班里待下去了
标签:
原文地址:http://www.cnblogs.com/DaD3zZ-Beyonder/p/5634322.html