Cod sursa(job #2077896)

Utilizator circeanubogdanCirceanu Bogdan circeanubogdan Data 28 noiembrie 2017 18:17:51
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include <fstream>
#include <cstdio>
#include <vector>
#include <cmath>
#define DIM 100002
#define ff first
#define ss second

using namespace std;

//ifstream f("lca.in");
//ofstream g("lca.out");



int n, q, t[DIM], k, put[DIM], x, y, l, d[20][DIM], nivel[DIM], putere;

vector<int> arb[DIM];

void dfs(int nod, int niv){
    nivel[nod] = niv;
    for(int i = 0; i < arb[nod].size(); ++ i)
        dfs(arb[nod][i], niv + 1);
}

int main()
{

    freopen("lca.in", "r", stdin);
    freopen("lca.out", "w", stdout);

    scanf("%d %d", &n, &q);
    for(int i = 2; i <= n; ++ i){
        scanf("%d", &d[0][i]);
        arb[d[0][i]].push_back(i);
    }

    dfs(1, 1);

    for(int k = 1; (1 << k) <= n; ++ k){
        for(int i = 1; i <= n; ++ i){
            d[k][i] = d[k - 1][d[k - 1][i]];
        }
    }

    for(int i = 2; i <= n; ++ i)
        put[i] = 1 + put[i / 2];

    for(int i = 1; i <= q; ++ i){
        //f>>x>>y;
        scanf("%d %d", &x, &y);
        if(nivel[y] < nivel[x])
            swap(x, y);
        int dif = nivel[y] - nivel[x];
        if(dif != 0){
            while(dif){
                int putere = put[dif];
                y = d[putere][y];
                dif -= (1 << putere);
            }
        }
        if(x == y)
            //g<<x<<'\n';
            printf("%d\n", x);
        else{
            int ok = 1;
            while(x && d[0][x] != d[0][y]){
                if(ok == 1)
                    putere = put[nivel[x]];
                else
                    -- putere;
                ok = 0;
                if(d[putere][x] != d[putere][y]){
                    x = d[putere][x];
                    y = d[putere][y];
                    ok = 1;
                }
                if(x == y){
                    //g<<x<<'\n';
                    printf("%d\n", x);
                    break;
                }
            }
            printf("%d\n", d[0][x]);
        }

    }




    return 0;
}