Cod sursa(job #673822)

Utilizator R.A.RFMI Romila Remus Arthur R.A.R Data 4 februarie 2012 22:11:54
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.65 kb
#include <fstream>
#define nmax 100002

using namespace std;

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

int Op,N;

int T[nmax],Arb[nmax];

int LCA(int x,int y)
{
    int x2 = x;
    while(x2)
    {
        Arb[x2] = x;
        x2 = T[x2];
    }//am marcat cu x2 toti tatii lui
    //caut pt y cel mai apropiat stramos al carui Arb sa fie x2
    while(Arb[y]!=x)
        y = T[y];
    return y;
}

int main()
{
    int x,y,i;
    in>>N>>Op;
    for(i=2;i<=N;i++)
        in>>T[i];
    while(Op--)
    {
        in>>x>>y;
        //afisez cel mai apropiat stramos comun
        out<<LCA(x,y)<<'\n';
    }
    return 0;
}