Pagini recente » Cod sursa (job #1233950) | Cod sursa (job #2632038)
#include <bits/stdc++.h>
#define endl "\n"
#define ll long long
#define ull unsigned long long
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
#define cin fin
#define cout fout
/*
ifstream fin("test.in");
#define cin fin
*/
#define Nmax 100001
int n, m;
vector < int > tati(Nmax + 1, 0);
vector < int > dp (Nmax + 1, 0);
void DFS(int nod, int nivel) {
dp[nod] = nivel;
for(int i=1; i <= n; i++) {
if(tati[i] == nod) {
DFS(i, nivel + 1);
}
}
}
void solve() {
cin >> n >> m;
for(int i=2; i <= n; i++) {
cin >> tati[i];
}
DFS(1, 0);
while(m-- ){
int a, b;
cin >> a >> b;
while(a != b) {
if(dp[a] > dp[b]) {
a = tati[a];
} else {
b = tati[b];
}
}
cout << a << endl;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin .tie(0);
cout.tie(0);
int testCases = 1;
//cin >> testCases;
while(testCases--) {
solve();
}
}