Cod sursa(job #2386309)

Utilizator Johnny07Savu Ioan-Daniel Johnny07 Data 22 martie 2019 15:21:01
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");

int n,m, rmq[17][100001],depth[100001],log[100001];

bool check (int node1, int node2, int dst)
{
    int aux=0;
    while (dst)
    {
        if (dst%2==1)
        {
            node1=rmq[aux][node1];
            node2=rmq[aux][node2];
        }
        aux++;
        dst/=2;
    }
    if (node1==node2) return 1;
    return 0;
}


void caut (int node1, int node2 )
{
int st, dr,mid;
st=1;
dr=depth[node1];
while (st<=dr)
{
    mid=st+dr;
    mid/=2;
    if ( check (node1, node2, mid)==1 ) dr=mid-1;
    else st=mid+1;
}
mid=st + dr ;
if (check(node1, node2, mid-1)==1) mid--;
if (check (node1, node2, mid)==0) mid++;
int aux=0;
//cout<<node1<<" "<<node2<<" "<<mid<<"\n";
while (mid)
{
    if (mid%2==1)
    {
        node1=rmq[aux][node1];
    }
    aux++;
    mid/=2;
}
g<<node1<<"\n";
}


int main()
{
int i,j;
f>>n>>m;
//log[2]=1;
for (i=2;i<=n;i++)
{
  log[i]=log[i/2]+1;
    f>>rmq[0][i];
    depth[i]=depth[rmq[0][i]]+1;
}

int aux;
for (i=2;i<=n;i++)
{
    for (j= 1; j < depth[i] ; j*=2)
    {
        aux= rmq[j-1][i];
        rmq[j][i]=rmq[j-1][aux];
    }
}
int node1, node2;
int aux1, aux2;
int z;

//cout<<check(8, 9, 1);

for (i=1;i<=m;i++)
{
    f>>node1>>node2;
    if (node1==1 || node2==1) g<<1<<"\n";
    else
    {
       // cout<<node1<<" "<<node2<<" : ";
        if (depth[node1]<depth[node2])
        {
            node2+=node1;
            node1=node2-node1;
            node1-=node2;
        }
        while (depth[node1]!=depth[node2])
        {
            node1=rmq[log[depth[node1]-depth[node2]]][node1];
        }
        caut(node1, node2);
       // cout<<node1<<" "<<node2<<"\n";

    }


}

//cout<<sizeof(short int );
//short int x;
//upper_bound(short int);
    return 0;
}