Cod sursa(job #1900184)

Utilizator DobosDobos Paul Dobos Data 3 martie 2017 10:44:25
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.9 kb
#include <bits/stdc++.h>
#define NMAX 100005

using namespace std;

ifstream fin("lca.in");
ofstream fout("lca.out");

int D[NMAX],ant[NMAX];

vector < int > G[NMAX];

void DFS(const int &nod){

    for(auto const &it : G[nod]){
        D[it] = D[nod] + 1;
        DFS(it);
    }

}

int LCA(int x,int y){

    if(x == y)
        return x;
    if(D[x] == D[y] && ant[x] == ant[y])
        return ant[x];
    if(D[x] == D[y])
        return LCA(ant[x],ant[y]);
    if(D[x] < D[y])
        return LCA(x,ant[y]);
    else
        return LCA(ant[x],y);
}

int main()

{
    ios :: sync_with_stdio(false);

    int n,m,x,y;

    fin >> n >> m;

    for(int i = 2; i <= n; i++){
        fin >> ant[i];
        G[ant[i]].push_back(i);
    }

    DFS(1);

    for(int i = 1; i <= m; i++){
        fin >> x >> y;
        fout << LCA(x,y) << "\n";
    }

    return 0;
}