Cod sursa(job #2198660)

Utilizator PushkinPetolea Cosmin Pushkin Data 24 aprilie 2018 23:16:10
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.7 kb
#include <iostream>
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
vector<int> G, L;
int n, m;
inline void rd()
{
    int x=1;
    f>>n>>m;
    G.resize(n+1);
    L.resize(n+1);
    G[x]=-1;
    L[x]=0;
    while(x<n&&f>>G[++x])
    L[x]=L[G[x]]+1;
}
inline void LCA()
{
    int x, y;
    while(f>>x>>y)
    {
        if(L[x]<=L[y])
            swap(x, y);
        while(L[x]>L[y])
            x=G[x];
        while(x!=y)
        {
            x=G[x];
            y=G[y];
        }
        g<<x<<'\n';
    }
}
int main()
{
    int x, y;
    rd();
    LCA();
    f.close();
    g.close();
    return 0;
}