LCA

LCA

倍增

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 4e4 + 10, M = 18;
int n, m;
int fa[N][M], depth[N];
vector<int> G[N];
queue<int> q;
void add(int a, int b)
{
	G[a].push_back(b);
}

void bfs(int root)
{
	q.push(root);
	memset(depth, 0x3f, sizeof depth);
	depth[0] = 0;
	depth[root] = 1;
	while(!q.empty())
	{
		int t = q.front();
		q.pop();
		for (auto to : G[t])
		{
			if (depth[to] != depth[t] - 1)
			{
				depth[to] = depth[t] + 1;
				fa[to][0] = t;
				q.push(to);
				for (int k = 1; k < M; k++)
					fa[to][k] = fa[fa[to][k-1]][k-1];
			}
		}
	}
}

int lca(int a, int b)
{
	if (depth[a] < depth[b])
		swap(a, b);
	for (int k = M-1; k >= 0; k--)
		if (depth[fa[a][k]] >= depth[b])
			a = fa[a][k];
	if (a == b)
		return a;
	for (int k = M-1; k >= 0; k--)
		if (fa[a][k] != fa[b][k])
		{
			a = fa[a][k];
			b = fa[b][k];
		}
	return fa[a][0];
}
posted @   hzy0227  阅读(180)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!
点击右上角即可分享
微信分享提示