Cod sursa(job #3229115)

Utilizator AlinSSimilea Alin-Andrei AlinS Data 13 mai 2024 22:28:13
Problema Lowest Common Ancestor Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.08 kb
#include <bits/stdc++.h>
using namespace std;

class Task {
public:
    void solve() {
        read_input();
        print_output(get_result());
    }

private:
    // numarul maxim de noduri
    static constexpr int NMAX = (int)1e5 + 5; // 10^5 + 5 = 100.005

    // n = numar de noduri, m = numar de perechi
    int n, m;

    vector<pair<int, int>> pairs_of_nodes;

    // adj[node] = lista de adiacenta a nodului node
    vector<int> adj[NMAX];

    void read_input() {
        ifstream fin("lca.in");
        fin >> n >> m;
        for (int i = 2, x; i <= n; i++) {
            fin >> x; // muchie (i, x)
            adj[i].push_back(x); // graf orientat (jos in sus) i -> x
        }
        for (int i = 1; i <= m; i++) {
            int x, y;
            fin >> x >> y;
            pairs_of_nodes.push_back({x, y});
        }

        fin.close();
    }

    int lca(int x, int y) {
        if(x == y) {
            return x;
        }
        queue<int> q;
        unordered_set<int> visited;
        q.push(x);
        q.push(y);
        visited.insert(x);
        visited.insert(y);


        while (!q.empty()) {
            int node = q.front();
            q.pop();

            for (int neigh : adj[node]) {
                if(visited.find(neigh) != visited.end()) {
                    return neigh;
                } else {
                    visited.insert(neigh);
                    q.push(neigh);
                }
            }
        }

        return -1;
    }

    vector<int> get_result() {
        vector<int> lcas;

        for (pair<int, int> p : pairs_of_nodes) {
            lcas.push_back(lca(p.first, p.second));
        }

        return lcas;
    }

    void print_output(const vector<int>& lcas) {
        ofstream fout("lca.out");
        for (int i = 0; i < m; i++) {
            fout << lcas[i] << '\n';
        }
        fout.close();
    }
};

int main() {
    auto* task = new (nothrow) Task(); // hint: cppreference/nothrow
    if (!task) {
        cerr << "new failed: WTF are you doing? Throw your PC!\n";
        return -1;
    }
    task->solve();
    delete task;
    return 0;
}