Cod sursa(job #3307285)

Utilizator Victor5539Tanase Victor Victor5539 Data 19 august 2025 16:40:26
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");

const int MAX=1e5;
int n,i,t[MAX+5],depth[MAX+5],node1,node2,q;
bool viz[MAX+5];
vector <int> edge[MAX+5];

void dfs(int node)
{
    viz[node]=1;

    for (auto node2: edge[node])
    {
        if (!viz[node2])
        {
            depth[node2]=depth[node]+1;
            dfs(node2);
        }
    }
}

int lca(int x, int y)
{
    if (depth[x]<depth[y])
        swap(x,y);

    while (depth[x]>depth[y])
        x=t[x];

    while (x!=y)
    {
        x=t[x];
        y=t[y];
    }

    return x;
}

int main()
{
    ios_base::sync_with_stdio(false);
    fin.tie(0); fout.tie(0);

    fin>>n>>q;

    for (i=2; i<=n; i++)
    {
        fin>>t[i];
        edge[i].push_back(t[i]);
        edge[t[i]].push_back(i);
    }

    dfs(1);

    while (q--)
    {
        fin>>node1>>node2;

        fout<<lca(node1,node2)<<'\n';
    }



    return 0;
}