Cod sursa(job #2203694)

Utilizator Menage_a_011UPB Cheseli Neatu Popescu Menage_a_011 Data 12 mai 2018 21:34:43
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 kb
// https://goo.gl/fBmFxu
#include <bits/stdc++.h>
using namespace std;

#define NMAX        100009
#define MMAX        200009
#define LGMAX       21
#define kInf        (1 << 30)
#define kInfLL      (1LL << 60)
#define kMod        666013
#define edge pair<int, int>
#define x first
#define y second

#define USE_FILES "MLC"

#ifdef USE_FILES
#define cin fin
#define cout fout
ifstream fin("lca.in");
ofstream fout("lca.out");
#endif

// number of tests from "in"
int test_cnt = 1;
void clean_test();

// your global variables are here
int n, m;
int stramos[17][NMAX], nivel[NMAX];
vector <int> G[NMAX];

void dfs(int nod, int lev) {
    nivel[nod] = lev;
    vector<int>::iterator it;
    for(it = G[nod].begin(); it != G[nod].end(); ++it)
        dfs(*it, lev+1);
}

int lca(int x, int y) {
    if(nivel[x] < nivel[y])
        swap(x, y);

    int log1, log2;
    for(log1 = 1; (1 << log1) < nivel[x]; ++log1);
    for(log2 = 1; (1 << log2) < nivel[y]; ++log2);

    for(int k = log1; k >= 0; --k) {
        if(nivel[x] - (1 << k) >= nivel[y])
            x = stramos[k][x];
    }

    if(x == y)
        return x;

    for(int k = log2; k >= 0; --k) {
        if(stramos[k][x] && stramos[k][x] != stramos[k][y]) {
            x = stramos[k][x];
            y = stramos[k][y];
        }
    }
    return stramos[0][x];
}
// your solution is here
void solve() {
    // n nr de noduri
    // m nr de query-uri
    cin >> n >> m;
    for (int i = 2; i <= n; ++i) {
        cin >> stramos[0][i];
        G[stramos[0][i]].push_back(stramos[0][i]);
    }

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

    dfs(1, 0);

    while(m--) {
        int x, y;
        cin >> x >> y;
        cout << lca(x, y) << "\n";
    }

    if (test_cnt > 0) {
        clean_test();
    }
}


void clean_test() {
    // clean if needed
    for (int i = 1; i <= n; ++i)
        G[i].clear();

}

int main() {
//     cin >> test_cnt;
    while (test_cnt--) {
        solve();
    }

    return 0;
}