orazma

lca.cpp

Apr 4th, 2026
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.24 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define f first
  4. #define s second
  5. using ll = long long;
  6. const int MOD = 998244353;
  7. const int MAXN = 1e6 + 10;
  8.  
  9. bool upper(int a, int b){
  10.     return (tin[a] <= tin[b] && tout[a] >= tout[b]);
  11. }
  12. int timer = 0;
  13.  
  14. void dfs(int v, int pr = 0){
  15.     was[v] = 1;
  16.     tin[v] = ++timer;
  17.     up[v][0] = pr;
  18.     for (int i = 1; i <= l; i++){
  19.         up[v][i] = up[up[v][i - 1]][i - 1];
  20.     }
  21.     for (int to : g[v]){
  22.         if (!was[to]){
  23.             dfs(to, v);
  24.         }
  25.     }
  26.  
  27.     tout[v] = ++timer;
  28. }
  29.  
  30. int lca(int a, int b){
  31.     if (upper(a, b)){
  32.         return a;
  33.     }
  34.     if (upper(b, a)){
  35.         return b;
  36.     }
  37.     for (int i = l; i >= 0; i--){
  38.         if (!upper(up[a][i], b)){
  39.             a = up[a][i];
  40.         }
  41.     }
  42.     return up[a][0];
  43. }
  44.  
  45. void solve() {
  46.  
  47.     cin >> n;
  48.     int x = n;
  49.     while (x){
  50.         l++;
  51.         x >>= 1;
  52.     }
  53.     tout[0] = INF;
  54.     for (int i = 1; i < n; i++){
  55.         cin >> u >> v;
  56.         g[u].pb(v);
  57.         g[v].pb(u);
  58.     }
  59.  
  60.  
  61. }
  62.  
  63. int main(){
  64.     std::ios::sync_with_stdio(false);
  65.     std::cin.tie(nullptr); std::cout.tie(nullptr);
  66.     int t = 1;
  67.     //cin >> t;
  68.     while (t--) {
  69.         solve();
  70.     }
  71. }
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
Advertisement
Add Comment
Please, Sign In to add comment