算法:倍增LCA
难度:NOIP
题解略
代码如下
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <cmath>
#include <queue>
#define N 500005
using namespace std;
struct node
{
int next;
int to;
}edge[N<<1];
int head[N],cnt=1;
void init()
{
memset(head,-1,sizeof(head));
cnt=1;
}
void add(int u,int v)
{
edge[cnt].next=head[u];
edge[cnt].to=v;
head[u]=cnt++;
}
int dep[N],f[N][30];
void dfs(int rt,int fx,int deep)
{
dep[rt]=deep;
f[rt][0]=fx;
for(int i = head[rt];i!=-1;i=edge[i].next)
{
int to=edge[i].to;
if(to==fx) continue;
dfs(to,rt,deep+1);
}
}
int LCA(int x,int y)
{
if(dep[x]>dep[y])
{
swap(x,y);
}
for(int i = 25;i>=0;i--)
{
if(dep[f[y][i]]>=dep[x])
{
y=f[y][i];
}
}
if(x==y) return x;
int ret;
for(int i = 25;i>=0;i--)
{
if(f[y][i]!=f[x][i])
{
y=f[y][i];
x=f[x][i];
}else
{
ret=f[x][i];
}
}
return ret;
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
init();
for(int i = 1;i < n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
add(x,y);
add(y,x);
}
dfs(1,1,1);
for(int i=1;i<=25;i++)
{
for(int j=1;j<=n;j++)
{
f[j][i]=f[f[j][i-1]][i-1];
}
}
while(m--)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
int L1=LCA(x,y);
int L2=LCA(x,z);
int L3=LCA(y,z);
if(L1==L2&&L2==L3)
{
printf("%d ",L1);
int ans=(dep[x]+dep[y]+dep[z])-3*dep[L1];
printf("%d\n",ans);
continue;
}else if(L1==L2)
{
printf("%d ",L3);
int ans=dep[x]-dep[L1];
ans+=dep[y]+dep[z]-2*dep[L3];
int L4=LCA(L3,L1);
ans+=dep[L3]+dep[L1]-2*dep[L4];
printf("%d\n",ans);
continue;
}else if(L1==L3)
{
printf("%d ",L2);
int ans=dep[y]-dep[L1];
ans+=dep[x]+dep[z]-2*dep[L2];
int L4=LCA(L2,L1);
ans+=dep[L2]+dep[L1]-2*dep[L4];
printf("%d\n",ans);
continue;
}else if(L2==L3)
{
printf("%d ",L1);
int ans=dep[z]-dep[L2];
ans+=dep[x]+dep[y]-2*dep[L1];
int L4=LCA(L3,L1);
ans+=dep[L3]+dep[L1]-2*dep[L4];
printf("%d\n",ans);
}
}
return 0 ;
}
本文深入探讨了倍增LCA算法,一种高效求解树上两点最近公共祖先(LCA)问题的方法。通过预处理建立倍增父节点表,算法能在对数时间内找到任意两点的最近公共祖先。代码示例展示了算法的具体实现过程,包括树的初始化、DFS遍历以及LCA查询。
&spm=1001.2101.3001.5002&articleId=82810984&d=1&t=3&u=675c51313c394e9484e21ad0470fb1bc)
263

被折叠的 条评论
为什么被折叠?



