Cod sursa(job #1920869)

Utilizator hasmasandragosHasmasan Dragos hasmasandragos Data 10 martie 2017 10:30:09
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("lca.in");
ofstream g("lca.out");

const int logmax=20;
const int nmax=100005;

int n,m,stramosi[logmax][nmax]; /// stramosi[k][i] = al k-lea stramos al nodului i
int nivel[nmax];
vector <int> a[nmax]; /// arborele

void dfs (int node , int level)
{
    int vecini,h;
    nivel[node]=level;
    vecini=a[node].size();

    for (h=0;h<vecini;h++)
        dfs(a[node][h],level+1);
}

int main()
{
    int i,k;
    f>>n>>m; /// nodes , queries

    for (i=2;i<=n;i++)
    {
        f>>stramosi[0][i];
        a[stramosi[0][i]].push_back(i);
    }

    dfs(1,0);

    for (k=1;(1<<k)<=n;k++)
        for (i=1;i<=n;i++)
         stramosi[k][i]=stramosi[k-1][stramosi[k-1][i]];

    int x,y,diferenta;
    while (m--)
    {
       f>>x>>y;

       if (nivel[x]<nivel[y])
         swap(x,y);
       diferenta=nivel[x]-nivel[y];

       for (k=0;(1<<k)<=diferenta;k++)
       {
           if ((1<<k) & diferenta)
            x=stramosi[k][x];
       }

       k=0;
       while (x!=y)
       {
           if (stramosi[k][x]!=0)
           {
               x=stramosi[k][x];
               y=stramosi[k][y];
           }
       }

       g<<x<<'\n';

    }

    return 0;
}