Cod sursa(job #2509178)

Utilizator Briana_NeaguNeagu Briana Briana_Neagu Data 13 decembrie 2019 22:06:59
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>

using namespace std;

//varianta 2 - Heavy Path

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

const int nmax = 100005;
vector <int> son[nmax];

int deep[nmax];
int weight[nmax];
int where[nmax];
int last[nmax];
int father[nmax];

int cnt;

void dfs(int nod, int lvl)
{
    deep[nod] = lvl;
    int maxSon = 0;
    for (auto el : son[nod])
    {
        dfs(el, lvl + 1);
        weight[nod] += weight[el] + 1;
        if (maxSon == 0 || weight[el] > weight[maxSon])
            maxSon = el;
    }
    if (weight[nod] == 0)
    {
        where[nod] = ++ cnt;
        last[cnt] = nod;
    }
    else
    {
        assert(maxSon != 0);
        where[nod] = where[maxSon];
        last[where[nod]] = nod;
    }
}

int solve(int a, int b)
{
    while (where[a] != where[b])
    {
      if (deep[last[where[a]]] < deep[last[where[b]]])
          swap(a, b);
      a = father[last[where[a]]];
    }
    if (weight[a] > weight[b])
        return a;
    else
        return b;
}


int main()
{
    int n, m;
    f >> n >> m;
    for (int i = 1; i < n; ++ i)
    {
        int x;
        f >> x;
        son[x].push_back(i + 1);
        father[i + 1] = x;
    }
    dfs(1, 1);
    for (int i = 1; i <= m; ++ i)
    {
        int a, b;
        f >> a >> b;
        g << solve(a, b) << '\n';
    }
}