9

6  •  1个月前


include

include

using namespace std; vectormap[500001]; int anc[500001][25]; int dep[500001];

void dfs(int node, int father) {

anc[node][0] = father;
dep[node] = dep[father] + 1;
for (int i = 1; anc[node][i - 1] > 0; i++)
	anc[node][i] = anc[anc[node][i - 1]][i - 1];
for (int next : map[node])
	if (father != next) {
		dfs(next, node);
	}

}

int getlca(int x, int y) {

if (dep[x] < dep[y])
	swap(x, y);
for (int i = 24; dep[x] > dep[y]; i--)
	if (dep[anc[x][i]] >= dep[y])
		x = anc[x][i];
if (x == y)
	return x;
for (int i = 24; i >= 0; i--)
	if (anc[x][i] != anc[y][i]) {
		x = anc[x][i];
		y = anc[y][i];
	}
return anc[x][0];

}

int main() {

int n, m, s;
scanf("%d%d%d", &n, &m, &s);
for (int i = 0; i < n - 1; i++) {
	int x, y;
	scanf("%d%d", &x, &y);
	map[x].push_back(y);
	map[y].push_back(x);
}
dfs(s, 0);
for (int i = 0; i < m; i++) {
	int a, b;
	scanf("%d%d", &a, &b);
	printf("%d\n", getlca(a, b));
}
return 0;

}


评论:

请先登录,才能进行评论