Cod sursa(job #2635212)

Utilizator paul3ioanCirstean Paul Ioan paul3ioan Data 13 iulie 2020 17:45:45
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("lca.in");
ofstream cout("lca.out");
vector <int> L[100001];
int log;
int n,a, q,viz[100001], v[100001][20], nivel[100001];
void dfs(int x)
{
    a++;
    nivel[x] = a;
    viz[x] = 1;
    for(int i = 1 ; i <= log; i ++)
        v[x][i] = v[v[x][i - 1]][i - 1];
    for(int i  : L[x])
        if(!viz[i])
            dfs(i);
    a--;
}
int LCA(int x,int y)
{
    int p = log;
    if(nivel[x] > nivel[y])
        swap(x,y);
    while(nivel[y] > nivel[x])
    {
        if(nivel[y] - (1 << p) >= nivel[x])
            y = v[y][p];
        p--;
    }
    if( x == y)
        return x;;
//    p = log;
    for(int p = log; p >= 0 ; p--)
    {
        if(v[x][p] != v[y][p])
            x = v[x][p], y = v[y][p];
    }
    return v[x][0];
}
int main() {
    cin >> n >> q;
    while((1 << (log + 1)) <=n)
        log++;
    for(int i = 2 ;i <=n ;i ++)
    {
        cin >> v[i][0];
        L[v[i][0]].push_back(i);
        L[i].push_back(v[i][0]);
    }

    dfs(1);
    int x ,y ;
    while(q--)
    {
        cin >> x >> y;
        cout << LCA(x,y) << '\n';
    }
    return 0;
}