Wednesday, 13 April 2016

****E. A and B and Lecture Rooms

E. A and B and Lecture Rooms
A and B are preparing themselves for programming contests.
The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.
Every day А and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them.
As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following m days.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of rooms in the University.
The next n - 1 lines describe the corridors. The i-th of these lines (1 ≤ i ≤ n - 1) contains two integers ai and bi (1 ≤ ai, bi ≤ n), showing that the i-th corridor connects rooms ai and bi.
The next line contains integer m (1 ≤ m ≤ 105) — the number of queries.
Next m lines describe the queries. The j-th of these lines (1 ≤ j ≤ m) contains two integers xj and yj (1 ≤ xj, yj ≤ n) that means that on the j-th day A will write the contest in the room xj, B will write in the room yj.
Output
In the i-th (1 ≤ i ≤ m) line print the number of rooms that are equidistant from the rooms where A and B write contest on the i-th day.
Examples
input
4
1 2
1 3
2 4
1
2 3
output
1
input
4
1 2
2 3
2 4
2
1 2
1 3
output
0
2
Note
in the first sample there is only one room at the same distance from rooms number 2 and 3 — room number 1.

----------------------------------------editorial-------------------------------
In this problem we have to answer to the following queries on tree: for given pairs of vertices your program should output number of eqidistand vertices from them.
Let's denote:
dist(a, b) as distance between vertices a and b.
LCA(a, b) as lowest common ancestor of vertices a and b.
depth[a] as distance between root of the tree and vertex a.
size[a] as size of subtree of vertex a.
On each picture green nodes are equidistant nodes, blue nodes — nodes from query.
Preprocessing: Read edges of tree and build data structure for LCA (it is more convenient to use binary raise, becase we will use it further for other purposes).
Complexity: O(NlogN)
Queries:
We have to consider several cases for each query:
1) a = b. In that case answer is n.
2) dist(a, b) is odd. Then answer is 0.
3) dist(a, l) = dist(b, l), where l = LCA(a, b).
Find children of l, which are ancestors of a and b (let's denote them as aa and bb). Answer will be n - size[aa] - size[bb].
4) All other cases.

  
Assume that depth[a] > depth[b]. Then using binary raise find dist(a, b) / 2-th ancestor of a (let's denote it as p1), dist(a, b) / 2 - 1-th ancestor of vertex a (denote it as p2). Answer will be size[p1] - size[p2].
Complexity: O(logN) for each query, O(MlogN) for all queries.
Resulting complexity:O(MlogN + NlogN

--------------------------------------------code--------------------------------------------------------
// tree is treated as 1 based 
// level is also 1 based 

#include<bits/stdc++.h>
using namespace std;
typedef long long int lli;
list<pair<int,int> >li[100010];
lli dp[100010][30];
int lev[100010];
int dist[100010];
 int countt[100010];
 int all;
int dfs(int start,int par,int le,int di)
{

  lev[start]=le;
  list<pair<int,int > >:: iterator it;
  int ret=1;
  for(it=li[start].begin();it!=li[start].end();it++)
   {
     if(it->first!=par)
      {
        dp[it->first][0]=start;
        lev[it->first]=le+1;
        dist[it->first]=di+it->second;
        ret+=  dfs(it->first,start,le+1,di+it->second);
       }
   }
   countt[start]=ret;
   return ret;
}


int binary_rais(int a,int b)// return lca of a,b
 {
   if(lev[a]<lev[b]) swap(a,b);
   int lg;
   for(lg=1;(1<<lg)<=lev[a];lg++);
   lg--;
     for(int i=lg;i>=0;i--)
      {
        if(lev[a]-(1<<i)>=lev[b])
         {
            a=dp[a][i];//   moving a upward
          }
      }
    
   if(a==b) return a;
   else
   {
    for(int i=lg;i>=0;i--)
    {
     if(dp[a][i]!=-1 && dp[a][i]!=dp[b][i]) 
      {
        a=dp[a][i];
        b=dp[b][i];
      }
    }
    return dp[a][0];
   }
 }

int find(int a,int b,int gap)//  return ans 
 {
    if(lev[a]<lev[b]) swap(a,b);
    
    if(lev[a]==lev[b]) // case 1  if both are at same distance from parent
    {
    int lg;
          for(lg=1;(1<<lg)<=lev[a];lg++);
        lg--;
   
     for(int i=lg;i>=0;i--)
      {
        if(lev[a]-(1<<i)>=lev[b])
         {
            a=dp[a][i];
          }
      }
    for(int i=lg;i>=0;i--)
    {
     if(dp[a][i]!=-1 && dp[a][i]!=dp[b][i])//  moving botha and b up 
      {
        a=dp[a][i];
        b=dp[b][i];
      }
    }
    if(a==b)
     {
      return all-countt[a];
}
else
    return all-countt[a]-countt[b];
}
     
   
   else//   else shift  low till (gap/2)-1   and ans will be 
       //  no of child of par[(gap/2)-1] - no of child of (gap/2)-1
   {
    int shift=(gap/2)-1;
    int lg;
   for(lg=1;(1<<lg)<=lev[a];lg++);
   lg--;
     
    for(int i=lg;i>=0;i--)
     {
      if(shift-(1<<i)>=0)
       {
          shift-=(1<<i);
         a=dp[a][i];
  }
  }
  
  return countt[dp[a][0]]-countt[a];
   }
 }


int main()
{

 int n;
 cin>>n;
 all=n;
  
 for(int i=0;i<n-1;i++)
 {
  int a,b,c;
   cin>>a>>b;
   
   li[a].push_back({b,1});
   li[b].push_back({a,1});
}

 memset(dp,-1,sizeof dp);

 dist[1]=0;
 dp[1][0]=0;
 dfs(1,-1,1,0);

    int max_h=20;
    for(int i=1;i<=max_h;i++)
     {
       for(int j=1;j<=n;j++)
        {
            if(dp[j][i-1]!=-1)
       dp[j][i]=dp[dp[j][i-1]][i-1];
     }
  }
  
  
  int q;
  cin>>q;
  while(q--)
   {
     int a,b;
      cin>>a>>b;
        if(a==b)
{
         cout<<all<<endl;
          continue;
}
          int par= binary_rais(a,b);
        int distance=dist[a]+dist[b]-2*dist[par];
        if(distance%2==1)
         cout<<0<<endl;
         else
         {
          cout<<find(a, b,distance)<<endl;
}
   }
 }


Tuesday, 12 April 2016

***LCA USING BINARY RAIS TREE tutorial

Another easy solution in <O(N logN, O(logN)>
If we need a faster solution for this problem we could use dynamic programming. First, let’s compute a table P[1,N][1,logN] where P[i][j] is the 2j-th ancestor of i. For computing this value we may use the following recursion:
The preprocessing function should look like this:
  void process3(int N, int T[MAXN], int P[MAXN][LOGMAXN])
  {
      int i, j;
   
  //we initialize every element in P with -1
      for (i = 0; i < N; i++)
          for (j = 0; 1 << j < N; j++)
              P[i][j] = -1;
   
  //the first ancestor of every node i is T[i]
      for (i = 0; i < N; i++)
          P[i][0] = T[i];
   
  //bottom up dynamic programing
      for (j = 1; 1 << j < N; j++)
         for (i = 0; i < N; i++)
             if (P[i][j - 1] != -1)
                 P[i][j] = P[P[i][j - 1]][j - 1];
  }
  
This takes O(N logN) time and space. Now let’s see how we can make queries. Let L[i] be the level of node i in the tree. We must observe that if p and q are on the same level in the tree we can compute LCA(p, q) using a meta-binary search. So, for every power j of 2 (between log(L[p]) and 0, in descending order), if P[p][j] != P[q][j] then we know that LCA(p, q) is on a higher level and we will continue searching for LCA(p = P[p][j], q = P[q][j]). At the end, both p and q will have the same father, so return T[p]. Let’s see what happens if L[p] != L[q]. Assume, without loss of generality, that L[p] < L[q]. We can use the same meta-binary search  for finding the ancestor of p situated on the same level with q, and then we can compute the LCA  as described below. Here is how the query function should look:
  int query(int N, int P[MAXN][LOGMAXN], int T[MAXN], 
  int L[MAXN], int p, int q)
  {
      int tmp, log, i;
   
  //if p is situated on a higher level than q then we swap them
      if (L[p] < L[q])
          tmp = p, p = q, q = tmp;
  
  //we compute the value of [log(L[p)]
      for (log = 1; 1 << log <= L[p]; log++);
      log--;
   
  //we find the ancestor of node p situated on the same level
  //with q using the values in P
      for (i = log; i >= 0; i--)
          if (L[p] - (1 << i) >= L[q])
              p = P[p][i];
   
      if (p == q)
          return p;
   
  //we compute LCA(p, q) using the values in P
      for (i = log; i >= 0; i--)
          if (P[p][i] != -1 && P[p][i] != P[q][i])
              p = P[p][i], q = P[q][i];
   
      return T[p];
  }
Now, we can see that this function makes at most 2 * log(H) operations, where H is the height of the tree. In the worst case H = N, so the overall complexity of this algorithm is <O(N logN), O(logN)>. This solution is easy to code too, and it’s faster than the previous one

-----------------------------------CODE----------------------------------------------------------------------
// tree is treated as 1 based 
// level is also 1 based 

#include<bits/stdc++.h>
using namespace std;
typedef long long int lli;
list<int>li[1010];
lli dp[1010][30];
int lev[1010];
int dfs(int start,int par,int le)
{

  lev[start]=le;
  list<int>:: iterator it;
  for(it=li[start].begin();it!=li[start].end();it++)
   {
     if(*it!=par)
      {
        dp[*it][0]=start;
        lev[*it]=le+1;
        dfs(*it,start,le+1);
   }
   }
}


int binary_rais(int a,int b)// return lca of a,b
 {
  
    //  always we conseider that lev a> lev b so swap else
   if(lev[a]<lev[b]) swap(a,b);
   
   int lg;
   
   /// maximum jump that can be alloweable to make both a and 
   // b at same level  will be the depth of the node a 
   for(lg=1;(1<<lg)<=lev[a];lg++);
   
   // 
   lg--;
   
   // this will make both at same level
   //  we can write any number as the power of 2 
   //  so by binary raise we can reach to any node 
     for(int i=lg;i>=0;i--)
      {
        if(lev[a]-(1<<i)>=lev[b])
         {
            a=dp[a][i];//   moving a upward
          }
      }
    
    //  now a and b are at same level 
    
    
      //now we always try to  to shift a and be at a point just below the lca
      //  but if both a and b are in the same line than while shifing leven we reach 
      //  both a and become same 
    
   if(a==b) return a;
   
   else
   {
    for(int i=lg;i>=0;i--)
    {
     if(dp[a][i]!=-1 && dp[a][i]!=dp[b][i])//  moving botha and b up 
      {
        a=dp[a][i];
        b=dp[b][i];
      }
    }
    //  since we atmax shift a and b 
    //  just below there lca 
    //  lca will be the parent of a or parent of b
    
    return dp[a][0];
   }
 }


int main()
{

 int t;
  cin>>t;
  int cas=1;
  while(t--)
  {
    cout<<"Case "<<cas++<<":"<<endl;
    for(int i=0;i<1010;i++)li[i].clear();
 int n;
 cin>>n;
 int m ;
  cin>>m;// edge 
  
 for(int i=1;i<=m;i++)
 {
   int a,b;
    cin>>a>>b;
    li[a].push_back(b);
    li[b].push_back(a);
}

 memset(dp,-1,sizeof dp);
 // we are consedering 1 as the root of all nodes 
 // so its parent is non so its pow(2,0) the parent is 0;

 dp[1][0]=0;
 dfs(1,-1,1);

    int max_h=20;//  or lon(n)
    //  maximum height 
    for(int i=1;i<=max_h;i++)
     {
       for(int j=1;j<=n;j++)
        {
            if(dp[j][i-1]!=-1)
       dp[j][i]=dp[dp[j][i-1]][i-1];//
     }
  }
  
  int q;
  cin>>q;
  while(q--)
   {
     int a,b;
      cin>>a>>b;
      cout<< binary_rais(a,b)<<endl;
   }
 }

}