Cod sursa(job #3005590)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 17 martie 2023 09:16:28
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
/// Preset de infoarena
#include <fstream>
#include <vector>

using namespace std;

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

const int maxN = 100005;
int n, q, depth[maxN];
int s[20][maxN];
vector <int> G[maxN];

void dfs(int nod, int d)
{
    depth[nod] = d;
    for(int j = 1; j < 20; j++)
        s[j][nod] = s[j - 1][s[j - 1][nod]];
    for(int fiu : G[nod])
        dfs(fiu, d + 1);
}

int main()
{
    fin >> n >> q;
    for(int i = 2; i <= n; i++)
    {
        fin >> s[0][i];
        G[s[0][i]].push_back(i);
    }
    dfs(1, 0);
    while(q--)
    {
        int x, y;
        fin >> x >> y;
        if(depth[x] < depth[y])
            swap(x, y);
        int diff = depth[x] - depth[y];
        for(int i = 0; i < 20; i++)
            if(diff & (1 << i))
                x = s[i][x];
        if(x == y)
        {
            fout << x << '\n';
            continue;
        }
        for(int i = 18; i >= 0; i--)
        {
            if(s[i][x] != s[i][y])
            {
                x = s[i][x];
                y = s[i][y];
            }
        }
        fout << s[0][x] << '\n';
    }
    return 0;
}