Pagini recente » Cod sursa (job #161592) | Cod sursa (job #430055) | Cod sursa (job #1466972) | Cod sursa (job #853418) | Cod sursa (job #3297566)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int NMAX = 1e5 + 1, LOG = 19;
vector<int> adj[NMAX];
int n, q, up[LOG][NMAX], depth[NMAX];
void build()
{
for(int k = 1; k < LOG; k++)
for(int node = 1; node <= n; node++)
up[k][node] = up[k-1][up[k-1][node]];
}
void dfs(int node, int parent)
{
up[0][node] = parent;
depth[node] = depth[parent] + 1;
for(int child : adj[node])
if(child != parent)
dfs(child, node);
}
int lca(int u, int v)
{
if(depth[u] < depth[v])
swap(u, v);
for(int k = LOG - 1; k >= 0; k--)
if(depth[up[k][u]] >= depth[v])
u = up[k][u];
if(u == v)
return u;
for(int k = LOG - 1; k >= 0; k--)
{
if(up[k][u] != up[k][v])
{
u = up[k][u];
v = up[k][v];
}
}
return up[0][u];
}
int main()
{
fin >> n >> q;
for(int i = 2; i <= n; i++)
{
int parent;
fin >> parent;
adj[parent].push_back(i);
}
dfs(1, 0);
build();
while(q--)
{
int u, v;
fin >> u >> v;
fout << lca(u, v) << "\n";
}
fin.close();
fout.close();
return 0;
}