(Large extbf{Description: } large{一棵n个节点的树,m次操作,每次给出三个节点x,y,z,求三个节点到树上某个节点距离之和的\最小值,并输出此节点。(1 leq x,y,z leq n leq 5 imes 10^{5}, 1 leq m leq 5 imes 10^{5})}\)
(Large extbf{Solution: } large{我们很容易的想到 ext{LCA},显然三个节点两两之间的 ext{LCA}一定有一个是同一个节点,那么我们\要求的节点就是此点,因为可证无论是这个节点祖先,儿子还是兄弟都不可能更优。\对于距离,我们可以在 ext{dfs}的时候顺便处理,然后用前缀和的思想O(1)查询就好了。})
(Large extbf{Code: })
#include <cstdio>
#include <algorithm>
#define LL long long
#define gc() getchar()
#define rep(i, a, b) for(int i = (a); i <= (b); ++i)
#define _rep(i, a, b) for(int i = (a); i >= (b); --i)
using namespace std;
const int N = 5e5 + 5;
int n, m, cnt, head[N], size[N], son[N], top[N], fa[N], dep[N];
struct Edge {
int to, next;
}e[N << 1];
inline int read() {
char ch = gc();
int ans = 0, flag = 1;
while (ch > '9' || ch < '0') ch = gc();
while (ch >= '0' && ch <= '9') ans = (ans << 1) + (ans << 3) + ch - '0', ch = gc();
return ans * flag;
}
inline void add(int x, int y) {
e[++cnt].to = y;
e[cnt].next = head[x];
head[x] = cnt;
}
inline void dfs1(int x, int y) {
fa[x] = y;
dep[x] = dep[y] + 1;
size[x] = 1;
int Max = 0;
for (int i = head[x]; i ; i = e[i].next) {
int u = e[i].to;
if (u == y) continue;
dfs1(u, x);
size[x] += size[u];
if (size[u] > Max) son[x] = u, Max = size[u];
}
}
inline void dfs2(int x, int tp) {
top[x] = tp;
if (!son[x]) return;
dfs2(son[x], tp);
for (int i = head[x]; i ; i = e[i].next) {
int u = e[i].to;
if (u == son[x] || u == fa[x]) continue;
dfs2(u, u);
}
}
inline int lca(int x, int y) {
while (top[x] != top[y]) {
if (dep[top[x]] < dep[top[y]]) swap(x, y);
x = fa[top[x]];
}
return dep[x] < dep[y] ? x : y;
}
int main() {
n = read(), m = read();
int x, y, z;
rep(i, 2, n) x = read(), y = read(), add(x, y), add(y, x);
dfs1(1, 0);
dfs2(1, 1);
while (m--) {
x = read(), y = read(), z = read();
int f = lca(x, y), ff = lca(x, z), fff = lca(y, z);
if (dep[f] == dep[ff]) printf("%d ", fff);
else if (dep[ff] == dep[fff]) printf("%d ", f);
else printf("%d ", ff);
printf("%d
", dep[x] + dep[y] + dep[z] - min(dep[f], min(dep[ff], dep[fff])) * 2 - max(dep[f], max(dep[ff], dep[fff])));
}
return 0;
}