Cod sursa(job #1309853)

Utilizator thesvcoolmanLucian Bicsi thesvcoolman Data 6 ianuarie 2015 09:12:20
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include<cstdio>
#include<vector>

#define NMAX 102

using namespace std;

vector<int> PARENT;
vector<int> RANK;
int n, t;

int makeRank(int i) {
    if(i == 1) return 0;
    if(RANK[i]) return RANK[i];
    else RANK[i] = makeRank(PARENT[i]) + 1;
}

int lca (int a, int b) {
    while(RANK[a] > RANK[b]) {
        a = PARENT[a];
    }
    while(RANK[b] > RANK[a]) {
        b = PARENT[b];
    }
    while(b != a) {
        a = PARENT[a];
        b = PARENT[b];
    }

    return a;
}

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

    scanf("%d %d", &n, &t);

    PARENT.resize(n+1, 0);
    RANK.resize(n+1, 0);

    for(int i=2; i<=n; i++) {
        scanf("%d", &PARENT[i]);
        RANK[i] = RANK[PARENT[i]] + 1;
    }

    int a, b;
    for(int i=1; i<=t; ++i) {
        scanf("%d %d", &a, &b);
        printf("%d\n", lca(a, b));
    }

    return 0;
}