Cod sursa(job #933089)

Utilizator PatrikStepan Patrik Patrik Data 29 martie 2013 16:41:48
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
    #include<cstdio>
    #include<vector>
    using namespace std;
    #define MAX 100001
    #define pb push_back
    int N ,M , T[MAX]  , Lev[MAX];
    vector<int>G[MAX] ;

    void DF(int nod,int lev)
    {
        Lev[nod] = lev;
        for(int j = 0 ; j < (int)G[nod].size() ; ++j )
            DF(G[nod][j],lev+1);
    }

    int main()
    {
        int x , y;
        freopen("lca.in" , "r" , stdin );
        freopen("lca.out" , "w" , stdout );
        scanf("%d%d" , &N , &M );
        for(int i = 2 ; i <= N ; ++i )
            {scanf("%d" , &T[i]);
            G[T[i]].pb(i);}
        DF(1,0);
        for(int i = 1 ; i <= M ; ++i )
        {
            scanf("%d%d" , &x , &y );
            while(x != y)
                if(Lev[x] > Lev[y])
                    x = T[x];
                else
                    y = T[y];
            printf("%d\n" , x);
        }
        return 0;
    }