Pagini recente » Cod sursa (job #2451574) | Cod sursa (job #325849) | Cod sursa (job #1500033) | Istoria paginii runda/cel_mai_mare_olimpicar_2019_oni2009_zi1/clasament | Cod sursa (job #1283399)
//Deresu Roberto - FMI
//Re :)
#include<fstream>
#include<vector>
#define nx 100007
using namespace std;
int n,m,x,y,father;
struct lca
{
int father;
int height;
}a[nx];
vector<int>v[nx];
ifstream fin("lca.in");
ofstream fout("lca.out");
void dfs(int node, int height)
{
a[node].height = height;
for(int i=0;i<v[node].size();i++)
dfs(v[node][i], height+1);
}
int lca(int x,int y)
{
while(a[x].height > a[y].height) x = a[x].father;
while(a[y].height > a[x].height) y = a[y].father;
while(x != y)
{
x = a[x].father;
y = a[y].father;
}
return x;
}
int main()
{
fin>>n>>m;
for(int i=2;i<=n;i++)
{
fin>>father;
a[i].father = father;
v[father].push_back(i);
}
dfs(1,1);
for(int i=1;i<=m;i++)
{
fin>>x>>y;
fout<<lca(x,y)<<"\n";
}
return 0;
}