Cod sursa(job #2672742)

Utilizator maraboneaMara Bonea marabonea Data 14 noiembrie 2020 16:57:25
Problema Lowest Common Ancestor Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
/**
infoarena.ro/problema/lca
Lowest Common Ancestor
*/
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int nmax = 100020;
int n,m;
vector <int> g[nmax];
int a[20][nmax],log2[nmax];
int use[nmax],vt[nmax],nivel[nmax];
void citire()
{
    fin>>n>>m;
    for(int i=2;i<=n;i++)
    {
        fin>>vt[i];
        g[vt[i]].push_back(i);
    }
}
void precalcul()
{
    for(int i=2;i<=n;i++)
        log2[i]=log2[i/2]+1;
    for(int i=1;i<=n;i++)
        a[0][i]=vt[i];
    for(int i=1;(1<<i)<=n;i++)
        for(int j=1;j<=n;j++)
            a[i][j]=a[i-1][a[i-1][j]];
}
void dfs(int nod)
{
    use[nod]=1;
    for(int i=0;i<(int)g[nod].size();i++)
    {
        int vecin = g[nod][i];
        if(!use[vecin])
        {
            nivel[vecin]=nivel[nod]+1;
            dfs(vecin);
        }
    }
}

int ancestor(int x, int y)
{
    if(nivel[x]<nivel[y])
        swap(x,y);
    while(nivel[x]!=nivel[y])
    {
        int k=log2[nivel[y]-nivel[x]];
        x=a[k][x];
    }
    if(x==y)
    {
        return x;
    }
    for(int k=log2[nivel[x]]; k>=0; k--)
    {
        if(a[k][x]!=a[k][y])
        {
            x=a[k][x];
            y=a[k][y];
        }
    }
    return vt[x];

}

void rezolv()
{
    dfs(1);
    while(m--)
    {
        int x,y;
        fin>>x>>y;
        fout<<ancestor(x,y)<<endl;
    }
}
int main()
{
    citire();
    precalcul();
    rezolv();
    return 0;
}