Pagini recente » Cod sursa (job #2514273) | Cod sursa (job #562082) | Cod sursa (job #2668152) | Cod sursa (job #554310) | Cod sursa (job #2307701)
#include <bits/stdc++.h>
#define MAXN 100000
#define MAXQ 2000000
int n;
std::vector <int> G[1 + MAXN];
struct Query{int index, node;};
std::vector <Query> Q[1 + MAXN];
int father[1 + MAXN];
inline void Union(int x, int y){
father[y] = x;
}
inline int Find(int x){
if(father[x] == 0)
return x;
return father[x] = Find(father[x]);
}
bool color[1 + MAXN];
int ans[1 + MAXQ];
void dfs(int node, int papa){
for(auto y: G[node]) if(y != papa){
dfs(y, node);
Union(node, y);
}
color[node] = 1;
for(auto y: Q[node]) if(color[y.node])
ans[y.index] = Find(y.node);
}
int main(){
FILE*fi,*fo;
fi = fopen("lca.in","r");
fo = fopen("lca.out","w");
int m;
fscanf(fi,"%d%d", &n, &m);
for(int i = 2; i <= n; i++){
int x;
fscanf(fi,"%d", &x);
G[i].push_back(x);
G[x].push_back(i);
}
for(int i = 1; i <= m; i++){
int x, y;
fscanf(fi,"%d%d", &x, &y);
Q[x].push_back({i, y});
Q[y].push_back({i, x});
}
dfs(1, 0);
for(int i = 1; i <= m; i++)
fprintf(fo,"%d\n", ans[i]);
return 0;
}