Cod sursa(job #2247746)

Utilizator preda.andreiPreda Andrei preda.andrei Data 29 septembrie 2018 00:03:13
Problema Lowest Common Ancestor Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include <fstream>
#include <vector>

using namespace std;

struct Node
{
    int time = 0;
    vector<int> ancestors;
    vector<int> sons;
};

using Tree = vector<Node>;

void Dfs(Tree &t, int node)
{
    if (!t[node].ancestors.empty()) {
        auto anc = t[node].ancestors[0];
        auto ind = 0;

        while (ind < (int)t[anc].ancestors.size()) {
            t[node].ancestors.push_back(t[anc].ancestors[ind]);
            anc = t[node].ancestors.back();
            ind += 1;
        }
    }

    for (const auto &next : t[node].sons) {
        Dfs(t, next);
    }

    static auto time = 0;
    t[node].time = (time += 1);
}

int HighestAncestor(const Tree &t, int node, int max_time)
{
    auto index = -1;
    auto power = (1 << 16);

    while (power > 0) {
        auto next_index = index + power;
        power >>= 1;

        if (next_index < (int)t[node].ancestors.size()) {
            auto anc = t[node].ancestors[next_index];
            if (t[anc].time <= max_time) {
                index = next_index;
            }
        }
    }

    index = max(index, 0);
    return t[node].ancestors[index];
}

int FindLca(const Tree &t, int a, int b)
{
    if (t[a].time > t[b].time) {
        swap(a, b);
    }

    while (a > 0 && t[a].time < t[b].time) {
        a = HighestAncestor(t, a, t[b].time);
    }
    return a;
}

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

    int nodes, queries;
    fin >> nodes >> queries;

    Tree tree(nodes);
    for (int i = 1; i < nodes; i += 1) {
        int father;
        fin >> father;
        tree[i].ancestors.push_back(father - 1);
        tree[father - 1].sons.push_back(i);
    }

    Dfs(tree, 0);

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

        auto lca = FindLca(tree, a - 1, b - 1);
        fout << lca + 1 << "\n";
    }

    return 0;
}