Cod sursa(job #3374937)

Utilizator EricDimiCismaru Eric-Dimitrie EricDimi Data 9 noiembrie 2026 19:44:26
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.18 kb
/// Algoritmul lui Tarjan
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;

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

const int MAX_N = 100000;
const int MAX_Q = 2000000;

struct Query
{
    int node, idx;
};

struct DisjointSetUnion
{
    int parent[MAX_N + 1], rank[MAX_N + 1];
    int n;

    void Init(int n)
    {
        this->n = n;
        for(int i = 1; i <= n; i++)
            parent[i] = rank[i] = 0;
    }

    int Find(int node)
    {
        int root = node;

        while(parent[root] != 0)
            root = parent[root];

        while(node != root)
        {
            int aux = parent[node];
            parent[node] = root;
            node = aux;
        }

        return root;
    }

    void Union(int node1, int node2)
    {
        node1 = Find(node1);
        node2 = Find(node2);

        if(node1 == node2)
            return;

        if(rank[node1] < rank[node2])
            parent[node1] = node2;
        else
        {
            parent[node2] = node1;
            if(rank[node1] == rank[node2])
                rank[node1]++;
        }
    }
};

vector<int> adj[MAX_N + 1]; int n;
bitset<MAX_N + 1> vis;
int ancestor[MAX_N + 1];

vector<Query> queries[MAX_N + 1];
DisjointSetUnion dsu;
int res[MAX_Q + 1]; int q;

void Read()
{
    fin >> n >> q;
    for(int x = 2; x <= n; x++)
    {
        int y;
        fin >> y;
        adj[y].push_back(x);
    }
    for(int i = 1; i <= q; i++)
    {
        int u, v;
        fin >> u >> v;
        queries[u].push_back({v, i});
        queries[v].push_back({u, i});
    }
}

void DFS(int u = 1)
{
    vis[u] = true;
    ancestor[u] = u;
    for(int v : adj[u])
        if(!vis[v])
        {
            DFS(v);
            dsu.Union(u, v);
            ancestor[dsu.Find(u)] = u;
        }
    for(const auto& [v, idx] : queries[u])
        if(vis[v])
            res[idx] = ancestor[dsu.Find(v)];
}

void Print()
{
    for(int i = 1; i <= q; i++)
        fout << res[i] << '\n';
}

int main()
{
    Read();
    DFS();
    Print();

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

    return 0;
}