Cod sursa(job #2093296)

Utilizator MaligMamaliga cu smantana Malig Data 23 decembrie 2017 12:55:20
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include <iostream>
#include <fstream>
#include <vector>

#if 1
#define pv(x) cout<<#x<<" = "<<x<<"; ";cout.flush()
#define pn cout<<endl
#else
#define pv(x)
#define pn
#endif

using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");

using ll = long long;
using ull = unsigned long long;
using ui = unsigned int;
#define pb push_back
#define mp make_pair
const int NMax = 1e5 + 5;
const ll inf = 1e18 + 5;
const int mod = 100003;
using zint = int;

int N,M,H,root;
int depth[NMax],dad[NMax],an[NMax];
vector<int> v[NMax];

void dfs(int);
void build(int);

int main() {
    in>>N>>M;

    for (int i=2;i <= N;++i) {
        int node;
        in>>node;

        dad[i] = node;
        v[node].pb(i);
    }

    dfs(1);

    root = 1;
    for (;root * root < H;++root) ;
    --root;

    build(1);

    while (M--) {
        int x,y;

        in>>x>>y;

        while (an[x] != an[y]) {
            if (depth[x] > depth[y]) {
                x = an[x];
            }
            else {
                y = an[y];
            }
        }

        while (x != y) {
            if (depth[x] > depth[y]) {
                x = dad[x];
            }
            else {
                y = dad[y];
            }
        }

        out<<x<<'\n';
    }

    return 0;
}

void dfs(int node) {
    depth[node] = depth[dad[node]] + 1;

    for (int nxt : v[node]) {
        dfs(nxt);
    }

    H = max(H,depth[node]);
}

void build(int node) {
    if (depth[node] % root == 0) {
        an[node] = dad[node];
    }
    else {
        an[node] = an[dad[node]];
    }

    for (int nxt : v[node]) {
        build(nxt);
    }
}