Cod sursa(job #3144796)

Utilizator Traian_7109Traian Mihai Danciu Traian_7109 Data 10 august 2023 18:23:46
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
#include <bits/stdc++.h>

using namespace std;

const int LOGMAX = 21, NMAX = 1e5;
int ancestor[LOGMAX + 5][NMAX + 5], depth[NMAX + 5];
vector<vector<int>> g;

class Query {
    private:
        int u, v;
        
        void reset() {
            
        }
        
        void read() {
            cin >> u >> v;
        }
        
        void solve() {
            if (depth[u] < depth[v])
                swap(u, v);
            int lg = __lg(depth[u]);
            for (int i = lg; i >= 0; i--)
                if (depth[u] - (1 << i) >= depth[v])
                    u = ancestor[i][u];
            if (u == v) {
                cout << u << '\n';
                return;
            }
            for (int i = lg; i >= 0; i--)
                if (ancestor[i][u] != -1 && ancestor[i][u] != ancestor[i][v])
                    u = ancestor[i][u], v = ancestor[i][v];
            cout << ancestor[0][u] << '\n';
        }
    
    public:
        Query() {
            reset(), read(), solve();
        }
};

int main() {
    #ifndef TEST 
        freopen("lca.in", "r", stdin);
        freopen("lca.out", "w", stdout);
    #endif 
    ios_base :: sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    
    for (int i = 1; i <= LOGMAX; i++)
        for (int j = 1; j <= NMAX; j++)
            ancestor[i][j] = -1;
    int t = 1, n;
    cin >> n >> t;
    ancestor[0][1] = depth[1] = 1;
    for (int i = 2; i <= n; i++)
        cin >> ancestor[0][i], depth[i] = depth[ancestor[0][i]] + 1;
    for (int i = 1; (1 << i) <= n; i++)
        for (int j = 1; j <= n; j++)
            ancestor[i][j] = ancestor[i - 1][ancestor[i - 1][j]];
    while (t--)
        Query query;
    return 0;
}