Cod sursa(job #2770752)

Utilizator helloworld0107Iordachi Bianca helloworld0107 Data 22 august 2021 23:11:57
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#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';
  }
}