您的位置:首页 > 其它

【模板】lca 最近公共祖先

2017-11-04 10:29 435 查看
lca:

hljs cpp">#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN=500001;
int n,m,gen,x,y;
struct Edge{
int next,to;
}edge[2*MAXN];
int deep[MAXN],fa[MAXN][20];//deep记录每个点的深度,fa[i][j]:表示节点向上跳2^j 个节点所能到达的节点
//显然fa[i][0]就是直接的父节点了

int num_edge,head[MAXN];
void add_edge(int from,int to)
{
edge[++num_edge].next=head[from];
edge[num_edge].to=to;
head[from]=num_edge;
}

bool vis[MAXN];
void dfs(int x)//保存f[i][0]
{
vis[x]=true;
for (int i=1; i<=16; i++)
{
if ((1<<i)>deep[x]) break;
fa[x][i]=fa[fa[x][i-1]][i-1];
}
for (int i=head[x]; i!=0; i=edge[i].next)
{
if (!vis[edge[i].to])
{
deep[edge[i].to]=deep[x]+1;
fa[edge[i].to][0]=x;
dfs(edge[i].to);
}
}
}

int lca(int x,int y)
{
if (deep[x]<deep[y]) swap(x,y);
int d=deep[x]-deep[y];
for (int i=0; i<=16; i++)
{
if ((1<<i)&d) x=fa[x][i];//判断d的第i位是否为1,是的话就往上跳
}
if (x==y) return x;
for (int i=16; i>=0; i--)//因为要找最深的公共祖先,所以要倒着循环
{
if (fa[x][i]!=fa[y][i])
{
x=fa[x][i];//一起往上跳到最近公共祖先的下面
y=fa[y][i];
}
}
return fa[x][0];
}

int main()
{
scanf("%d%d%d",&n,&m,&gen);
for (int i=1; i<=n-1; i++)
{
scanf("%d%d",&x,&y);
add_edge(x,y); add_edge(y,x);
}
dfs(gen);
for (int i=1; i<=m; i++)
{
scanf("%d%d",&x,&y);
printf("%d\n",lca(x,y));
}
return 0;
}
/*
5 5 4
3 1
2 4
5 1
1 4
2 4
3 2
3 5
1 2
4 5

4
4
1
4
4
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: