Cod sursa(job #2306824)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 22 decembrie 2018 23:47:59
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <cmath>

using namespace std;

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

const int NMAX = 100005;

vector<int> g[NMAX], p[NMAX];
int color[NMAX], ncolors;
int dad[NMAX], h[NMAX];

int dfs(int node, int level) {
    int mx = 0, son, dim = 1;
    for(auto it: g[node])
        if(h[it] == 0) {
            h[it] = h[node] + 1;
            dad[it] = node;
            int aux = dfs(it, level + 1);

            if(aux > mx) {
                mx = aux;
                son = it;
            }

            dim += aux;
        }

    if(dim == 1) {
        ncolors ++;
        color[node] = ncolors;
        p[ncolors].push_back(node);
    } else {
        color[node] = color[son];
        p[color[son]].push_back(node);
    }

    return dim;
}

int main() {
    int n, m;
    in >> n >> m;
    for(int i = 2; i <= n; i ++) {
        int x;
        in >> x;
        g[x].push_back(i);
        g[i].push_back(x);
    }

    h[1] = 1;
    dfs(1, 1);

    for(int qr = 1; qr <= m; qr ++) {
        int x, y;
        in >> x >> y;

        while(color[x] != color[y]) {
            int fatherx = p[color[x]].back(), fathery = p[color[y]].back();
            if(h[fatherx] > h[fathery]) {
                x = fatherx;
                x = dad[x];
            } else {
                y = fathery;
                y = dad[y];
            }
        }

        if(h[x] < h[y])
            out << x << "\n";
        else
            out << y << "\n";
    }

    return 0;
}