Cod sursa(job #2171454)

Utilizator RazvanGutaGuta Razvan Alexandru RazvanGuta Data 15 martie 2018 12:25:36
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include<bits/stdc++.h>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
int n,m,s[100001],v1[100001],v2[100001],x,y,j,i,parc;
int main()
{
    f>>n>>m;
    s[1]=0;
    for(i=2;i<=n;i++)
    {
        f>>x;
        s[i]=x;
    }
    for(i=1;i<=m;i++)
    {
        f>>x>>y;
        v1[x]=1;
        int ok=0;
        v2[y]=1;
        while(s[x]!=0&&s[y]!=0)
          {
              x=s[x];
              v1[x]=1;
              y=s[y];
              v2[y]=1;
              if(x==y)
              {
                  g<<x<<'\n';
                  ok=1;
                  break;
              }
          }
     if(ok==0)
     {
      for(j=n;j>=1;j--)
        if(v1[j]==1&&v2[j]==1)
      {
          g<<j<<'\n';
          break;
      }
     }
       for(j=n;j>=1;j--)
            v1[j]=v2[j]=0;
    }
    return 0;
}