Cod sursa(job #1991140)

Utilizator MaligMamaliga cu smantana Malig Data 15 iunie 2017 13:47:18
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stack>
#include <vector>

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

#define ll long long
#define pb push_back
const int inf = 1e9 + 5;
const int NMax = 1e5 + 5;

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

void dfs(int);
void build(int);
int query(int,int);

int main() {
    in>>N>>M;
    for (int i=2;i <= N;++i) {
        in>>dad[i];
        v[dad[i]].pb(i);
    }

    dfs(1);

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

    while (M--) {
        int a,b;
        in>>a>>b;
        out<<query(a,b)<<'\n';
    }

    in.close();out.close();
    return 0;
}

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

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

    for (auto nxt : v[node]) {
        if (depth[nxt]) {
            continue;
        }

        dfs(nxt);
    }
}

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

    for (auto nxt : v[node]) {
        if (an[nxt]) {
            continue;
        }

        build(nxt);
    }
}

int query(int x,int 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];
        }
    }

    return x;
}