Cod sursa(job #1900195)

Utilizator DobosDobos Paul Dobos Data 3 martie 2017 10:49:09
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.79 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){



    while(x != y){

        if(D[x] > D[y])
            x = ant[x];
        else
            y = ant[y];

    }
    return x;
}

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;
}