Cod sursa(job #1919823)

Utilizator tudormaximTudor Maxim tudormaxim Data 9 martie 2017 21:11:08
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <cmath>
using namespace std;

ifstream fin ("lca.in");
ofstream fout ("lca.out");

const int maxn = 1e5 + 5;
vector <int> G[maxn];
int Dad[maxn], Ancestor[maxn], Lev[maxn];

int Lca (int x, int y) {
    while (Ancestor[x] != Ancestor[y]) {
        if (Lev[x] > Lev[y]) {
            x = Ancestor[x];
        } else {
            y = Ancestor[y];
        }
    }
    while (x != y) {
        if (Lev[x] > Lev[y]) {
            x = Dad[x];
        } else {
            y = Dad[y];
        }
    }
    return x;
}

void Dfs (int node, int rad) {
    vector <int> :: iterator it;
    if (Lev[node] < rad) {
        Ancestor[node] = 1;
    } else if (Lev[node] % rad == 0) {
        Ancestor[node] = Dad[node];
    } else {
        Ancestor[node] = Ancestor[Dad[node]];
    }
    for (it = G[node].begin(); it != G[node].end(); it++) {
        Dfs(*it, rad);
    }
}

int main() {
    ios_base :: sync_with_stdio (false);
    int n, m, x, y, i, maxx = 0;
    fin >> n >> m;
    for (i = 2; i <= n; i++) {
        fin >> Dad[i];
        G[Dad[i]].push_back(i);
        Lev[i] = Lev[Dad[i]] + 1;
        maxx = max(maxx, Lev[i]);
    }
    Dfs(1, sqrt(maxx));
    for (i = 1; i <= m; i++) {
        fin >> x >> y;
        fout << Lca(x, y) << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}