Cod sursa(job #2509023)

Utilizator Briana_NeaguNeagu Briana Briana_Neagu Data 13 decembrie 2019 17:32:30
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.75 kb
#include <bits/stdc++.h>

using namespace std;

//varianta 1 - brute force

const int nmax =  100005;

int deep[nmax];
int father[nmax];
vector <int> son[nmax];

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

void dfs(int nod, int lvl)
{
  deep[nod] = lvl;
  for (auto el : son[nod])
      dfs(el, lvl + 1);
}

int main()
{
    int n, m;
    f >> n >> m;
    for (int i = 1; i < n; ++ i)
    {
        int nod;
        f >> nod;
        son[nod].push_back(i + 1);
        father[i + 1] = nod;
    }
    dfs(1, 1);
    while (m --)
    {
        int a, b;
        f >> a >> b;
        while (a != b)
        {
            if (deep[a] > deep[b])
                a = father[a];
            else
                b = father[b];
        }
        g << a << '\n';
    }
}