Pagini recente » Cod sursa (job #1286807) | Cod sursa (job #1534398) | Cod sursa (job #1432187) | Cod sursa (job #2446884) | Cod sursa (job #3241585)
#include <fstream>
#include <vector>
using namespace std;
ifstream cin ("lca.in");
ofstream cout ("lca.out");
const int Nmax = 1e5 + 5;
int depth[Nmax], head[Nmax], heavy[Nmax], parent[Nmax], lin[Nmax];
vector<int> g[Nmax];
int dfs(int nod)
{
int weight = 1, maxweight = 0;
for(auto it : fii[nod])
{
depth[it] = depth[nod] + 1;
int nweight = dfs(it);
weight += nweight;
if(nweight > maxweight)
maxweight = nweight, heavy[nod] = it;
}
return weight;
}
void dfs2(int nod)
{
// cout << nod << endl;
if(nod == 1)
{
head[1] = 1;
}
for(auto it : fii[nod])
{
if(it != heavy[nod])
{
head[it] = it;
dfs2(it);
}
}
if(heavy[nod] == 0)
return;
head[heavy[nod]] = head[nod];
dfs2(heavy[nod]);
}
int solve(int a, int b)
{
while(1)
{
//cout << a << " " << b << " " << head[a] << " " << head[b] << '\n';
if(head[a] == head[b])
return (depth[a] < depth[b] ? a : b);
if(depth[head[a]] > depth[head[b]])
a = parent[head[a]];
else
b = parent[head[b]];
}
}
int main()
{
int n, m, a, b;
cin >> n >> m;
for(int i = 2; i <= n; i ++)
{
cin >> parent[i];
if(i != parent[i])
fii[parent[i]].push_back(i);
}
dfs(1);
dfs2(1);
while(m --)
{
cin >> a >> b;
cout << solve(a, b) << '\n';
}
return 0;
}