Cod sursa(job #3226427)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 21 aprilie 2024 13:31:32
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.31 kb
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#pragma GCC optimize ("O1")
#pragma GCC optimize ("O2")
#pragma GCC optimize ("O3")
#pragma GCC optimize ("Ofast")
#pragma GCC optimize ("unroll-loops")
#pragma GCC target ("avx2")

using namespace std;
using namespace __gnu_pbds;

#define ordered_set tree <long long, null_type, less<long long>, rb_tree_tag, tree_order_statistics_node_update>
#define lsb(x)(x & (-x))

const int max_size = 1e5 + 20, rmax = 20;

int lg[max_size], t[rmax][max_size], lvl[max_size];
vector <int> mc[max_size];

void dfs (int nod)
{
    for (auto f : mc[nod])
    {
        lvl[f] = lvl[nod] + 1;
        t[0][f] = nod;
        dfs(f);
    }
}

int anc (int x, int y)
{
    for (int e = 0; e < 20; e++)
    {
        if ((y & (1 << e)) != 0)
        {
            x = t[e][x];
        }
    }
    return x;
}

int lca (int x, int y)
{
    int e = lg[lvl[x]];
    while (e >= 0)
    {
        if (t[e][x] != t[e][y])
        {
            x = t[e][x];
            y = t[e][y];
        }
        e--;
    }
    return t[0][x];
}

void solve ()
{
    int n, q;
    cin >> n >> q;
    for (int i = 2; i <= n; i++)
    {
        int x;
        cin >> x;
        mc[x].push_back(i);
    }
    lvl[1] = 1;
    dfs(1);
    for (int e = 1; e < rmax; e++)
    {
        for (int i = 1; i <= n; i++)
        {
            t[e][i] = t[e - 1][t[e - 1][i]];
        }
    }
    for (int i = 2; i <= n; i++)
    {
        lg[i] = lg[i / 2] + 1;
    }
    while (q--)
    {
        int x, y;
        cin >> x >> y;
        if (lvl[x] > lvl[y])
        {
            swap(x, y);
        }
        y = anc(y, lvl[y] - lvl[x]);
        if (x == y)
        {
            cout << x << '\n';
        }
        else
        {
            cout << lca(x, y) << '\n';
        }
    }
    cout << '\n';
}

signed main ()
{
#ifdef LOCAL
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#else
    freopen("lca.in", "r", stdin);
    freopen("lca.out", "w", stdout);
#endif // LOCAL
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    long long tt;
    //cin >> tt;
    tt = 1;
    while (tt--)
    {
        solve();
    }
    return 0;
}