Cod sursa(job #3180780)

Utilizator rar3srares ioan rar3s Data 5 decembrie 2023 22:34:37
Problema Lowest Common Ancestor Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <unordered_map>

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

int getLCA(unordered_map<int, vector<int>> const &tree, int root, int const p, int const q)
{
    if (root == 0 || root == p || root == q)
        return root;

    vector<int> res;
    auto it = tree.find(root);
    if (it != tree.end())
    {
        for (auto const &child : it->second)
        {
            int l = getLCA(tree, child, p, q);
            if (l != 0)
                res.push_back(l);
        }
    }

    // cout << "root: " << root << '\n';
    // for (auto const &el : res)
    //     cout << el << ' ';

    // cout << '\n';

    if (res.size() == 2)
        return root;

    if (res.size() == 1)
        return res[0];

    return 0;
}

int main()
{
    int n, m;
    fin >> n >> m;

    unordered_map<int, vector<int>> tree;

    for (int child = 2; child <= n; child++)
    {
        int parent;
        fin >> parent;
        tree[parent].push_back(child);
    }

    for (int node = 1; node <= n; node++)
        if (tree.find(node) == tree.end())
            tree[node].push_back(0);

    for (int i = 0; i < m; i++)
    {
        int p, q;
        fin >> p >> q;
        fout << getLCA(tree, 1, p, q) << '\n';
    }

    // cout << getLCA(tree, 1, 6, 5);

    // for (auto const &[node, children] : tree)
    // {
    //     cout << node << ": {";
    //     for (auto ch : children)
    //     {
    //         cout << ch << ", ";
    //     }
    //     cout << "}\n";
    // }

    fin.close();
    fout.close();

    return 0;
}