Cod sursa(job #2116640)

Utilizator Garen456Paun Tudor Garen456 Data 27 ianuarie 2018 20:09:56
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.19 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int t,n,m,x,y,niv,ct,cap;
vector <int> V[100005];
bool viz[100005],v2[100005],v3[100005];
int h[100005],rez;
int l[200005][21];
int e[200005][21];
struct pr
{ int a,b,c;
};
pr G[100005];
void DFS(int x)
{ ++ct;
   e[ct][0]=x;
   if(h[x]==0)
    h[x]=ct;
    l[ct][0]=niv;

   vector<int>::iterator it;
   for(it=V[x].begin();it!=V[x].end();++it)
       if(!viz[x])
          {  ++niv; DFS(*it);   --niv; ++ct; e[ct][0]=x; l[ct][0]=niv;    }

}


inline bool srt(pr x1,pr x2)
{

        return l[0][ h[ x1.a]] >l[0][h [x2.a] ];


}


int main()
{   //fin>>t;
   t=1;
    int i,j,z,sol;
    while(t--)
    { fin>>n>>m; ct=0; niv=0; cap=0; rez=0;
         for(i=0;i<=20;++i)
            for(j=1;j<=200004;++j)
             e[i][j]=l[i][j]=0;
         for(i=1;i<=100000;++i)
         {V[i].erase(V[i].begin(),V[i].end());   v2[i]=v3[i]=0;  h[i]=0; viz[i]=0;}

        for(i=1;i<n;++i)
      { fin>>x;
        V[x].push_back(i+1);
    }
       // { fin>>x>>y;
         //   V[x].push_back(y);
       //     V[y].push_back(x);
      //  }
        DFS(1);

     for(j=1;(1<<j)<=ct;++j)
    for(i=1;i+(1<<j)-1<=ct;++i)
        if( l[i][j-1]<l[i+(1<<(j-1))][j-1] )
  { l[i][j]=l[i][j-1];
     e[i][j]=e[i][j-1];
  }
  else { l[i][j]=l[i+(1<<(j-1))][j-1];
        e[i][j]=e[i+(1<<(j-1))][j-1];
  }


    for(i=1;i<=m;++i)
  { fin>>x>>y;
      x=h[x]; y=h[y];
      if(x>y) swap(x,y);
      z=log2(y-x+1);
      if(l[x][z] <l[y-(1<<z)+1][z])
         sol=e[x][z];
      else sol=e[y-(1<<z)+1][z];
        fout<<sol<<"\n";
     // fout<<l[x][z]<<" "<<e[x][z]<<"\n";
     // fout<<l[y-z+1][z]<<" "<<e[y-z+1][z]<<"\n";
  }
  sort(G+1,G+cap+1,srt);

    for(i=1;i<=cap;++i)
      if(!v3[G[i].a] )
      if( G[i].b==G[i].c)
      { v2[G[i].b]=v2[G[i].c]=v2[G[i].a]=1;
          ++rez;
          v3[G[i].a]=1;
      }
     else if( !v2[G[i].c]  &&  !v2[G[i].b])
        { v2[G[i].b]=v2[G[i].c]=v2[G[i].a]=1;
          ++rez;
          v3[G[i].a]=1;
      }
      else
       v2[G[i].b]=v2[G[i].c]=1;




   // fout<<rez<<"\n";


    }
    return 0;
}