双倍经验的水题
虽说讲道理不应该刷,但是练练lca模板还是不错的
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
int head[1000003],to[1000003],nex[1000003],tot;
int depth[500003],in[500003],out[500003];
int chuo=0,n,m;
int f[500003][20];
void add(int u,int v){
to[++tot]=v;
nex[tot]=head[u];
head[u]=tot;
}
int dfs(int fa,int now,int dep){
depth[now]=dep;
in[now]=++chuo;
f[now][0]=now;
for(int i=head[now];i;i=nex[i]){
if(to[i]!=fa){
dfs(now,to[i],dep+1);
}
}
out[now]=++chuo;
}
bool pd(int x,int y){
if(in[x]<=in[y]&&out[x]>=out[y]){
return true;
}
return false;
}
int lca(int x,int y){
if(pd(x,y)){
return x;
}
if(pd(y,x)){
return y;
}
int k=x;
for(int i=30;i>=0;i--){
if(!pd(f[k][i],y)){
k=f[k][i];
}
}
return f[k][0];
}
int ju(int a,int b){
int x=lca(a,b);
return(2*depth[x]-depth[a]-depth[b]);
}
int main(){
cin>>n>>m;
for(int i=1;i<=n-1;i++){
int u,v;
cin>>u>>v;
add(u,v);
add(v,u);
}
dfs(0,1,1);
for(int i=1;i<=n;i++){
for(int j=1;j<=30;j++){
f[i][j]=f[f[i][j-1]][j-1];
}
}
for(int i=1;i<=m;i++){
int a,b,c;
cin>>a>>b>>c;
int lca1=lca(a,b);
int lca2=lca(a,c);
int lca3=lca(b,c);
if(lca1==lca2){
cout<<lca3<<" "<<-ju(lca3,a)-depth[lca3]*2+depth[b]+depth[c]<<endl;
continue;
}
if(lca2==lca3){
cout<<lca1<<" "<<-ju(lca1,a)-depth[lca1]*2+depth[a]+depth[b]<<endl;
continue;
}
if(lca1==lca3){
cout<<lca2<<" "<<-ju(lca2,a)-depth[lca2]*2+depth[a]+depth[c]<<endl;
continue;
}
}
//cout<<endl<<lca(1,3)<<lca(3,6)<<lca(1,6);
return 0;
}
/*
in:
6 4
1 2
2 3
2 4
4 5
5 6
4 5 6
6 3 1
2 4 4
6 6 6
out:
5 2
2 5
4 1
6 0
*/