Advertisement
_Tucha

Least Common Ancestor (LCA) Example

Nov 21st, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. /*
  2.  * Coded with love :3
  3.  */
  4. #include <bits/stdc++.h>
  5.  
  6. typedef long long int ll;
  7. typedef unsigned long long int ull;
  8.  
  9. #define pb push_back
  10. #define fr first
  11. #define sc second
  12. #define th third
  13. #define all(a) a.begin(), a.end()
  14. #define newline cout << "\n";
  15. #define scan(a) for(int i=0; i < (int)(sizeof(a) / sizeof(a[0])) ; i++) cin >> a[i];
  16. #define print(a) for(int i=0; i < (int)(sizeof(a) / sizeof(a[0])) ; i++) cout << a[i] << " ";
  17. #define tie() ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
  18.  
  19. using namespace std;
  20.  
  21. const int N   = 1000*100*2+1000;
  22. const int INF = 1000*1000*1000+1000;
  23. const int mod = 1000*1000*1000+7;
  24.  
  25. using namespace std;
  26.  
  27. int logN = 1;
  28. vector < vector <int> > g, up;
  29. vector <int> tin, tout;
  30.  
  31. int t = 1;
  32.  
  33. void dfs(int v, int p) {
  34.     tin[v] = t++;
  35.     up[v][0] = p;
  36.    
  37.     for(int i=1; i <= logN; i++)
  38.         up[v][i] = up[ up[v][i-1] ][i-1];
  39.        
  40.     for(auto to : g[v]) {
  41.         if(to != p)
  42.             dfs(to, v);
  43.     }
  44.    
  45.     tout[v] = t++;
  46. }
  47.  
  48. bool parent(int a, int b) {
  49.     return tin[a] <= tin[b] && tout[a] >= tout[b];
  50. }
  51.  
  52. int lca(int a, int b) {
  53.     if(parent(a, b)) return a;
  54.     if(parent(b, a)) return b;
  55.    
  56.     for(int i=logN; i >= 0; i--) {
  57.         if(!parent(up[a][i], b))
  58.             a = up[a][i];
  59.     }
  60.    
  61.     return up[a][0];
  62. }
  63.  
  64. int main() {
  65.     tie();
  66.    
  67.     // Vertexes, edges
  68.     int n, m;
  69.     cin >> n >> m;
  70.    
  71.     tin.assign(n, 0);
  72.     tout.assign(n, 0);
  73.     up.resize(n);
  74.     g.resize(n);
  75.    
  76.     for(int i=0; i < m; i++) {
  77.         int a, b;
  78.         cin >> a >> b;
  79.         a--; b--;
  80.         g[a].pb(b);
  81.     }
  82.    
  83.     while((1<<logN) <= n)
  84.         { logN++; }
  85.    
  86.     for(int i=0; i < n; i++)
  87.         { up[i].resize(logN + 1); }
  88.        
  89.     dfs(0, 0);
  90.    
  91.     int q;
  92.     cin >> q;
  93.    
  94.     for(int i=0; i < q; i++) {
  95.         int a, b;
  96.         cin >> a >> b;
  97.         a--; b--;
  98.         cout << lca(a, b)+1 << "\n";
  99.     }
  100.    
  101.     return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement