Pagini recente » Cod sursa (job #2942997) | Cod sursa (job #3134994) | Cod sursa (job #675492) | Cod sursa (job #2620790) | Cod sursa (job #3263425)
#include <bits/stdc++.h>
using namespace std;
const int NODES = 1e5 + 5, QUERIES = 2e6 + 5;
vector<int> graph[NODES], parent(NODES), answer(QUERIES);
vector<pair<int, int>> query[NODES];
bitset<NODES> used;
int find(int node) {
if (parent[node] == node) {
return node;
}
return parent[node] = find(parent[node]);
}
void dfs(int node) {
parent[node] = node;
used[node] = true;
for (int next : graph[node]) {
if (!used[next]) {
dfs(next);
parent[next] = node;
}
}
for (auto [next, pos] : query[node]) {
if (used[next]) {
answer[pos] = find(next);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
freopen("lca.in", "r", stdin);
freopen("lca.out", "w", stdout);
int n, m;
cin >> n >> m;
for (int i = 2; i <= n; ++i) {
int p;
cin >> p;
graph[p].push_back(i);
graph[i].push_back(p);
}
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
query[a].push_back({b, i});
query[b].push_back({a, i});
}
dfs(1);
for (int i = 0; i < m; ++i) {
cout << answer[i] << "\n";
}
return 0;
}