虛擬賽的時候
#include<string
#include<stdio
#define N
int father[N]
struct edge
{
int st
}E[N*
void addedge(int x
{
E[num]
E[num]
E[num]
E[num]
head[x]=num++;
}
int find(int a)
{
if(f[a]!=a)
f[a]=find(f[a])
return f[a];
}
void dfs
{
int i
vis[u]=
for(i=head[u];i!=
{
v=E[i]
if(vis[v]==
father[v]=u;
dfs[v]=dfs[u]+
dis[v]=E[i]
dfs
}
if(ans<dfs[u])
ans=dfs[u];
}
int LCA(int x
{
int sum=
while(dfs[x]>dfs[y])
{
sum+=dis[x];
x=father[x];
}
while(dfs[y]>dfs[x])
{
sum+=dis[y];
y=father[y];
}
while(x!=y)
{
sum+=(dis[x]+dis[y])
x=father[x];
y=father[y];
}
return sum;
}
int main()
{
int i
while(scanf(
{
memset(head
num=
for(i=
f[i]=i;
for(i=
{
scanf(
addedge(x
addedge(y
x=find(x)
y=find(y)
if(x!=y)
f[x]=find(y)
}
memset(vis
ans=
for(i=
{
if(vis[i]==
{
dis[i]=
dfs[i]=ans;
father[i]=i;
dfs
ans++;
}
}
while(k
{
scanf(
if(find(x)!=find(y))
{printf(
j=LCA(x
printf(
}
}
return
}
From:http://tw.wingwit.com/Article/program/c/201311/11104.html