Cod sursa(job #2116552)

Utilizator stefzahZaharia Stefan Tudor stefzah Data 27 ianuarie 2018 18:48:11
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
#define Max 100001
vector <int> G[Max];
int T[17][Max], LEV[Max],N,p,mx;
bool viz[Max];
void df(int n, int t[], int l){
    int i,l1,q[mx+1];
    viz[n]=1;
    vector <int> :: iterator it;
    for(i=1;i<=mx;i++)
       q[i]=T[i][n]=t[i];
    LEV[n] = l;
    l1=l;
    i=1;
    while(l1 % 2 == 0)
        {q[i]=n;
         mx=max(mx,i);
         i++;
         if(i==17)break;
         l1/=2;
        }
    for(it = G[n].begin(); it != G[n].end();it++)
        if(!viz[*it]){q[0]=T[0][*it]=n;
                      df(*it,q,l+1);
                     }
}
int lca(int x, int y){int i;
    for(i=mx ;i>=1; i--)
    while(T[i][x] != T[i][y])
        {//g<<i<<" "<<T[i][x]<<" "<<T[i][y]<<"\n";
         if(LEV[x] > LEV[y])
            x = T[i][x];
        else
            y = T[i][y];
        }
       while(x != y)
        if(LEV[x] > LEV[y])
            x = T[0][x];
        else
            y = T[0][y];
    return x;
}

int main()
{
    int m, i,j, x, y,t[1];
    f >> N>> m;
    for(i = 2; i <= N; i++){
        f>>x;
        G[x].push_back(i);
    }
    T[0][1]=1;
    t[0]=1;
    mx=1;
    df(1,t,1);
   /* for(i=1;i<=N;i++)
        {for(j=0;j<17;j++)
           g<<T[j][i]<<" ";
         g<<"\n";
        }
    */
    for(i = 1; i <= m; i++){
        f >> x >> y; p=lca(x,y);
        g <<p <<'\n';
    }

    return 0;
}