Cod sursa(job #2126878)

Utilizator andr3i_kaabAndrei Ciineanu andr3i_kaab Data 10 februarie 2018 02:29:24
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
//#include <iostream>
#include <fstream>

using namespace std;

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

int n, m, dads[100002];

int main()
{
    int i, j, x, y;
    f>>n>>m;
    dads[1]=0;
    for (i=2; i<=n; i++) f>>dads[i];

    for (i=1; i<=m; i++)
    {
        f>>x>>y;
        while (x && y)
        {
            //x=dads[x]; y=dads[y];
            int d1, d2;
            d1=dads[x]; d2=dads[y];
            if (d1==d2)
            {
                x=dads[x]; y=dads[y];
                cout<<x<<"\n";
                break;
            }
            else
             if (d1==y || d2==x)
             {
                 if (x<y) cout<<x<<"\n";
                 else cout<<y<<"\n";
                 x=dads[x]; y=dads[y];
                 break;
             }
             else x=dads[x], y=dads[y];
        }
    }
    return 0;
}