Cod sursa(job #3267302)

Utilizator TimurealTimu Ionut Timureal Data 11 ianuarie 2025 10:47:56
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.01 kb
#include <bits/stdc++.h>
#define ll long long
#define nl '\n';
using namespace std;
class InParser{
private:
    int sp;
    FILE *fin;
    char *buff;
    char rc(){
        if(++sp==4096){
            fread(buff , 1 , 4096 , fin);
            sp=0;
        }
        return buff[sp];
    }
public:
    InParser(const char *nume){
        fin=fopen(nume , "r");
        sp=4095;
        buff=new char[4096]();
    }
    InParser& operator>>(int &n){
        char c;
        int sgn=1;
        while(!isdigit(c=rc()) && c!='-');
        if(c=='-'){
            sgn=-1;n=0;
        }
        else{
            n=c-'0';
        }
        while(isdigit(c=rc())){
            n=n*10+c-'0';
        }
        n*=sgn;
        return *this;
    }
    InParser& operator>>(ll &n){
        char c;
        ll sgn=1;
        while(!isdigit(c=rc()) && c!='-');
        if(c=='-'){
            sgn=-1;n=0;
        }
        else{
            n=c-'0';
        }
        while(isdigit(c=rc())){
            n=n*10+c-'0';
        }
        n*=sgn;
        return *this;
    }
};
InParser fin("data.in");
ofstream fout("data.out");
const int NMAX=10000+10;

int t[100010];
int adancime[100010];
vector<vector<int>> adj;
void bfs(int start){
    queue<int> q;
    q.push(start);
    adancime[start]=0;
    while(q.size()){
        int nod=q.front(); q.pop();
        for(int i : adj[nod]){
            if(i!=t[nod]){
                adancime[i]=adancime[nod]+1;
                q.push(i);
            }
        }
    }
}

int lca(int a,int b){
    while(a!=b){
        if(adancime[a]<adancime[b]){
            b=t[b];
        }
        else{
            a=t[a];
        }
    }
    return a;
}

int main()
{
    int n , op;
    fin>>n>>op;
    adj.resize(n+1);
    for(int i=2 ;i<=n; i++)
    {
        fin>>t[i];
        adj[t[i]].push_back(i);
    }
    bfs(1);
    while(op--){
        int a , b ;
        fin>>a>>b;
        fout<<lca(a , b)<<nl;
    }
    return 0;
}