Cod sursa(job #3005645)

Utilizator MihaiZ777MihaiZ MihaiZ777 Data 17 martie 2023 09:57:06
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;

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

const int MAX_N = 100000;

int n, m;
int depth[MAX_N];
int ancestors[20][MAX_N];
vector <int> graph[MAX_N];


void DFS(int node, int d) {
    depth[node] = d;
    for (int i = 1; i < 20; i++) {
        ancestors[i][node] = ancestors[i - 1][ancestors[i - 1][node]];
    }
    for (int newNode : graph[node]) {
        DFS(newNode, d + 1);
    }
}

int main() {
    fin >> n >> m;
    for (int i = 2; i <= n; i++) {
        int node;
        fin >> node;

        ancestors[0][i] = node;
        graph[node].push_back(i);
    }

    DFS(1, 1);
    for (int i = 1; i <= m; i++) {
        int a, b;
        fin >> a >> b;

        if (depth[a] < depth[b]) {
            swap(a, b);
        }
        int depthDiff = depth[a] - depth[b];

        for (int e = 0; e < 20; e++) {
            if (depthDiff & (1 << e)) {
                a = ancestors[e][a];
            }
        }

        if (a == b) {
            fout << a << '\n';
            continue;
        }

        for (int e = 19; e >= 0; e++) {
            if (ancestors[e][a] != ancestors[e][b]) {
                a = ancestors[e][a];
                b = ancestors[e][b];
            }
        }

        fout << ancestors[0][a] << '\n';
    }
}