Decibinary Numbers


Problem Statement :


Let's talk about binary numbers. We have an n-digit binary number, b , and we denote the digit at index  i (zero-indexed from right to left) to be bi. We can find the decimal value of  using the following formula:

For example, if binary number b = 10010, we compute its decimal value like so:

Meanwhile, in our well-known decimal number system where each digit ranges from 0 to 9, the value of some decimal number, d, can be expanded in the same way:

Now that we've discussed both systems, let's combine decimal and binary numbers in a new system we call decibinary! In this number system, each digit ranges from  to  (like the decimal number system), but the place value of each digit corresponds to the one in the binary number system. For example, the decibinary number  represents the decimal number  because:

Pretty cool system, right? Unfortunately, there's a problem: two different decibinary numbers can evaluate to the same decimal value! For example, the decibinary number  also evaluates to the decimal value :

This is a major problem because our new number system has no real applications beyond this challenge!

Consider an infinite list of non-negative decibinary numbers that is sorted according to the following rules:

The decibinary numbers are sorted in increasing order of the decimal value that they evaluate to.
Any two decibinary numbers that evaluate to the same decimal value are ordered by increasing decimal value, meaning the equivalent decibinary values are strictly interpreted and compared as decimal values and the smaller decimal value is ordered first. For example,  and  both evaluate to . We would order  before  because .


Function Description

Complete the decibinaryNumbers function in the editor below. For each query, it should return the decibinary number at that one-based index.

decibinaryNumbers has the following parameter(s):

x: the index of the decibinary number to return
Input Format

The first line contains an integer, q, the number of queries.
Each of the next q lines contains an integer, x, describing a query.

Constraints


1   <=   q   <=   10^5
1   <=    x   <=  10^16

Output Format

For each query, print a single integer denoting the the xth decibinary number in the list. Note that this must be the actual decibinary number and not its decimal value. Use 1-based indexing.

Sample Input 0



Solution :



title-img


                            Solution in C :

In   C :




#include <stdio.h>
#include <stdlib.h>
#define MAX 500000
int get_i(long long*a,long long num,int size);
long long med(long long*a,int size);
long long dp[30][MAX],sum[MAX],two[30];
unsigned long long ten[30];

int main(){
  int T,i,j,k;
  long long x,y,z;
  unsigned long long ans;
  for(i=two[0]=ten[0]=1;i<30;i++){
    two[i]=two[i-1]*2;
    ten[i]=ten[i-1]*10;
  }
  for(i=0,dp[0][0]=1;i<MAX;i++)
    for(j=1;j<30;j++)
      for(k=0;k<10;k++)
        if(k*two[j-1]<=i)
          dp[j][i]+=dp[j-1][i-k*two[j-1]];
  for(i=0;i<MAX;i++)
    if(i)
      sum[i]=sum[i-1]+dp[29][i];
    else
      sum[i]=dp[29][i];
  scanf("%d",&T);
  while(T--){
    scanf("%lld",&x);
    i=get_i(sum,x,MAX);
    if(i)
      y=x-sum[i-1];
    else
      y=x;
      //printf("i:%d y:%lld\n",i,y);
    for(j=29,ans=0;j>=0;j--)
      if(j)
        for(k=z=0;k<10;k++){
          z+=dp[j][i-k*two[j]];
          if(z>=y){
            y-=z-dp[j][i-k*two[j]];
            i-=k*two[j];
            ans+=k*ten[j];
      //printf("i:%d y:%lld\n",i,y);
            break;
          }
        }
      else
        ans+=i;
    printf("%llu\n",ans);
  }
  return 0;
}
int get_i(long long*a,long long num,int size){
  if(size==0)
    return 0;
  if(num>med(a,size))
    return get_i(&a[(size+1)>>1],num,size>>1)+((size+1)>>1);
  else
    return get_i(a,num,(size-1)>>1);
}
long long med(long long*a,int size){
  return a[(size-1)>>1];
}
                        


                        Solution in C++ :

In   C++ :





