Cod sursa(job #2412363)

Utilizator alexandra_udristoiuUdristoiu Alexandra Maria alexandra_udristoiu Data 22 aprilie 2019 10:23:44
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include<fstream>
#include<vector>
#define DIM 100005
using namespace std;
int n, m, i, ii, x, y, dif;
int t[DIM], a[17][DIM], b[DIM], niv[DIM];
vector<int> v[DIM];
ifstream fin("lca.in");
ofstream fout("lca.out");
void dfs(int nod){
    for(int i = 0; i < v[nod].size(); i++){
        niv[ v[nod][i] ] = 1 + niv[nod];
        dfs(v[nod][i]);
    }
}
int main(){
    fin>> n >> m;
    for(i = 2; i <= n; i++){
        fin>> t[i];
        v[ t[i] ].push_back(i);
    }
    niv[1] = 1;
    dfs(1);
    for(i = 2; i <= n; i++){
        b[i] = 1 + b[i / 2];
        a[0][i] = t[i];
    }
    for(ii = 1; (1 << ii) <= n; ii++){
        for(i = 1; i <= n; i++){
            if(a[ii - 1][i] != 0){
                a[ii][i] = a[ii - 1][ a[ii - 1][i] ];
            }
        }
    }
    for(; m; m--){
        fin>> x >> y;
        if(niv[x] > niv[y]){
            swap(x, y);
        }
        dif = niv[y] - niv[x];
        while(dif != 0){
            y = a[ b[dif] ][y];
            dif -= (1 << b[dif]);
        }
        if(x == y){
            fout<< x <<"\n";
            continue;
        }
        for(i = ii - 1; i >= 0; i--){
            if(a[i][x] != a[i][y]){
                x = a[i][x];
                y = a[i][y];
            }
        }
        fout<< a[0][x] <<"\n";
    }
    return 0;
}