Cod sursa(job #1922538)

Utilizator hasmasandragosHasmasan Dragos hasmasandragos Data 10 martie 2017 17:49:28
Problema Lowest Common Ancestor Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 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];
       }

       if (x!=y && stramosi[0][x]!=stramosi[0][y])
       {
          for (k=logmax-1;k>=0;k--)
          {
              if (stramosi[k][x] && stramosi[k][y] && stramosi[k][x]!=stramosi[k][y] && x!=y)
              {
                  x=stramosi[k][x];
                  y=stramosi[k][y];
              }
          }

          if (x!=y)
           g<<stramosi[0][x]<<'\n';
          else g<<x<<'\n';
       }

       else
       {
         if (x!=y)
           g<<stramosi[0][x]<<'\n';
          else g<<x<<'\n';
       }
    }

    return 0;
}