Cod sursa(job #2723556)

Utilizator KakaDuuTurbut Sebastian KakaDuu Data 14 martie 2021 19:38:43
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;
struct Euler {
    int node;
    int depth;
};
int n, m, tati[200000];
vector<Euler> euler;

void gen(int nod, int poz, int depth) {
    while (tati[poz] == nod) {
        euler.push_back({nod, depth});
        int nextpoz = -1, j;
        for (j = 0; tati[j] != poz + 2 && j < n - 1; j++);
        if (j != n - 1)
            nextpoz = j;
        if (nextpoz != -1)
            gen(poz + 2, nextpoz, depth + 1);
        else
            euler.push_back({poz + 2, depth + 1});
        poz++;
    }
    euler.push_back({nod, depth});
}

int main() {
    ifstream fin("lca.in");
    ofstream fout("lca.out");
    fin >> n >> m;
    for (int i = 0; i < n - 1; i++)
        fin >> tati[i];
    gen(tati[0], 0, 0);

    for (int i = 0; i < m; i++) {
        int x, y, minDepth = n, dpoz, j;
        fin >> x >> y;
        bool k = false, l = false;
        for (j = 0; j < euler.size() && !l; j++) {
            if (euler[j].node == x) {
                minDepth = euler[j].depth;
                dpoz = euler[j].node;
                k = true;
            }
            if (euler[j].depth < minDepth) {
                minDepth = euler[j].depth;
                dpoz = euler[j].node;
            }
            if (k && euler[j].node == y) {
                if (euler[j].depth < minDepth) {
                    minDepth = euler[j].depth;
                    dpoz = euler[j].node;
                }
                l = true;
            }
        }
        cout << dpoz << endl;
    }
    return 0;
}