求调,不知道和答案那不一样
查看原帖
求调,不知道和答案那不一样
854450
fufengyiye楼主2024/3/13 23:43
#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std;

struct edge {
	int v, next;
}e[500004 << 1];
int head[500004], depth[500004], tot;
int f[500004][22];
int lg[500004];
int n, m, s;

void add(int u, int v)
{
	e[++tot].v = v;
	e[tot].next = head[u];
	head[u] = tot;
}
void dfs(int st, int fath)
{
	depth[st] = depth[fath] + 1;
	f[st][0] = fath;
	for (int i = 1; (1 << i) <= depth[st]; i++)
	{
		f[st][i] = f[f[st][i - 1]][i - 1];
	}
	for (int i = head[st]; i; i = e[i].next)
	{
		if (e[i].v != fath)
		{
			dfs(e[i].v, st);
		}
	}
}

int lca(int x, int y)
{
	if (depth[x] < depth[y])
		swap(x, y);
	while (depth[x] > depth[y])
	{
		x = f[x][lg[depth[x] - depth[y]] - 1];
	}
	if (x == y)
		return x;
	for (int i = lg[depth[x]]-1; i >= 0; i--)
	{
		if (f[x][i] != f[y][i])
			x = f[x][i], y = f[y][i];
	}
	return f[x][0];
}

int main()
{
	cin >> n >> m >> s;
	for (int i = 0; i < n - 1; i++)
	{
		int u, v;
		cin >> u >> v;
		add(u, v);
		add(v, u);
	}
	for (int i = 1; i <= n; i++)
	{
		lg[i] = lg[i - 1];
		if (i == 1 << i)
			lg[i]++;
	}
	dfs(s, 0);
	while (m--)
	{
		int x, y;	
		cin >> x >> y;
		cout << lca(x, y) << endl;
	}
	return 0;
}
2024/3/13 23:43
加载中...