#include<bits/stdc++.h>
#include<iostream>
using namespace std;
#define fre 	freopen("in.txt","r",stdin);freopen("0.out","w",stdout)
#define abs(x) ((x)>0?(x):-(x))
#define MOD 1000000007
#define LL signed long long int
#define scan(x) scanf("%d",&x)
#define print(x) printf("%d\n",x)
#define scanll(x) scanf("%lld",&x)
#define printll(x) printf("%lld\n",x)
#define rep(i,from,to) for(int i=(from);i <= (to); ++i)
#define pii pair<int,int>
LL dp[300000+5][22];
LL sdp[300000+5];
int main(){
    int N = 300000;
    for(int i=0;i<=9;++i)dp[i][0] = 1;
    for(int i=0;i<=N;++i){
        for(int j=1;j<=20;++j){
            for(int d=0;d<=9;++d){
                if((i-d*(1<<j)) >= 0)
                    dp[i][j] = (dp[i][j] + dp[i-d*(1<<j)][j-1]);
            }
        }
        sdp[i] = sdp[i-1] + dp[i][20];
    }
    int Q;
    cin>>Q;
    while(Q--){
        LL x;
        cin>>x;
        if(x==1){cout<<0<<endl;continue;}
        int L = 0;
        int R = N;
        while(L!=R){
            int m = ceil((L+R)/2.0);
            if(sdp[m] < x)L=m;
            else R = m-1;
        }
        LL val = L+1;
        x -= sdp[L];
        int pos = 0;
        for(int j=20;j>=1;--j){
            for(int d = 0;d<=9;++d){
                if(x > dp[val-d*(1<<j)][j-1]){
                    //cout<<j<<' '<<d<<endl;
                    x -= dp[val-d*(1<<j)][j-1];
                }
                else{
                    if(pos or d){
                        pos = 1;
                        cout<<d;
                        val -= d * (1<<j);
                    }
                    break;
                }
            }
        }
        cout<<val<<endl;
    }
}
                    


                        Solution in Java :

In   Java :




import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        int BITS = 19;
        int MAX = 1<<BITS;
        long[][] dp = new long[BITS][MAX];
        for (int i = 0; i < 10; i++)
            dp[0][i] = 1;
        for (int i = 1; i < BITS; i++) {
            int sub = 1<<i;
            for (int j = 0; j < MAX; j++) {
                for (int k = 0; k <= 9; k++) {
                    int rem = j-k*sub;
                    if (rem < 0)
                        break;
                    dp[i][j] += dp[i-1][rem];
                }
            }
        }
        long sum = 0;
        TreeMap<Long, Integer> sums = new TreeMap<Long, Integer>();
        sums.put(0l, -1);
        for (int i = 0; i < MAX; i++) {
            sum += dp[BITS-1][i];
            sums.put(sum, i);
        }
        Scanner sc = new Scanner(System.in);
        int q = sc.nextInt();
        for (int z = 0; z < q; z++) {
            long n = sc.nextLong();
            int val = sums.floorEntry(n-1).getValue()+1;
            n -= sums.floorEntry(n-1).getKey();
            long ans = 0;
            for (int i = BITS-1; i > 0; i--) {
                int digit = 0;
                while (dp[i-1][val] < n) {
                    n -= dp[i-1][val];
                    digit++;
                    val -= (1<<i);
                }
                ans *= 10;
                ans += digit;
            }
            ans *= 10;
            ans += val;
            System.out.println(ans);
        }
    }
}
                    


                        Solution in Python : 
                            
In   Python3 :






import math
import os
import random
import re
import sys
import bisect
import array
import timeit
from itertools import repeat

def decbinValue(x):
    ans = 0
    p2 = 1
    while x > 0:
        ans += (x % 10) * p2
        p2 *= 2
        x //= 10
    return ans

