lca lowest common ancestor 最小公共祖先 How far away?(安达里士no.3)
作者:互联网
scanf("%d%d",&n,&m);
for(int i=1; i<n; i++) {
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
a[x].push_back(edge{y,z});
a[y].push_back(edge{x,z}); }
//void SPFA()
memset(dis,0x3f,sizeof(dis));
dis[1]=0;
vis[1]=1;
q.push(1);//queue <int> q;
while(!q.empty()){
int x=q.front();
q.pop();
vis[x]=0;
for(int i=0;i<a[x].size();i++){
int y=a[x][i].y,z=a[x][i].z;
if(dis[y]>dis[x]+z;
dep[y]=dep[x]+1;
f[y][0]=x;
if(!vis[y]) vis[y]=1,q.push(y);
}
}
int t=log2(n);
for(int i=1;i<=t;i++)
for(int j=1;j<=n;j++)
f[j][i]=f[f[j][i-1]][i-1];
for(int i=1;i<=m;i++){
scanf("%d%d",&x,&y);
int distance=dis[x]+dis[y];
if(dep[x]<dep[y]) swap(x,y);
while(dep[x]>dep[y]){
int z=log2(dep[x]-dep[y]);
x=f[x][z];
}
if(x==y){
distance-=2*dis[y];
printf("%d\n",distance);
}
for(int j=int(log2(dep[x]));j>=0;j--){
if(f[x][j]!=f[y][j]{
x=f[x][j];
y=f[y][j];
}
distance-=2*dis[f[x][0]];
printf("%d",distance);
}
}
标签:lowest,distance,vis,int,away,d%,dep,lca,dis 来源: https://www.cnblogs.com/AntaresMilo/p/12364463.html