Cod sursa(job #2044541)

Utilizator MaligMamaliga cu smantana Malig Data 21 octombrie 2017 10:58:42
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <map>
#include <algorithm>

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

#define ll long long
#define ull unsigned long long
#define pb push_back
const int NMax = 1e5 + 5;
const ll inf = 1e18 + 7;

int N,M,H,root;
int dad[NMax],depth[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) {
        in>>dad[i];
        v[dad[i]].pb(i);
    }

    depth[1] = 1;
    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';
    }

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

void dfs(int node) {

    for (int nxt : v[node]) {
        depth[nxt] = depth[node] + 1;

        dfs(nxt);
    }

    if (depth[node] > H) {
        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);
    }
}