[AHOI2008]聚会
首先有一个结论:树上三个点两两求lca,最多只会出现两个不同的点。
这个结论不难证明:对于两个点\(A,B\)和他们的lca,\(X\)。第三个点\(C\)只可能在\(X\)的子树内外,而这两种情况都只会使公共的lca数目最多增加1。
有了这个结论后,我们的集合地点就要选在另一个非公共的lca,\(Y\)上。因为从\(X\)到\(Y\)只需要一个点爬,而从\(Y\)到\(X\)需要两个点爬,集合时间是原来的一倍,所以我们要离\(Y\)尽量近,于是在\(Y\)上就是最优解。
代码:
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<queue>
#include<assert.h>
#include<ctime>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
#define forE(i, x, y) for(int i = head[x], y; ~i && (y = e[i].to); i = e[i].nxt)
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 5e5 + 5;
const int N = 19;
In ll read()
{
ll ans = 0;
char ch = getchar(), las = ' ';
while(!isdigit(ch)) las = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(las == '-') ans = -ans;
return ans;
}
In void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
In void MYFILE()
{
#ifndef mrclr
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
#endif
}
int n, m;
struct Edge
{
int nxt, to;
}e[maxn << 1];
int head[maxn], ecnt = -1;
In void addEdge(int x, int y)
{
e[++ecnt] = (Edge){head[x], y};
head[x] = ecnt;
}
int fa[N + 2][maxn], dep[maxn];
In void dfs(int now, int _f)
{
for(int i = 1; (1 << i) <= dep[now]; ++i)
fa[i][now] = fa[i - 1][fa[i - 1][now]];
forE(i, now, v)
{
if(v == _f) continue;
dep[v] = dep[now] + 1, fa[0][v] = now;
dfs(v, now);
}
}
int ha[maxn];
In int lca(int x, int y)
{
if(dep[x] < dep[y]) swap(x, y);
for(int i = ha[dep[x]]; i >= 0; --i)
if(dep[fa[i][x]] >= dep[y]) x = fa[i][x];
if(x == y) return x;
for(int i = ha[dep[x]]; i >= 0; --i)
if(fa[i][x] != fa[i][y]) x = fa[i][x], y = fa[i][y];
return fa[0][x];
}
int main()
{
// MYFILE();
Mem(head, -1), ecnt = -1;
n = read(), m = read();
for(int i = 1; i < n; ++i)
{
int x = read(), y = read();
addEdge(x, y), addEdge(y, x);
}
for(int i = 1, x = 0; i <= n; ++i)
{
if((1 << (x + 1)) <= i) ++x;
ha[i] = x;
}
dep[1] = 1, dfs(1, 0);
for(int i = 1; i <= m; ++i)
{
int x = read(), y = read(), z = read();
int t1 = lca(x, y), t2 = lca(y, z), t3 = lca(x, z), tt, tp;
if(t1 == t2) tt = t3, tp = t1; //求tt可以直接写成:tt=t1^t2^t3
else if(t2 == t3) tt = t1, tp = t2;
else if(t1 == t3) tt = t2, tp = t1;
write(tt), space, write(dep[x] + dep[y] + dep[z] - dep[tt] - 2 * dep[tp]), enter;
}
return 0;
}