Pagini recente » Cod sursa (job #2432648) | Cod sursa (job #1026746) | Cod sursa (job #1294088) | Cod sursa (job #2389852) | Cod sursa (job #2150966)
#include <cstdio>
#include <vector>
using namespace std;
#define NMAX 100005
int n, m;
vector<int> ad[NMAX];
int lca(int root, int a, int b){
int q1, q2, h = 0;
if(root == a || root == b)
return root;
int i;
int rez = 0;
for(i=0; i<(int) ad[root].size(); i++){
rez = lca(ad[root][i], a, b);
if(rez)
q1 = rez, h++;
if(h == 2)
return root;
}
if(h)
return q1;
return 0;
}
int main(){
int i, x, y;
FILE *fin, *fout;
fin = fopen("lca.in", "r");
fout = fopen("lca.out", "w");
fscanf(fin, "%d %d", &n, &m);
for(i=1; i<=n-1; i++){
fscanf(fin, "%d", &x);
ad[x].push_back(i + 1);
}
for(i=1; i<=m; i++){
fscanf(fin, "%d %d", &x, &y);
fprintf(fout, "%d\n", lca(1, x, y));
}
fclose(fin);
fclose(fout);
return 0;
}