Tuesday, 27 December 2016

Lexicographic paths (string rank algo)

Krishnakant is standing at  in the Cartesian plane. He wants to go to the point  in the same plane using only horizontal and vertical moves of  unit. There are many ways of doing this, and he is writing down all such ways. Each way comprises of few  moves and few  moves. i.e. moves in horizontal and vertical direction respectively. For example, if Krishnakant wants to go to point  from point  is one of the possible ways.
Given the value of , he wants to know lexicographically  smallest way of going to  from .
Input Format 
The first line contains an integer  , i.e., number of test cases. 
Next  lines will contain integers , and .
Output Format 
For each test case, print lexicographically  smallest path.
Constraints 
 
 
 
Sample Input
2
2 2 2
2 2 3
Sample Output
HVVH
VHHV
Explanation
All the paths of going to  from  in lexicographically increasing order:





=========================editorial============================
it is simple string rank algorithm type ..
===============================code=======================
#include<bits/stdc++.h>
using namespace std;
typedef long long int lli;

lli c[21][21];
lli table[21][21];
lli fact[21];
void f()
{
fact[0]=1;
for(int i=1;i<=20;i++)
{
fact[i]=fact[i-1]*i;
}
}

#include<bits/stdc++.h>
using namespace std;
#define mod 1000000007
typedef long long int lli;
void compute() 
{
    table[1][0] = 1;
    table[1][1] = 1;
    for(int n=2; n<=20; n++) 
{
        for(int r=0; r<=n; r++) 
{
            table[n][r] = ((long long)((r<n) ? table[n-1][r] : 0) + ((r>0) ? table[n-1][r-1] : 0))%mod;
        }
    }
    return;
}


int main()
{
int t;
cin>>t;
compute();
f();
while(t--)
{
  int x,y,r;
 cin>>x>>y>>r;
 r++;
 string s="";
 int tot=x+y;
 while(tot)
  {
  lli   gen=0;
    if(x>=1)
  gen =fact[tot-1]/(fact[x-1]*fact[y]);
  
 // cout<<tot<<" "<<gen<<endl;
  if(gen>=r)
  {
  s+='H';
  x--;
  }
  else
  {
  r-=gen;
  s+='V';
  y--;
  }
  tot--;
  }
 // reverse(s.begin(),s.end());
  cout<<s<<endl;
 
}
}

No comments:

Post a Comment