Cod sursa(job #2501593)

Utilizator preda.andreiPreda Andrei preda.andrei Data 29 noiembrie 2019 23:09:53
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>
#include <vector>

struct Node {
    int father = -1;
    int depth = -1;
};

using Tree = std::vector<Node>;

static void dfs(const std::vector<std::vector<int>> &graph,
                int node, int father, Tree &tree) {

    tree[node].father = father;
    tree[node].depth = (father >= 0 ? (tree[father].depth + 1) : 0);

    for (const auto &son : graph[node]) {
        if (son != father) {
            dfs(graph, son, node, tree);
        }
    }
}

static Tree buildTree(const std::vector<std::vector<int>> &graph) {
    Tree tree(graph.size());
    dfs(graph, 0, -1, tree);
    return tree;
}

static int lca(const Tree &tree, int a, int b) {
    while (a != b) {
        if (tree[a].depth > tree[b].depth) {
            a = tree[a].father;
        } else {
            b = tree[b].father;
        }
    }
    return a;
}

std::vector<int> lca(const std::vector<std::vector<int>> &graph,
                     const std::vector<std::pair<int, int>> &queries) {
    auto tree = buildTree(graph);

    std::vector<int> answers;
    for (const auto &q : queries) {
        int a = q.first;
        int b = q.second;
        answers.push_back(lca(tree, a, b));
    }
    return answers;
}

int main()
{
    std::ifstream fin("lca.in");
    std::ofstream fout("lca.out");

    int nodes, tests;
    fin >> nodes >> tests;

    std::vector<std::vector<int>> tree(nodes);
    for (int i = 1; i < nodes; i += 1) {
        int father;
        fin >> father;
        tree[father - 1].push_back(i);
        tree[i].push_back(father - 1);
    }

    std::vector<std::pair<int, int>> queries(tests);
    for (auto &q : queries) {
        fin >> q.first >> q.second;
        q.first -= 1;
        q.second -= 1;
    }

    auto res = lca(tree, queries);
    for (const auto &node : res) {
        fout << node + 1 << "\n";
    }

    return 0;
}