Advertisement
istinishat

LCA

Jul 18th, 2017
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. LCA code from PrinceOfparsia's blog :Codeforces
  3. http://codeforces.com/blog/entry/16221
  4. */
  5. #include<bits/stdc++.h>
  6. using namespace std;
  7.  
  8. #define si(n) scanf("%d",&n)
  9. #define MAX 100005
  10. #define MAXLOG 20
  11.  
  12. int par[MAX][MAXLOG];
  13. int h[MAX];
  14. vector<int>graph[MAX];
  15.  
  16. void dfs(int now,int from=-1){
  17.     par[now][0]=from;
  18.     if(from+1){
  19.         h[now]=h[from]+1;
  20.     }
  21.     for(int i=1;i<MAXLOG;i++){
  22.         if(par[now][i-1]+1){
  23.             par[now][i]=par[par[now][i-1]][i-1];
  24.         }
  25.     }
  26.     for(auto to : graph[now]){
  27.         if(to != from){
  28.             dfs(to,now);
  29.         }
  30.     }
  31. }
  32.  
  33. //find jth parrent of x
  34. int parent(int x,int j){
  35.     for (int i=0; i<MAXLOG; i++)
  36.          if (j&(1<<i)) x=par[x][i];
  37.     return x;
  38. }
  39.  
  40. int LCA(int v,int u){
  41.     if(h[v]<h[u])
  42.         swap(v,u);
  43.     for(int i=MAXLOG-1;i>=0;i--){
  44.         if(par[v][i]+1 && h[par[v][i]]>=h[u]){
  45.             v=par[v][i];
  46.         }
  47.     }
  48.     //now h[u]=h[v]
  49.     if(u==v)
  50.         return v;
  51.     for(int i=MAXLOG-1;i>=0;i--){
  52.         if(par[v][i]-par[u][i]){
  53.             v=par[v][i];
  54.             u=par[u][i];
  55.         }
  56.     }
  57.     return par[v][0];
  58. }
  59.  
  60. //number of edges of path x->y
  61. int dist(int x,int y)
  62. {
  63.     return h[x]+h[y]-2*h[LCA(x,y)];
  64. }
  65. //number of common edges of two paths
  66. // a->c & b->c
  67. int common_edges(int a,int b,int c)
  68. {
  69.     return (dist(a,c)+dist(b,c)-dist(a,b))/2;
  70. }
  71.  
  72. int main()
  73. {
  74.     //freopen("input.txt","r",stdin);
  75.     int n,m,q,i,j;
  76.     si(n);si(q);
  77.     for(i=1;i<=n-1;i++){
  78.         int u,v;
  79.         si(u);si(v);
  80.         graph[u].push_back(v);
  81.         graph[v].push_back(u);
  82.     }
  83.     memset(par,-1,sizeof(par));
  84.     dfs(1);
  85.     while(q--){
  86.         int u,v,a;
  87.         si(u);si(v);
  88.         int ans=LCA(u,v);
  89.         cout<<ans<<endl;
  90.     }
  91.     return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement