Cod sursa(job #2198658)

Utilizator PushkinPetolea Cosmin Pushkin Data 24 aprilie 2018 23:04:23
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.65 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 int LCA(int x, int 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];
    }
    return x;
}
int main()
{
    int x, y;
    rd();
    while(f>>x>>y)
        g<<LCA(x, y)<<'\n';
    f.close();
    g.close();
    return 0;
}