Cod sursa(job #2923334)

Utilizator tescovschimarioTescovschi Mario tescovschimario Data 12 septembrie 2022 20:27:49
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
using namespace std;
ifstream cin ("stramosi.in");
ofstream cout ("stramosi.out");
int dp[100002][20], n, parent[1000002], LOG, m, x, y, depth[1000002];

void bl(){
    for(int i = 1; i <= n; i++){
        dp[i][0] = parent[i];
        for(int j = 1; j < LOG; j++)
            dp[i][j] = dp[ dp[i][j-1] ][j-1];
    }
}

void yes(int x, int y){
    if(depth[x] < depth[y]) swap(x,y);

    int k = depth[x] - depth [y];
    for(int j = LOG - 1; j >= 0; j--)
        if(k & (1 << j))
            x = dp[x][j];

    if(x == y)
    {cout << y << '\n'; return;}


    for(int j = LOG - 1; j >= 0; j--)
        if( dp[x][j] != dp[y][j]){
            x = dp[x][j];
            y = dp[y][j];
        }
    cout << dp[x][0] << '\n';
}

int main() {

    cin >> n >> m;
    for(int i = 2; i <= n; i++){
        cin >> parent[i];
        depth[i] = depth[parent[i]] + 1;}
    parent[1] = 1;
    while ((1 << LOG) <= n) LOG++;
    bl();

    for(int i = 1; i <= m; i++){
        cin >> x >> y;
        yes(x, y);
    }

}