Cod sursa(job #2447506)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 13 august 2019 15:18:29
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 100005;

int val[MAXN], nivel[MAXN], pos[MAXN], lant[MAXN], sub[MAXN], anc[MAXN];
vector<int> graf[MAXN], hpd[MAXN];
int lanturi;

void HPDInit(int nod, int tata){
    nivel[nod] = nivel[tata] + 1;
    sub[nod] = 1;
    for(auto x:graf[nod]){
        HPDInit(x, nod);
        sub[nod] += sub[x];
    }
    if(sub[nod] == 1){
        lanturi++;
        hpd[lanturi].push_back(nod);
        lant[nod] = lanturi;
        return;
    }
    int best = 0;
    for(auto x:graf[nod])
        if(sub[x] > sub[best]) best = x;
    lant[nod] = lant[best];
    hpd[lant[nod]].push_back(nod);
    pos[nod] = (int)hpd[lant[nod]].size() - 1;
}

int solve(int x, int y){
    if(lant[x] == lant[y]){
        if(nivel[x] < nivel[y]) return x;
        else return y;
    }
    else{
        if(nivel[hpd[lant[x]][0]] > nivel[hpd[lant[y]][0]]) solve(anc[hpd[lant[x]][0]], y);
        else solve(x, anc[hpd[lant[y]][0]]);
    }
}

int main()
{
    ifstream fin("lca.in");
    ofstream fout("lca.out");
    int n, m;
    fin >> n >> m;
    for(int i = 2; i <= n; ++i){
        fin >> anc[i];
        graf[anc[i]].push_back(i);
    }
    HPDInit(1, 0);
    for(int i = 1; i <= lanturi; ++i)
        reverse(hpd[i].begin(), hpd[i].end());
    for(int i = 1; i <= n; ++i)
        pos[i] = (int)hpd[lant[i]].size() - 1 - pos[i];
    while(m){
        int x, y;
        fin >> x >> y;
        fout << solve(x, y) << "\n";
        m--;
    }
    return 0;
}