Cod sursa(job #1329648)

Utilizator okros_alexandruOkros Alexandru okros_alexandru Data 29 ianuarie 2015 18:51:48
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
#include <vector>

#define Lmax 18
#define Nmax 100100

using namespace std;

vector <int> Tree[Nmax];
int N, Level[Nmax], Log2[Nmax], Father[Lmax][Nmax];

int lca(int x, int y) {

    for(; Level[x] > Level[y]; x = Father[Log2[Level[x] - Level[y]]][x]);
    for(; Level[y] > Level[x]; y = Father[Log2[Level[y] - Level[x]]][y]);

    for(int step = Log2[Level[x]]; step != -1; step--)
        if(Father[step][x] != Father[step][y]) {
            x = Father[step][x];
            y = Father[step][y];
        }

    if(x != y)
        x = Father[0][x];

    return x;
}
void process() {

    int i, j;

    for(i = 2; i <= N; i++)
        Log2[i] = Log2[i >> 1] + 1;

    for(i = 1; i <= Log2[N]; i++)
        for(j = 1; j <= N; j++)
            Father[i][j] = Father[i - 1][ Father[i - 1][j] ];

}
void Dfs(int node, int level) {

    Level[node] = level;

    for(int i = 0; i < Tree[node].size(); i++)
        Dfs(Tree[node][i], level + 1);

}
int main() {

    int i, x, y, queries;
    ifstream in("lca.in");
    ofstream out("lca.out");

    in >> N >> queries;
    for(i = 2; i <= N; i++) {
        in >> x;
        Tree[x].push_back(i);
        Father[0][i] = x;
    }

    Dfs(1, 0);
    process();

    while(queries--) {
        in >> x >> y;
        out << lca(x, y) << '\n';
    }

    in.close();
    out.close();

    return 0;
}