Cod sursa(job #2468688)

Utilizator Senth30Denis-Florin Cringanu Senth30 Data 5 octombrie 2019 19:53:30
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.56 kb
#include <bits/stdc++.h>
#define MAX 131072

using namespace std;
const int NMAX = 100010;

FILE *IN, *OUT;

int N, M, ans;
bool seen[NMAX];
int depth[NMAX], dp[17][NMAX];
vector <int> Gph[NMAX];

int pos, sign, out;
char f[MAX], Out[MAX], str[10];

inline void Read(int &nr){
    sign = 0;
    nr = 0;
    while(f[pos] < '0' || f[pos] > '9'){
        if(f[pos] == '-') sign = 1;
        pos++;
        if(pos == MAX)
            fread(f, MAX, 1, IN), pos = 0;
    }
    while(f[pos] >= '0' && f[pos] <= '9'){
        nr = 10 * nr + f[pos++] - '0';
        if(pos == MAX)
            fread(f, MAX, 1, IN), pos = 0;
    }
    if(sign) nr =- nr;
}

inline void Write_Ch(char ch){
    Out[out++] = ch;
    if(out == MAX)
        fwrite(Out, MAX, 1, OUT), out = 0;
}

inline void Write_Int(int nr){
    int x = 0;
    if(nr < 0) Write_Ch('-'), nr = -nr;
    do{
        str[x++] = nr % 10 + '0';
        nr /= 10;
    } while(nr);
    while(x > 0)
        Write_Ch(str[--x]);
}

void read(){
    int x;
    Read(N); Read(M);
    dp[0][1] = 1;
    depth[1] = 1;
    for(int i = 1; i < N; i++){
        Read(dp[0][i + 1]);
        Gph[dp[0][i + 1]].push_back(i + 1);
        //Write_Int(dp[0][i + 1]); Write_Ch(' '); Write_Int(i + 1); Write_Ch('\n');
    }
}

void DFS(int node, int val){
    depth[node] = val;
    for(int i = 0; i < Gph[node].size(); i++){
        int x = Gph[node][i];
        DFS(x, val + 1);
    }
}

int main(){

    IN = fopen("lca.in", "r");
    OUT = fopen("lca.out", "w");

    read();
    DFS(1, 1);

    for(int i = 1; (1 << i) <= N; i++)
        for(int j = 1; j <= N; j++)
            dp[i][j] = dp[i - 1][dp[i - 1][j]];

    int A, B, vmax, Q, p;
    for(int i = 1; i <= M; i++){
        Read(A); Read(B); p = 0;
        if(A == B){
            Write_Int(A); Write_Ch('\n');
            continue;
        }
        if(depth[A] > depth[B]){
            vmax = depth[A] - depth[B];
            while(vmax != 0){
                if(vmax % 2) A = dp[p][A];
                vmax /= 2; p++;
            }
        } else {
            vmax = depth[B] - depth[A];
            while(vmax != 0){
                if(vmax % 2) B = dp[p][B];
                vmax /= 2; p++;
            }
        }

        p = 4;
        while(A != B && p >= 0){
            if(dp[p][A] != dp[p][B])
                A = dp[p][A], B = dp[p][B];
            else ans = dp[p][A];
            p--;
        }
        Write_Int(ans); Write_Ch('\n');
    }

    if(out > 0) fwrite(Out, 1, out, OUT);

    return 0;
}