BZOJ 1787 紧急集合

时间:2023-03-08 18:21:11

LCA。注意细节。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxv 500500
#define maxe 1005000
using namespace std;
int n,m,x,y,z,g[maxv],nume=,anc[maxv][],dis[maxv];
struct edge
{
int v,nxt;
}e[maxe];
void addedge(int u,int v)
{
e[++nume].v=v;
e[nume].nxt=g[u];
g[u]=nume;
}
void dfs(int x)
{
for (int ee=;ee<=;ee++)
anc[x][ee]=anc[anc[x][ee-]][ee-];
for (int i=g[x];i;i=e[i].nxt)
{
int v=e[i].v;
if (v!=anc[x][])
{
anc[v][]=x;dis[v]=dis[x]+;
dfs(v);
}
}
}
int lca(int x,int y)
{
if (dis[x]<dis[y]) swap(x,y);
for (int e=;e>=;e--)
{
if ((dis[anc[x][e]]>=dis[y]) && (anc[x][e]!=))
x=anc[x][e];
}
if (x==y) return x;
for (int ee=;ee>=;ee--)
{
if (anc[x][ee]!=anc[y][ee])
{
x=anc[x][ee];
y=anc[y][ee];
}
}
return anc[x][];
}
int get_dis(int x,int y)
{
int k=lca(x,y);
return dis[x]+dis[y]-*dis[k];
}
int main()
{
scanf("%d%d",&n,&m);
for (int i=;i<=n-;i++)
{
scanf("%d%d",&x,&y);
addedge(x,y);
addedge(y,x);
}
dfs();
for (int i=;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&z);
int t1,t2,t3;
t1=lca(x,y);t2=lca(x,z);t3=lca(y,z);
int ans1,ans2=;
if (t1==t2) ans1=t3;
else if (t1==t3) ans1=t2;
else ans1=t1;
ans2=get_dis(x,ans1)+get_dis(y,ans1)+get_dis(z,ans1);
printf("%d %d\n",ans1,ans2);
}
return ;
}