Advertisement
Araf_12

LCA

Apr 14th, 2025
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. const int N = 100005; // Adjust this based on your maximum number of nodes
  7. const int LOG = 24;    // Enough for trees up to 2^24 nodes
  8.  
  9. vector<int> g[N];
  10. int table[N][LOG];
  11. int depth[N];
  12.  
  13. void dfs(int u, int p) {
  14.     table[u][0] = p;
  15.     depth[u] = depth[p] + 1;
  16.    
  17.     for(int i = 1; i < LOG; i++) {
  18.         table[u][i] = table[table[u][i-1]][i-1];
  19.     }
  20.    
  21.     for(int v : g[u]) {
  22.         if(v == p) continue;
  23.         dfs(v, u);
  24.     }
  25. }
  26.  
  27. int find_lca(int u, int v) {
  28.     if(depth[u] > depth[v]) swap(u, v);
  29.     int diff = depth[v] - depth[u];
  30.    
  31.     // Bring v to the same depth as u
  32.     for(int i = 0; i < LOG; i++) {
  33.         if(diff == 0) break;
  34.         if(diff & (1 << i)) {
  35.             v = table[v][i];
  36.             diff -= (1 << i);
  37.         }
  38.     }
  39.    
  40.     if(u == v) return u;
  41.    
  42.     // Now find the LCA
  43.     for(int i = LOG-1; i >= 0; i--) {
  44.         if(table[u][i] != table[v][i]) {
  45.             u = table[u][i];
  46.             v = table[v][i];
  47.         }
  48.     }
  49.    
  50.     return table[u][0];
  51. }
  52.  
  53. int main() {
  54.     // Example usage:
  55.     int n; // number of nodes
  56.     cin >> n;
  57.    
  58.     // Build the tree (n-1 edges)
  59.     for(int i = 0; i < n-1; i++) {
  60.         int u, v;
  61.         cin >> u >> v;
  62.         g[u].push_back(v);
  63.         g[v].push_back(u);
  64.     }
  65.    
  66.     // Initialize
  67.     depth[0] = -1; // Assuming root is 1 and its parent is 0
  68.     dfs(1, 0);     // Start DFS from root (assuming root is 1)
  69.    
  70.     // Query processing
  71.     int q;
  72.     cin >> q;
  73.     while(q--) {
  74.         int u, v;
  75.         cin >> u >> v;
  76.         cout << "LCA of " << u << " and " << v << " is: " << find_lca(u, v) << endl;
  77.     }
  78.    
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement