Cod sursa(job #2001298)

Utilizator MaligMamaliga cu smantana Malig Data 16 iulie 2017 13:11:22
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <stack>

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],ans[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);

    root = 1;
    while (root * root <= H) {
        ++root;
    }
    --root;

    build(1);

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

        out<<query(x,y)<<'\n';
    }

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

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

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

        dfs(nxt);
    }

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

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

    for (int nxt : v[node]) {
        if (ans[nxt]) {
            continue;
        }

        build(nxt);
    }
}

int query(int x,int y) {
    while (ans[x] != ans[y]) {
        if (depth[x] > depth[y]) {
            x = ans[x];
        }
        else {
            y = ans[y];
        }
    }

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