class Solution:
    def __init__(self):
        self.nrepr = {0: 1, 1: 1, 2: 2, 3: 2}
        self.ndrepr = {(0,0): 1}
        #self.initSimple()
        self.init()
        #self.test()
        # self.speedTest()

    def numRepr(self, n):
        if n in self.nrepr:
            return self.nrepr[n]
        ans = 0
        for i in range(10):
            if n-i >= 0 and (n-i)%2 == 0:
                ans += self.numRepr((n-i)//2)
        self.nrepr[n] = ans
        return ans

    def numFixR(self, n, d):
        if (n,d) in self.ndrepr:
            return self.ndrepr[(n,d)]
        if d == 0 and n > 0:
            return 0
        if n > (2**d - 1) * 9:
            return 0
        ans = 0
        for i in range(10):
            if n-i >= 0 and (n-i)%2 == 0:
                ans += self.numFixR((n-i)//2, d-1)
        self.ndrepr[(n,d)] = ans
        return ans

    def test(self):
        print(10**16)
        print(self.numRepr(100000))
        print(self.numRepr(100))
        start = timeit.default_timer()
        self.decibinaryNumbers(10**16)
        stop = timeit.default_timer()
        self.decibinaryNumbers(10**16)
        stop2 = timeit.default_timer()
        print(self.decibinaryNumbers(10**16))
        print('Time 1st: ', stop - start, '2nd:', stop2 - stop)
        for d in range(1, 35000):
            if str(self.decibinaryNumbersSimple(d)) != self.decibinaryNumbers(d):
                print("Yoop", d, self.decibinaryNumbersSimple(d), self.decibinaryNumbers(d))
                break
        a = array.array('q', [1,10**8,10**15,10**16])
        print(a, a.itemsize)

    def speedTest(self):
        print(10**16)
        print(self.numRepr(100000))
        print(self.numRepr(100))
        start = timeit.default_timer()
        self.decibinaryNumbers(10**16)
        stop = timeit.default_timer()
        self.decibinaryNumbers(10**16)
        stop2 = timeit.default_timer()
        print(self.decibinaryNumbers(10**16))
        print('Time 1st: ', stop - start, '2nd:', stop2 - stop)
        t1 = timeit.default_timer()
        for x in range(10**15, 10**15 + 10000):
            self.decibinaryNumbers(x)
        t2 = timeit.default_timer()
        print('Time many: ', t2 - t1)

    def initSimple(self):
        d = {}
        val = 0
        for n in range(1200111):
            if n%10 == 0:
                val = decbinValue(n)
            else:
                val += 1
            if val not in d:
                d[val] = [n]
            else:
                d[val].append(n)
        self.dbl = []
        ls = []
        for v in range(100):
            self.dbl.extend(sorted(d[v]))
            ll = len(d[v])
            ls.append((ll, self.numRepr(v)))
        print(len(self.dbl))

    def decibinaryNumbersSimple(self, x):
        if x <= len(self.dbl):
            return self.dbl[x-1]
        else:
            return 0

    def init(self):
        # tmst1 = timeit.default_timer()
        self.MAX_VAL = 285113
        # print(self.MAX_VAL, bin(self.MAX_VAL), len(bin(self.MAX_VAL)))
        self.MAX_L = 20
        # tmst2 = timeit.default_timer()
        self.ndra = [list(repeat(0, self.MAX_VAL)) for i in range(self.MAX_L)]
        # self.ndra = [array.array('q', repeat(0, self.MAX_VAL)) for i in range(self.MAX_L)]
        # self.ndra = [memoryview(self.mem[i*8*self.MAX_VAL: (i+1)*8*self.MAX_VAL]).cast('q') for i in range(self.MAX_L)]
        # [array.array('q', repeat(0, self.MAX_VAL)) for i in range(self.MAX_L)]
        for d in range(self.MAX_L):
            self.ndra[d][0] = 1
        # tmst3 = timeit.default_timer()
        max_values = [(2**d - 1) * 9 for d in range(self.MAX_L)]
        for v in range(1, self.MAX_VAL):
            # self.ndra[0][v] = 0 # default is zero
            rr = [(v-i)//2 for i in range(10) if v-i >= 0 and (v-i)%2 == 0]
            slc = slice(min(rr), max(rr) + 1)
            for d in range(1, self.MAX_L):
                if v <= max_values[d]:
                    self.ndra[d][v] = sum(self.ndra[d-1][slc])
        # tmst4 = timeit.default_timer()
        self.ssum = list(repeat(0, self.MAX_VAL))
        self.ssum[0] = self.ndra[-1][0]
        for v in range(1, self.MAX_VAL):
            self.ssum[v] = self.ssum[v-1] + self.ndra[-1][v]
        # print(self.ssum[-1])
        # tmst5 = timeit.default_timer()
        # print('Time whole: ', tmst4 - tmst1)
        # print('Time : ', tmst2 - tmst1)
        # print('Time : ', tmst3 - tmst2)
        # print('Time : ', tmst4 - tmst3)
        # print('Time : ', tmst5 - tmst4)
        # for v in range(1, self.MAX_VAL//1000):
        #     d = 3
        #     if self.ndra[d][v] != self.numFixR(v, d):
        #         print("NOOO", v, self.ndra[d][v], self.numFixR(v, d))
        #         break;

    def numFixArr(self, n, d):
        return self.ndra[d][n]

    def decibinaryNumbers(self, x):
        if x == 1:
            return "0"
        # find decibinary value
        v = bisect.bisect_left(self.ssum, x)
        x = x - self.ssum[v-1]
        # v = 0
        # while self.numRepr(v) < x:
        #     x -= self.numRepr(v)
        #     v += 1
        # if v != newv or x != newx:
        #     print("WWW", x, newx, v, newv)
        #     return 0
        # find lenth of result
        l = 0
        while self.ndra[l][v] < x:
            l += 1
        res = [0] * l
        selected_value = 0
        rv = v
        for pos in range(l):
            dig_left = l-pos-1
            p2 = 2**dig_left
            ndra_dig = self.ndra[dig_left]
            for dig in range(10):
                ndr = ndra_dig[rv]
                if ndr < x:
                    x -= ndr
                else:
                    res[pos] = dig
                    break
                rv -= p2
        return "".join(map(str,res))


if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')
    q = int(input())
    sol = Solution()
    for q_itr in range(q):
        x = int(input())
        result = sol.decibinaryNumbers(x)
        fptr.write(str(result) + '\n')
    fptr.close()
                    


View More Similar Problems

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →