6 • 1个月前
using namespace std; vectormap[500001];
struct query {
int index;
int other;
}; int ans[500001]; int group[500001]; vectorq[500001];
int find(int x) {
if (x != group[x]) {
group[x] = find(group[x]);
}
return group[x];
}
bool vis[5000011];
void dfs(int node, int father) {
vis[node] = true;
for (int i = 0; i < q[node].size(); i++)
if (vis[q[node][i].other]) {
ans[q[node][i].index ] = find(q[node][i].other );
}
for (int i = 0; i < map[node].size(); i++)
if (map[node][i] != father) {
dfs(map[node][i], node);
}
group[node] = father;
}
int main() {
int n, m, s;
scanf("%d%d%d", & n, &m, &s);
for (int i = 1; i <= n; i++)
group[i] = i;
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);
}
for (int i = 0; i < m; i++) {
int a, b;
scanf("%d%d", & a, &b);
q[a].push_back({i, b});
q[b].push_back({i, a});
}
dfs(s, 0);
for (int i = 0; i < m; i++)
printf("%d\n", ans[i]);
return 0;
}
评论:
请先登录,才能进行评论