Pagini recente » Cod sursa (job #789688) | Cod sursa (job #640217) | Cod sursa (job #1615382) | Cod sursa (job #106555) | Cod sursa (job #1184901)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
const int Nmax = 100000 + 2;
vector <int> G[Nmax];
int depth[Nmax];
int tata[Nmax];
int N, M;
void DFS( int nod, int d )
{
depth[nod] = d;
for ( auto x: G[nod] )
{
if ( tata[x] == 0 )
{
tata[x] = nod;
DFS( x, d + 1 );
}
}
}
int lca( int x, int y )
{
while ( x != y )
{
if ( depth[x] > depth[y] )
x = tata[x];
else
y = tata[y];
}
return x;
}
int main()
{
ifstream f("lca.in");
ofstream g("lca.out");
f >> N >> M;
for ( int i = 2, a; i <= N; ++i )
{
f >> a;
G[a].push_back( i );
}
DFS( 1, 0 );
for ( int i = 1, a, b; i <= M; ++i )
{
f >> a >> b;
g << lca( a, b ) << "\n";
}
return 0;
}