Cod sursa(job #2664480)

Utilizator TheGodFather2131Alexandru Miclea TheGodFather2131 Data 28 octombrie 2020 18:22:41
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.18 kb
//ALEXANDRU MICLEA

#include <vector>
#include <algorithm>
#include <string>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <time.h>
#include <iomanip>
#include <deque>
#include <math.h>
#include <cmath>
#include <assert.h>
#include <stack>
#include <bitset>
#include <random>
#include <chrono>
#include <assert.h>

using namespace std;

#include <fstream>
//ifstream cin("input.in"); ofstream cout("output.out");
ifstream cin("lca.in"); ofstream cout("lca.out");

//VARIABLES

const int MAXN = 100005;

int st[25][MAXN];
int LOG[MAXN];

int h[MAXN];

vector <vector <int> > gr(MAXN);

//FUNCTIONS

void dfs(int nod) {

    for (auto& x : gr[nod]) {
        h[x] = h[nod] + 1;
        dfs(x);
    }

}

//MAIN
int main() {

    int n, m;
    cin >> n >> m;

    for (int i = 2; i <= n; i++) LOG[i] = LOG[i / 2] + 1;

    for (int i = 2; i <= n; i++) {
        cin >> st[0][i];
        gr[st[0][i]].push_back(i);
    }

    for (int p = 1; p <= LOG[n]; p++) {
        for (int i = 1; i <= n; i++) {
            st[p][i] = st[p - 1][st[p - 1][i]];
        }
    }

    /*for (int p = 0; p <= LOG[n]; p++) {
        for (int i = 1; i <= n; i++) {
            cout << st[p][i] << " ";
        }
        cout << '\n';
    }*/

    dfs(1);

    /*for (int i = 1; i <= n; i++) cout << h[i] << ' ';
    cout << '\n';*/
    
    for (int i = 1; i <= m; i++) {
        int x, y;
        cin >> x >> y;

        if (h[x] > h[y]) {
            int pos = h[x] - h[y];

            while (pos) {
                x = st[LOG[pos]][x];
                pos -= (1 << LOG[pos]);
            }
        }
        else {
            int pos = h[y] - h[x];

            while (pos) {
                y = st[LOG[pos]][y];
                pos -= (1 << LOG[pos]);
            }
        }

        if (x == y) {
            cout << x << '\n';
            continue;
        }

        for (int p = LOG[h[x]]; p >= 0; p--) {
            if (st[p][x] != st[p][y]) {
                x = st[p][x];
                y = st[p][y];
            }
        }
        cout << st[0][x] << '\n';
    }
    
    return 0;
}