Pagini recente » Cod sursa (job #1538805) | Cod sursa (job #844363) | Monitorul de evaluare | Cod sursa (job #1659346) | Cod sursa (job #2770752)
#include <bits/stdc++.h>
using namespace std;
int n, logn = 19;
vector <int> g[100005];
int p[20][100005];
int h[100005];
int BuildSparseTable (int nod, int par)
{
h[nod] = h[par] + 1;
p[0][nod] = par;
for (int i = 1; i <= logn; i++)
{
p[i][nod] = p[i-1][p[i-1][nod]];
}
for(int i : g[nod])
{
if(h[i] == 0)
{
BuildSparseTable (i, nod);
}
}
}
int LCA (int x, int y)
{
if(h[x] < h[y]) swap(x, y);
for (int i = logn; i >= 0; i--)
{
if( h[p[i][x]] >= h[y]) x = p[i][x];
}
if(x == y) return x;
for (int i = logn; i >= 0; i--)
{
if( p[i][x] != p[i][y]) x = p[i][x], y = p[i][y];
}
return p[0][x];
}
int main()
{
freopen("lca.in", "r", stdin);
freopen("lca.out", "w", stdout);
cin >> n;
int x, y;
for(int i = 1; i < n; i++)
{
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
BuildSparseTable(1, 0);
while(1)
{
cin >> x >> y;
cout << LCA(x, y) << '\n';
}
}