Cod sursa(job #2214774)

Utilizator AndreiDumitrescuAndrei Dumitrescu AndreiDumitrescu Data 20 iunie 2018 01:33:19
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream f("lca.in");
ofstream g("lca.out");


int nivel[100010], tati[100010];
vector < vector<int>> v;

int DFS(int nod, int nivel_actual)
{
    nivel[nod] = nivel_actual;
    for(int i = 0; i < v[nod].size(); i++)
        DFS(v[nod][i], nivel_actual + 1);
}

int query(int x, int y)
{
    while(nivel[x] > nivel[y])
        x = tati[x];
    while(nivel[y] > nivel[x])
        y = tati[y];
    if(x == y)
        return x;
    while(x != y)
    {
        x = tati[x];
        y = tati[y];
    }
    return x;
}
int main()
{
    int n, m;
    f >> n >> m;
    v.resize(n + 2);
    for(int i = 2 ; i <= n ; i++)
    {
        int x;
        f >> x;
        v[x].push_back(i);
        tati[i] = x;
    }
    DFS(1, 0);
    for(int i = 0 ; i < m; i++)
    {
        int x, y;
        f >> x >> y;
        g << query(x, y) << '\n';
    }
}