Cod sursa(job #738595)

Utilizator gener.omerGener Omer gener.omer Data 21 aprilie 2012 01:13:05
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <iostream>
#include <fstream>
#include <cmath>

using namespace std;

#define NMAX 100005

int N, M, A[NMAX], h[NMAX], P[NMAX];

int find_height(int i){
    if(h[i] != -1)
        return h[i];
    h[i] = find_height(A[i]) + 1;
}

void compute_heights(){
    h[1] = 0;
    for(int i = 2; i <= N; ++i) h[i] = -1;
    for(int i = 2; i <= N; ++i)
        if(h[i] == -1)
            find_height(i);
}

int getMaxHeight(){
    int m = 0;
    for(int i = 1; i <= N; ++i)
        m = max(h[i], m);
    return m;
}

void preprocess(){
    int bucket = static_cast<int>(sqrt(getMaxHeight() + 1));
    for(int i = 1; i <= N; ++i){
        if(h[i] < bucket) P[i] = 1;
        else{
            if(h[i] % bucket == 0)
                P[i] = A[i];
            else
                P[i] = P[A[i]];
        }
    }
}

int solve(int x, int y){
    while(P[x] != P[y]){
        if(h[x] < h[y])
            y = P[y];
        else
            x = P[x];
    }
    while(x != y){
        if(h[x] < h[y])
            y = A[y];
        else
            x = A[x];
    }

}

int main(){
    ifstream in("lca.in");
    ofstream out("lca.out");
    in >> N >> M;
    A[1] = 0;
    for(int i = 2; i <= N; ++i)
        in >> A[i];
    compute_heights();
    preprocess();
    for(int i = 0; i < M; ++i){
        int x, y;
        in >> x >> y;
        int ret = solve(x, y);
        out << ret << endl;
    }
    return 0;
}