Cod sursa(job #2028159)

Utilizator LucaSeriSeritan Luca LucaSeri Data 27 septembrie 2017 11:40:27
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <vector>
// SOLUTIA 1 - BRUT
using namespace std;
const int Maxn = 1e5 + 1e4;

ifstream cin("lca.in");
ofstream cout("lca.out");

int tata[Maxn];
int nivel[Maxn];
vector <int> gr[Maxn];

void dfs(int node, int boss, int lvl){
    nivel[node] = lvl;
    for(int x : gr[node]){
        if(x == boss) continue;
        dfs(x, node, lvl+1);
    }
}

int solve(int x, int y){
    if(nivel[x] < nivel[y]) swap(x, y);
    while(nivel[x] > nivel[y]) x = tata[x];
    while(x != y) x = tata[x], y = tata[y];
    return x;
}

int main(){
    int n, m;
    cin >> n >> m;
    tata[1] = 0;
    for(int i = 2; i <= n; ++ i){
         cin >> tata[i];
         gr[i].push_back(tata[i]);
         gr[tata[i]].push_back(i);
    }
    dfs(1, 0, 1);
    for(int i = 1; i <= m; ++ i){
        int x, y;
        cin >> x >> y;
        cout << solve(x, y) << '\n';
    }
    return 0;
}