Cod sursa(job #2632038)

Utilizator xCata02Catalin Brita xCata02 Data 2 iulie 2020 01:05:27
Problema Lowest Common Ancestor Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#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();
    }
}