Cod sursa(job #2672513)

Utilizator mlupseLupse-Turpan Mircea mlupse Data 14 noiembrie 2020 10:03:44
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <fstream>
#include <cstdio>
#include <vector>
using namespace std;
ofstream fout("lca.out");
const int NMax = 100000;
const int Size = 8192;
int N,M;
vector <int> G[NMax + 5];
int Use[NMax + 5],TT[NMax + 5],Level[NMax + 5];
char Buffer[Size + 5];
int Pos;

inline void ReadValue(int &Value)
{
	Value=0;
	while(Buffer[Pos]<'0' || Buffer[Pos]>'9')
		if(++Pos == Size)
        {
            fread(Buffer, 1, Size, stdin);
            Pos=0;
        }
	while(Buffer[Pos]>='0' && Buffer[Pos]<='9')
	{
		Value = Value*10 + Buffer[Pos] - '0';
		if(++Pos == Size)
        {
            fread(Buffer, 1, Size, stdin);
            Pos=0;
        }
	}
}


void Read()
{
    freopen("lca.in","r",stdin);
    //fin >> N >> M;
    ReadValue(N); ReadValue(M);
    for(int i = 2; i <= N; ++i)
    {
        //fin >> TT[i];
        ReadValue(TT[i]);
        G[TT[i]].push_back(i);
    }
}
void DFS(int Nod)
{
    Use[Nod] = 1;
    for(int i = 0; i < (int)G[Nod].size(); ++i)
    {
        int Vecin = G[Nod][i];
        if(!Use[Vecin])
            {
                Level[Vecin] = Level[Nod] + 1;
                DFS(Vecin);
            }
    }
}
void SolveandPrint()
{
    DFS(1);
    while(M--)
    {
        int x,y;
        //fin >> x >> y;
        ReadValue(x); ReadValue(y);
        if(Level[x]<Level[y])
            swap(x,y);
        while(Level[x] != Level[y])
            x = TT[x];
        while(x != y)
        {
            x = TT[x];
            y = TT[y];
        }
        fout << x << "\n";

    }
}
int main()
{
    Read();
    SolveandPrint();
    return 0;
}