Advertisement
Fahim_7861

LCA

Feb 20th, 2020
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. typedef int ll;
  4. typedef unsigned long long ull;
  5. typedef pair<ll,ll>pll;
  6. typedef pair<ll,pair<ll,ll>>plll;
  7. #define F first
  8. #define S second
  9. #define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL));
  10. #define pb push_back
  11. #define eb emplace_back
  12. #define vll(v) v.begin(),v.end()
  13. #define all(x) x.rbegin(),x.rend()
  14. #define min3(a, b, c) min(a, min(b, c))
  15. #define max3(a, b, c) max(a, max(b, c))
  16. #define in freopen("input.txt", "r", stdin)
  17. #define out freopen("output.txt", "w", stdout)
  18. #define minheap int,vector<int>,greater<int>
  19.  
  20.  
  21. const int Max = 1e5 + 10;
  22.  
  23.  
  24. vector<ll>adj[Max+10];
  25.  
  26. ll P[Max][30], T[Max], dep[Max],n,m;
  27.  
  28.  
  29.  
  30. void DFS(ll src,ll par,ll lev)
  31. {
  32. dep[src]=lev;
  33.  
  34. T[src]=par;
  35.  
  36. for(auto x : adj[src])
  37. {
  38. if(x!=par)DFS(x,src,lev+1);
  39. }
  40.  
  41. return ;
  42. }
  43.  
  44. void input()
  45. {
  46. cin>>n>>m;
  47.  
  48. ll a,i,b;
  49.  
  50. for(i=0; i<m; i++)
  51. {
  52. cin>>a>>b;
  53.  
  54. adj[a].eb(b);
  55. }
  56.  
  57. return ;
  58. }
  59.  
  60. void initLCA()
  61. {
  62. memset(P,-1,sizeof(P));
  63.  
  64. ll i,j;
  65.  
  66.  
  67. for(i=1; i<=n; i++)
  68. P[i][0]=T[i];
  69.  
  70. for(j=1; 1<<j <n ; j++)
  71. {
  72. for(i=1; i<=n; i++)
  73. {
  74. if(P[i][j-1]!=-1)
  75. P[i][j]=P[P[i][j-1]][j-1];
  76. }
  77. }
  78. }
  79.  
  80. ll query(ll u,ll v)
  81. {
  82. if(dep[u]<dep[v])
  83. swap(u,v);
  84.  
  85. ll log=1,i;
  86.  
  87. while(1)
  88. {
  89. ll next=log+1;
  90.  
  91. if( (1<<next)>dep[u])
  92. break;
  93.  
  94. log++;
  95. }
  96.  
  97. for(i=log; i>=0; i--)
  98. {
  99. if(dep[u]-(1<<i)>=dep[v])
  100. u=P[u][i];
  101. }
  102.  
  103. if(u==v)
  104. return u;
  105.  
  106. for(i=log; i>=0; i--)
  107. {
  108. if(P[u][i]!=-1 && P[u][i]!=P[v][i])
  109. {
  110. u=P[u][i];
  111. v=P[v][i];
  112. }
  113.  
  114. }
  115.  
  116. return T[u];
  117. }
  118.  
  119. int main()
  120. {
  121.  
  122. fastread();
  123.  
  124. ll i,j,p,sum=0,k,t,a,b,c,d,cnt=0,q,u,v;
  125.  
  126. input();
  127.  
  128. DFS(0,0,1);
  129.  
  130. initLCA();
  131.  
  132. cin>>q;
  133.  
  134. while(q--)
  135. {
  136. // cout<<"sdf"<<endl;
  137. cin>>u>>v;
  138.  
  139. cout<<query(u,v)<<endl;
  140. }
  141.  
  142.  
  143.  
  144. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement