Wednesday, 30 September 2015

**Monk and Otakuland

         Monk and Otakuland

Problem

Monk lives in Otakuland. Otakuland consists of N vertices and N-1 directed edges. i-th edge is a directed edge either from i-th vertex to i+1-th vertex or from i+1-th vertex to i-th vertex. You are given M Queries. Queries are 2 types:
  1. 1 l r - Reverse the direction of the edges between l-th vertex and r-th vertex.
  2. 2 f t - Output the minimum number of edges which you have to reverse the direction to arrive from f to t.

Input:

The first line contains two integers N, the number of vertices and M, the number of queries. The next line will containsN-1 characters which represent the direction of the edges. i-th character is either '>' or '<': '>' represents that only i -> i+1is valid, '<' represents that only i+1 -> i is valid. The following M lines will each contain a query like the ones mentioned above.

Output:

For query 2, print the answer in a new line.

Constraints:

2 ≤ N ≤ 200000
1 ≤ M ≤ 200000
1 ≤ l < r ≤ N
1 ≤ f , t ≤ N

Sample Input
(Plaintext Link)
6 6
>><<>
2 1 6
2 6 1
1 3 5
2 1 6
1 1 6
2 6 1
Sample Output
(Plaintext Link)
2
3
0
0
Explanation
In the sample testcase the graph is like this, 1->2->3<-4<-5->6. At the first query, Monk have to reverse the direction of 3rd edge and 4th edges to arrive from 1st vertex to 6th vertex. Second, Monk have to reverse the direction of 1st, 2nd, and 5th edges to arrive from 6th vertex to 1st vertex. Third, Reverse the direction of the edges between 3rd vertex and 5th vertex. After the query, graph is like this, 1->2->3->4->5->6. Fourth, Monk don't have to reverse the direction of any edge. Fifth, Reverse the direction of the edges between 1st vertex and 6th vertex. After the query, graph is like this, 1<-2<-3<-4<-5<-6. Sixth, Monk don't have to reverse the direction of any edge.

------------------------------------------editorial-------------------------------------------------------------------------------------------------------------
Reach-ability of t from f
All the edges between f to t must be in the direction from f towards *t.
Lets say f<t, then all the edges must be towards the right. The edges we need to reverse are those edges that are in the opposite direction from t towards *f
.
Thus the answer to any query is the count of edges that are in direction from t towards f. Without loss of generality assume f<t. The answer would be the number of edges in the left direction.
Thus to solve this problem we need to maintain the direction of each edge and efficiently count the number of edges facing left in any queried range.
The two tasks can be done easily using segment tree with lazy propagation ( as there are range updates and range queries). Any node of segment tree can store the number of edges in the left direction in its responsibility range. We can deal with updates lazily.
The case when f>t can be similarly answered. Just count the number of edges facing right =( total edges in between fand t) - (total edges facing left in the same range).
Thus there is O(log N) per update and O(log N) per query making it O(N + Q * log N) final time complexity.


-------------------------------------------------------------------------code----------------------------------------------------------------------------------
#include<iostream>
using namespace std;
int arr[6010000];
#define inf 999999999
struct st
 {
  int     zero;
  int one;
 } 
 tree[6000000];
 
 int lazy[6000000];
int  ans=0;
  int read_int(){
char r;
bool start=false,neg=false;
int ret=0;
while(true){
r=getchar();
if((r-'0'<0 || r-'0'>9) && r!='-' && !start){
continue;
}
if((r-'0'<0 || r-'0'>9) && r!='-' && start){
break;
}
if(start)ret*=10;
start=true;
if(r=='-')neg=true;
else ret+=r-'0';
}
if(!neg)
return ret;
else
return -ret;
}
int query(int node,int start,int end,int r1,int r2,int  tt)
 {
  //   cout<<start<<" "<<end<<endl;
  //  cout<<" r1 "<<r1<<" r2 "<<r2<<endl;
 
  
   if(lazy[node])
   {
       if(lazy[node]%2==1)
       {
        int temp=tree[node].zero;
         tree[node].zero=tree[node].one;
         tree[node].one=temp;
            lazy[2*node]+=lazy[node];
             lazy[2*node+1]+=lazy[node];
     
  }
  lazy[node]=0;
         
   }
   if(start>end || r1>end || r2<start || r1>r2) return 0;
   if(r1<=start && r2>=end)
    {
    // cout<<"here "<<node<<endl;
    if(tt==1)
    {
    // cout<<" returning       "<<tree[node].zero<<endl;
    ans+=tree[node].zero;
    return tree[node].zero;
     
}
    
     else
     {//
      // cout<<"  returning       "<<tree[node].one<<endl;
      ans+=tree[node].one;
      return tree[node].one;
       
     
}
     
     
    }
    else
    {
     int q1=query(2*node,start,(start+end)/2,r1,r2,tt);
     int q2=query(2*node+1,((start+end)/2)+1,end,r1,r2,tt);
 
     return (q1+q2);
    }
 }
 
 
void update(int node ,int start,int end,int r1,int r2,int val)
 {
 
 // cout<<" update in the range "<<start<<" "<<end<<endl;

  
  if(lazy[node]!=0)
   {
    // cout<<" lazy node "<<node<<endl;
   
     int times=lazy[node];
    // cout<<" lazy node "<<node<<" times "<<times<<endl;
     times%=2;
     
     if(times==1)
     {
      int temp=tree[node].zero;
      tree[node].zero=tree[node].one;
      tree[node].one=temp;
       
     // cout<<" making lazing "<<2*node<<" "<<2*node+1<<endl;
         lazy[2*node+1]+=1;
         lazy[2*node]+=1;
          
}
 
    lazy[node]=0;
    
   }
   
   
    if(r1>end  || r2<start   || start>end) return  ;
  if(r1<=start && r2>=end)
   {
   
     int temp=tree[node].zero;
      tree[node].zero=tree[node].one;
      tree[node].one=temp;
     if(start!=end)
      {
     
       lazy[2*node]+=1;
       lazy[2*node+1]+=1;
      //  cout<<" making lazing "<<2*node<<" "<<2*node+1<<endl;
      }
      return  ;
   }
   
    update(2*node, start,(start+end)/2,r1,r2,val);
    update(2*node+1, ((start+end)/2)+1,end,r1,r2,val);
    // cout<<" finalizing node "<<node<<endl;
     tree[node].zero=tree[2*node].zero+tree[2*node+1].zero;
    tree[node].one=tree[2*node].one+tree[2*node+1].one;
   
 }
 
 
void build(int node , int start,int end)
 {
 
  if(start==end)
  {
  if(arr[start]==1)
  {
  tree[node].zero=0;
  tree[node].one=1;
  }
  else
  {
  tree[node].zero=1;
  tree[node].one=0;
  }
  // cout<<"  at nod"<<node<<"  zero          "<<tree[node].zero<<" one      "<<tree[node].one<<endl;
   }
  else if(start>end) return ;
  else
   {
    build(2*node,start,(start+end)/2);
    build(2*node+1,((start+end)/2)+1,end);
    tree[node].zero=tree[2*node].zero+tree[2*node+1].zero;
    tree[node].one=tree[2*node].one+tree[2*node+1].one;
  
   }
   
 }
 
 
int main()
 {
  
   int n,q;
   // cin>>n>>q;
   n=read_int();
   q=read_int();
    
    char ae[10000+n];
    cin>>ae;
     for(int i=0;i<n-1;i++)
     {
     
     
       
       if(ae[i]=='>')arr[i]=1;
       else   arr[i]=0;
     
}

 
      for(int i=0;i<2*n+100;i++)
       {
        tree[i].zero=0;
        tree[i].one=0;
  }
  
       build(1,0,n-2);
 
       
    
        while(q--)
         {
          ans=0;
            int typ,l,r;
          // cin>>typ>>l>>r;
           typ=read_int();
            l=read_int();
             r=read_int();
             if(typ==2)
             {
              int res;
              if(l<=r)
              res=query(1,0,n-2,l-1,r-2,1);
              else
              {
             
              res=query(1,0,n-2,r-1,l-2,0);
               
}
              cout<<ans<<endl;
               
}
else
{
int val=0;
    update(1,0,n-2,l-1,r-2,val);
}
              
              
             
         }
       
  return 0;
 }

Tuesday, 15 September 2015

****Tywins Tactics Solved

Tywins Tactics 
Solved


Tywin Lannister is a tactical genius. At the heart of his tactical skills, is the way he has organized his armies, and the way he is able to estimate his soldiers' skill-levels, thus helping him make crucial decisions as to whom to dispatch to which areas of the war.
His army is organized in the form of a hierarchy - indeed it is a tree, with him as the root. We say "A has immediate superior B" if A reports directly to B. We further say "A has superior B" if there is a chain of soldiers starting with A, ending with B, and where each soldier reports directly to the next soldier of the chain. Further, each soldier is assigned an initial skill-level based on prior experience and battle proficiency.
In order for Tywin to decide whom to send to which battle, he has the following scheme: He chooses a particular soldier S as the leader of his temporary 'regiment', and sends in to battle, S as well as all the soldiers that have S as one of their superiors. He estimates the skill level of the regiment as the total skill level of all the soldiers under S (denoted by query "Q S").
After a battle, he may want to update the skill levels of some soldiers. If he wants to update the skill level of soldier S to value x, it is denoted by the query "U S x".
You are given the structure of the army, whose size is N, the initial skill levels of all the individual soldiers, as well the number of queries M. For each query of the type "Q S", report the sum of skill-levels of all the soldiers who have S as their superior.
Note: The soldiers are numbered 1 to N, and Tywin is given the number 1.

Input

The first line consists of the integers N and M, denoting the number of soldiers and the number of queries.
This is followed by a single line consisting of N nonnegative values - the skill levels of the N soldiers.
This is then followed by N-1 lines consisting of pairs of integers (u, v), denoting that either u is an immediate superior of v, or vice-versa.
Finally you are given the M queries, of either the form "U S x" or "Q S".

Output

For each "Q S" query, output the sum of skill values of all the soldiers under S.

Constraints

  • 1 ≤ N ≤ 105
  • 1 ≤ M ≤ 105
  • All skill values given with be in the range [020,000]
  • 1 ≤ S ≤ N for all queries
  • All soldiers will have soldier 1 (Tywin) as their superior

Example

Input:
5 8
7 2 0 5 8
1 2
2 3
2 4
1 5
Q 1
Q 2
U 2 4
Q 1
Q 2
U 5 3
Q 1
Q 2

Output:
22
7
24
9
19
9


*******************************************EDITORIAL****************************************************************

Pre-requisites:

dfs, range sum queries

Problem:

You are given a rooted tree T, associate with each vertex v a weight skill[v]. Also given are a set of queries of either the form "update skill of v to x", or "what is the sum of skill values of vertices in the subtree of v". For each query of the second form, return the answer.

Quick Explanation:

Map the given vertex numbers to [1...N] such that the subtree rooted at any vertex has all mapped values in a contiguous range. Then updates of the first form imply changing skill-values at the given mapped number, and queries of the second form are simply range sum queries in the appropriate range, that can be answered using either a segment tree or a binary indexed tree.
The mapping of vertices that satisfy the given property can be done using dfs numbers (in-times/out-times). For details, see the Explanation section which draws an analogy to a bracketed expression.
Overall time complexity: O(N) - finding out the mapping and the required range for each node O(M logN) - to carry out each query: either point update, or range sum query.

Detailed Explanation:

For an illustration, let us consider the following tree: 1 / \ 2 5 / \ 3 6 \ 4
From the above, I can form a bracketed expression of the form: (x1 + (x2) + (x5 + (x3 + (x4)) + (x6))) Whenever I go down the tree, I am opening a bracket, whenever I go up the tree, I am closing a bracket. I am also giving "variables" that will correspond to skill-values for each node.
Seeing the above, I can rewrite 1,2,3,4,5 by mapping them to values as seen from left to right: 1 -> 1 2 -> 2 5 -> 3 3 -> 4 4 -> 5 6 -> 6
Now, in the mapped version, the bracketed expression looks like: (y1 + (y2) + (y3 + (y4 + (y5)) + (y6)))
We are here interested in queries of two types: Type1: change value of x[i], or in other words, y[mapped(i)] Type2: Find the total in the complete bracket "defined" by i, which is y[mapped(i)] + y[mapped(i)+1] + ... + y[end_range(i)], for suitable mapped(i) and end_range(i).
The good thing to note is, type2 is now a query over values in a range. This can be done by a segment tree or a binary indexed tree! We only need what the range is, given each vertex.
Finding out the range, as well as the mapping, can be done easily by dfs-times. The dfs-time for a node is the value of a time-counter when that node was visited. Indeed, if you ran a dfs on the given tree, it will visit the nodes in the order "1-2-5-3-4-6" itself! The range is then just starting from the current point, and ending at the latest time a node was visited. This information can be returned in the dfs function, as in the following pseudocode: int dfs(node v, int time) mapping[v] = time ret = time for(c is a child of v) ret = dfs(c, ret+1) //give it the next "time"-point, and get the latest time point of the child for future begin_range[v] = time end_range[v] = ret return ret
Calling the above with dfs(1, 1) will do all the magic for you!
Finally, a BIT pseudocode implementation of the rest of the problem:
void update(int S, int x)
    BIT.increment(mapping[S], x - skill[S])
    skill[S] = x;

int query(int S)
    return BIT.query(end_range[S]) - BIT.query(begin_range[S]-1)

Alternate Approach:

This approach was used by some contestants. It is summarized as follows:
Step 1: Perform a heavy-light decomposition of the tree. Step 2: Initialize each node with the value that is the sum of the skill-levels of its subtree. Step 3: For each "U S x" query, add "skill[S]-x" to the nodes along the path from S to the root. Due to Heavy-light decomposition structure, this can be done in O(logN ^ 2) time. Also update the value of skill[S]. Step 4: For each "Q S" query, return the value stored in the node S.
********************************************CODE***********************************************************************
#include<iostream>
using namespace std;
typedef long long int lli;
#include<bits/stdc++.h>
list<lli> li[1000000];
lli gen[1000000];
vector<pair<lli,lli> > v;
lli end=0;
lli arr[1000000+10];
lli visited[10000000];
lli start=0;
lli indx=0;
lli t[10000000];
 
 
void build(lli node, lli a, lli b)
     {
  if(a>b) return;
if (a==b)
{
t[node]=gen[a];
return;
}
build(node*2, a, (a+b)/2);
build(node*2+1,(a+b)/2+1,b);
  t[node]=t[node*2]+t[node*2+1];
   }
lli  query(lli node, lli a, lli b, lli i, lli j)
{
if(a>b||a>j||b<i) return 0;
if (a>=i && b<=j) return t[node];
lli q1=query(node*2, a, (a+b)/2, i, j);
lli q2=query(node*2+1, (a+b)/2+1, b, i, j);
return q1+q2;
}
void update(lli node, lli a, lli b, lli i, lli j,  lli inc)
{
if(a>b) return;
if(a>b||a>j||b<i) return;
if (a>=i && b<=j)
{
t[node]=inc;
return;
}
update(node*2, a, (a+b)/2, i, j, inc);
update(node*2+1, (a+b)/2+1, b,i, j, inc);
t[node] = t[node*2] + t[node*2+1];
}
/* ARRAY GENERATION PART *//////////
void dfs(lli node)
{
 end++;
 start++;
  
     gen[indx]=arr[node];
     
//   cout<<" seting gen[indx] "<< gen[indx]<<endl;
     indx++;
     v[node].first=start;
list<lli>:: iterator it;
for(it=li[node].begin();it!=li[node].end();it++)
{
// cout<<" trying "<<*it<<endl;
if(!visited[*it])
{
//cout<<" get "<<*it<<endl;
visited[*it]=1;
dfs(*it);
  }
 }
//   cout<<"finalizing "<<node<<" with start  and end time "<<start<<" "<<end<<endl;
// v[node].first=start;
 v[node].second=end;
 
}
int main()
 {
   
   
  lli n,m;
  cin>>n>>m;
  for(lli i=1;i<=n;i++)
   {
    cin>>arr[i];
  }
  
  v.push_back(make_pair(0,0));
  for(lli i=1;i<n;i++)
   {
    v.push_back(make_pair(0,0));
    lli a,b;
     cin>>a>>b;
     li[a].push_back(b);
     li[b].push_back(a);
}
v.push_back(make_pair(0,0));
//cout<<" dfs call "<<endl;
visited[1]=1;
dfs(1);
build(1,0,n-1);
// for(lli i=0;i<n;i++)cout<<gen[i]<<endl;
for(lli i=1;i<=m;i++)
{
 
char c;
 cin>>c;
 if(c=='Q')
  {
  lli node ;
  cin>>node;
  // cout<<" query for  node "<<node<<" range "<<v[node].first<<" "<<v[node].second<<endl;
  lli ans=query(1,0,n-1,v[node].first-1,v[node].second-1);
   cout<<ans<<endl;
  }
  else
  {
  lli a,b;
   cin>>a>>b;
   update(1,0,n-1,v[a].first-1,v[a].first-1,b);
  }
 
}
  return 0;
 }