Pagini recente » Cod sursa (job #1227238) | Cod sursa (job #12531) | Cod sursa (job #1766416) | Cod sursa (job #732184) | Cod sursa (job #3309145)
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int tata[100005], h[100005], tot_fii[100005], lant[100005], capat_lant[100005], lant_curent;
vector <int> fii[100005];
void dfs1( int x ){
int i, y;
for( i = 0; i < fii[x].size(); i++ ){
y = fii[x][i];
h[y] = h[x] + 1;
dfs1( y );
tot_fii[x] += tot_fii[y];
}
tot_fii[x]++;
}
void dfs2( int x ){
int i, y, max_fii, r;
max_fii = r = -1;
for( i = 0; i < fii[x].size(); i++ ){
y = fii[x][i];
if( tot_fii[y] > max_fii ){
max_fii = tot_fii[y];
r = y;
}
}
if( r != -1 ){
lant[r] = lant_curent;
dfs2( r );
for( i = 0; i < fii[x].size(); i++ ){
y = fii[x][i];
if( y != r ){
lant_curent++;
capat_lant[lant_curent] = y;
lant[y] = lant_curent;
dfs2( y );
}
}
}
}
int main(){
int n, m, i, x, y;
ifstream fin( "lca.in" );
ofstream fout( "lca.out" );
fin >> n >> m;
for( i = 2; i <= n; i++ ){
fin >> tata[i];
fii[tata[i]].push_back( i );
}
tata[1] = 1;
dfs1( 1 );
lant_curent = 0;
capat_lant[0] = 1;
lant[1] = 0;
dfs2( 1 );
for( i = 0; i < m; i++ ){
fin >> x >> y;
//cout << x << ' ' << y << '\n';
while( lant[x] != lant[y] ){
if( h[tata[capat_lant[lant[x]]]] > h[tata[capat_lant[lant[y]]]] ){
x = tata[capat_lant[lant[x]]];
}
else{
y = tata[capat_lant[lant[y]]];
}
//cout << x << ' ' << y << '\n';
}
if( h[x] < h[y] ){
fout << x << '\n';
}
else{
fout << y << '\n';
}
//cout << '\n';
}
return 0;
}