Cod sursa(job #987701)

Utilizator classiusCobuz Andrei classius Data 21 august 2013 13:05:05
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <queue>
#include <cmath>
using namespace std;

ifstream f("lca.in");
ofstream g("lca.out");


int main()
{
    int n,m;

    f>>n>>m;
    vector<int> v[100001];
    int T[100001];

    for(int i=1;i<n;i++){
        int x;
        f>>x;
        v[x].push_back(i+1);
        T[i+1]=x;
    }

    int h=0;
    int L[100001]={};

    queue<int> q;
    q.push(1);

    while(!q.empty()){
        int x=q.front();
        q.pop();
        for(unsigned j=0;j<v[x].size();j++){
            L[v[x][j]]=L[x]+1;
            q.push(v[x][j]);
        }
        if(L[x]>h)
            h=L[x];
    }

    int hd=(int)sqrt(double(h));

    int P[100001]={};
    q.push(1);
    P[1]=1;

    int lv=0;

    while(!q.empty()){
        int x=q.front();
        q.pop();
        for(unsigned j=0;j<v[x].size();j++){
            if(L[v[x][j]]==lv+hd)
                P[v[x][j]]=x;
            else
                P[v[x][j]]=P[x];
            q.push(v[x][j]);
        }
        if(L[x]==lv+hd-1&&L[q.front()]==lv+hd)
            lv+=hd;
    }

    for(int i=1;i<=m;i++){
        int x,y;
        f>>x>>y;

        while(P[x]!=P[y]){
            if(L[x]>L[y])
                x=P[x];
            else
                y=P[y];
        }

        while(x!=y){
            if(L[x]>L[y])
                x=T[x];
            else
                y=T[y];
        }
        g<<x<<'\n';
    }


    return 0;
}