# BZOJ1832 聚会

Description：
Y岛风景美丽宜人，气候温和，物产丰富。Y岛上有N个城市，有N-1条城市间的道路连接着它们。每一条道路都连接某两个城市。幸运的

Input：

Output：

#include<bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;

struct edges{
int to, next;
}edge[N<<1];

int n, m, fa[N][22], dep[N];
void dfs(int x, int pre){
fa[x][0] = pre;
for(int i = head[x]; i; i = edge[i].next){
int v = edge[i].to;
if(v == pre) continue;
dep[v] = dep[x] + 1;
dfs(v, x);
}
}
int LCA(int u,int v){
if(dep[v] > dep[u]) swap(u, v);
int k=dep[u]-dep[v];
for(int i=0;i<=20;i++)
if((1<<i)&k) u=fa[u][i];
if(u == v) return u;
for(int i = 20; i >= 0; i--)
if(fa[u][i] != fa[v][i])
u = fa[u][i], v = fa[v][i];
return fa[u][0];

}
int main(){
scanf("%d%d",&n, &m);
int x, y, z;
for(int i = 1; i < n; i++){
scanf("%d%d",&x, &y);
}
dep[1] = 1; dfs(1, 1);
for(int j = 0; j <= 20; j++)
for(int i = 1; i <= n; i++)
fa[i][j + 1] = fa[fa[i][j]][j];
for(int i = 1; i <= m; i++){
scanf("%d%d%d",&x, &y, &z);
int lca, pos, tmp, tot = 0, ans = 1e9;

lca = LCA(x, y); tot += dep[x] + dep[y] - 2*dep[lca];
tmp = LCA(lca, z); tot += dep[z] + dep[lca] - 2*dep[tmp];
if(tot < ans) ans = tot, pos = lca;

swap(x, z); tot = 0;
lca = LCA(x, y); tot += dep[x] + dep[y] - 2*dep[lca];
tmp = LCA(lca, z); tot += dep[z] + dep[lca] - 2*dep[tmp];
if(tot < ans) ans = tot, pos = lca;

swap(y, z); tot = 0;
lca = LCA(x, y); tot += dep[x] + dep[y] - 2*dep[lca];
tmp = LCA(lca, z); tot += dep[z] + dep[lca] - 2*dep[tmp];
if(tot < ans) ans = tot, pos = lca;

printf("%d %d\n", pos, ans);
}
return 0;
}
View Code

posted @ 2018-04-05 23:35  Ror_shach  阅读(214)  评论(0编辑  收藏