Cod sursa(job #735472)

Utilizator visanrVisan Radu visanr Data 16 aprilie 2012 15:38:57
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
using namespace std;


void firstupdate(long start);
void secondupdate(long start);
long search();
void LCA();


vector<long> father;
vector<long> way;
long n,t,x,y;



int main()
{
    freopen("lca.in","r",stdin);
    freopen("lca.out","w",stdout);
   // int i;
    LCA();
   // scanf("%i", &i);
    return 0;
}



void LCA()
{
     scanf("%ld %ld", &n,&t);
     father.reserve(n+1);
     way.reserve(n+1);
     father[1]=0;
     for(int i=0;i<n-1;i++)
     {
                       scanf("%ld", &x);
                       father[i+2]=x;
     }
     for(;t>=0;t--)
     {
                     for(int i=1;i<=n;i++) way[i]=0;
                     scanf("%ld %ld", &x,&y);
                     firstupdate(x);
                    // printf("\n");
                     secondupdate(y);
                     printf("%ld\n", search());
                   //  int i;
                   //  scanf("%i", &i);
     }
}

void firstupdate(long x)
{
     if(x==1) way[x]++;
     else
     {
         way[x]++;
        // printf("%ld ", father[x]);
         firstupdate(father[x]);
     }
}

void secondupdate(long x)
{
     if(x==1) way[x]+=2;
     else
     {
         way[x]+=2;
          //printf("%ld ", father[x]);
         secondupdate(father[x]);
     }
}

long search()
{
     for(long i=n;i;i--) if(way[i]==3) return i;
}