Cod sursa(job #3241585)

Utilizator adelinapetreAdelina Petre adelinapetre Data 31 august 2024 19:35:45
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
#include <vector>
using namespace std;

ifstream cin ("lca.in");
ofstream cout ("lca.out");

const int Nmax = 1e5 + 5;

int depth[Nmax], head[Nmax], heavy[Nmax], parent[Nmax], lin[Nmax];
vector<int> g[Nmax];

int dfs(int nod)
{
    int weight = 1, maxweight = 0;
    for(auto it : fii[nod])
    {
        depth[it] = depth[nod] + 1;
        int nweight = dfs(it);
        weight += nweight;
        if(nweight > maxweight)
            maxweight = nweight, heavy[nod] = it;
    }
    return weight;
}

void dfs2(int nod)
{
   // cout << nod << endl;
    if(nod == 1)
    {
        head[1] = 1;
    }
    for(auto it : fii[nod])
    {
        if(it != heavy[nod])
        {
            head[it] = it;
            dfs2(it);
        }
    }
    if(heavy[nod] == 0)
        return;
    head[heavy[nod]] = head[nod];
    dfs2(heavy[nod]);
}

int solve(int a, int b)
{
    while(1)
    {
        //cout << a << " " << b << " " << head[a] << " " << head[b] << '\n';
        if(head[a] == head[b])
            return (depth[a] < depth[b] ? a : b);
        if(depth[head[a]] > depth[head[b]])
            a = parent[head[a]];
        else
            b = parent[head[b]];
    }
}

int main()
{
    int n, m, a, b;
    cin >> n >> m;
    for(int i = 2; i <= n; i ++)
    {
        cin >> parent[i];
        if(i != parent[i])
            fii[parent[i]].push_back(i);
    }
    dfs(1);
    dfs2(1);
    while(m --)
    {
        cin >> a >> b;
        cout << solve(a, b) << '\n';
    }
    return 0;
}