题目链接:https://www.luogu.org/problemnew/show/P3884
对方不想和你说话并向你扔了一个lca模板。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxlog = 10;
const int maxn = 105;
int n, m, s, widans = -1, depans = -1;
int root;
int fa[maxn][maxlog];
int deep[maxn], wide[maxn];
int head[maxn];
int cnt;
struct Edge{
int next;
int to;
}e[maxn<<2];
void add(int u, int v)
{
e[cnt].to = v;
e[cnt].next = head[u];
head[u] = cnt++;
}
void dfs(int u, int p, int d)
{
fa[u][0] = p;
deep[u] = d;
for(int i = head[u]; i != -1; i = e[i].next)
if(e[i].to != p) dfs(e[i].to, u, d+1);
}
void init()
{
dfs (root, -1, 0);
for(int k = 0; k + 1 < maxlog; k++)
{
for(int v = 1; v <= n; v++)
if(fa[v][k] < 0) fa[v][k+1] = -1;
else fa[v][k+1] = fa[fa[v][k]][k];
}
}
int lca(int u, int v)
{
if(deep[u] > deep[v]) swap(u, v);
for(int k = 0; k < maxlog; k++)
{
if(deep[v] == deep[u]) break;
if((deep[v] - deep[u]) >> k & 1)
{
v = fa[v][k];
}
}
if(u == v) return u;
for(int k = maxlog - 1; k >= 0; k--)
{
if(fa[v][k] != fa[u][k])
{
u = fa[u][k];
v = fa[v][k];
}
}
return fa[u][0];
}
int main()
{
memset(head,-1,sizeof(head));
int a,b;
scanf("%d",&n);
for(int i = 1; i < n; i++)
{
scanf("%d%d",&a,&b);
add(a,b);
add(b,a);
}
root = 1;
init();
for(int i = 1; i <= n; i++)
{
depans = max(depans, deep[i]);
wide[deep[i]]++;
}
int u, v;
scanf("%d%d",&u,&v);
int p = lca(u,v);
for(int i = 0; i <= depans; i++)
{
widans = max(widans, wide[i]);
}
printf("%d\n%d\n%d",depans+1,widans,2*(deep[u]-deep[p])+deep[v]-deep[p]);
return 0;
}
哇我lca是真菜。
【luogu P3884 [JLOI2009]二叉树问题】 题解
原文:https://www.cnblogs.com/MisakaAzusa/p/9219654.html