Problem:


Score : 400 points

Problem Statement

In some other world, today is Christmas.

Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing:

A level-0 burger is a patty.

A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) burger and another bun, stacked vertically in this order from the bottom.

For example, a level-1 burger and a level-2 burger look like BPPPB and BBPPPBPBPPPBB (rotated 90 degrees), where B and P stands for a bun and a patty.

The burger Mr. Takaha will make is a level-N burger. Lunlun the Dachshund will eat X layers from the bottom of this burger (a layer is a patty or a bun). How many patties will she eat?

Constraints

1 \leq N \leq 50

1 \leq X \leq ( the total number of layers in a level-N burger )

N and X are integers.

Input

Input is given from Standard Input in the following format:

N X

Output

Print the number of patties in the bottom-most X layers from the bottom of a level-N burger.

Sample Input 1

2 7

Sample Output 1

4

There are 4 patties in the bottom-most 7 layers of a level-2 burger (BBPPPBPBPPPBB).

Sample Input 2

1 1

Sample Output 2

0

The bottom-most layer of a level-1 burger is a bun.

Sample Input 3

50 4321098765432109

Sample Output 3

2160549382716056

A level-50 burger is rather thick, to the extent that the number of its layers does not fit into a 32-bit integer.



Sample input:
2 7


Sample output:
4

Submission status: Accepted

Solution code:
def main():

    """ convenient functions
    # for i, a in enumerate(iterable)
    # q, mod = divmod(a, b)
    # divmod(x, y) returns the tuple (x//y, x%y)
    # Higher-order function: reduce(operator.mul, xyz_count, 1)
    # manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
    """

    """convenient decorator
    # @functools.lru_cache():
    # to facilitate use of recursive function
        # ex:
        # from functools import lru_cache
        # import sys
        # sys.setrecursionlimit(10**9)
        # @lru_cache(maxsize=None)
        # def fib(n):
        #     if n < 2:
        #         return n
        #     return fib(n-1) + fib(n-2)
        # print(fib(1000))
    """
    
    # import numpy as np
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
    # accumulate() returns iterator! to get list: list(accumulate())
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  # prime factor
        b, e = 2, 0  # base, exponent
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        # TODO: How should I do when n - r is negative?
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict # https://docs.python.org/ja/3/library/collections.html#collections.deque
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
    from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
    import operator
    from operator import itemgetter #sort 
    # ex1: List.sort(key=itemgetter(1))
    # ex2: sorted(tuples, key=itemgetter(1,2))
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)

    # first create factorial_list
    # fac_list = mod_factorial_list(n)
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
    def modinv(a, p = MOD):
        # evaluate reciprocal using Fermat's little theorem:
        # a**(p-1) is identical to 1 (mod p) when a and p is coprime
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        # fac_list = modfactorial_list(100)
        # print(modcomb(100, 5, modfactorial_list(100)))
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    """ initialize variables and set inputs
    # initialize variables
        # to initialize list, use [0] * n
        # to initialize two dimentional array, use [[0] * N for _ in range(N)]
    # set inputs
        # put inputs between specific values (almost as quickly)
        # ex) S = [-INF] + [int(r()) for _ in range(A)] + [INF]
        # open(0).read() is sometimes useful:
        # ex) n, m, *x = map(int, open(0).read().split())
        #     min(x[::2]) - max(x[1::2])
        # ex2) *x, = map(int, open(0).read().split())
        #     don't forget to add comma after *x if only one variable is used
    # preprocessing
        # transpose = [x for x in zip(*data)]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        # flat = [flatten for inner in data for flatten in inner]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    # calculate and output
        # output pattern
        # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
    """

    # functions used
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    R = lambda: list(map(int, r().split()))
    Rmap = lambda: map(int, r().split())
    Rfloat = lambda: list(map(float, r().split()))
    Rtuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    # single int: int(r())
    # single string: r()
    # single float: float(r())
    # line int: R()
    # line string: r().split()
    # line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
    # lines int: [R() for _ in range(n)]
    """

    if __name__ != '__main__':
        # for test
        sys.stdin = open('sample.txt')
        
    # ----------------------------------
    # main

    N, X = R()
    """
    A_n = 2A_(n-1) + 3, A_0 = 1
    B_n = 2B_n-1 + 1, B_0 = 0
    """
    A = [1] * 50
    B = [1] * 50
    for i in range(1, 50):
        A[i] = 2 * A[i-1] + 3
    for i in range(1, 50):
        B[i] = 2 * B[i-1] + 1
    
    @lru_cache(maxsize=None)
    def burg(l, x):
        if x == 1:
            if l == 0:
                return 1
            return 0
        elif x <= 1 + A[l-1]:
            return 0 + burg(l-1, x-1)
        elif x == 2 + A[l-1]:
            return 1 + B[l-1]
        elif x <= 2 + 2*A[l-1]:
            return 1 + B[l-1] + burg(l-1, x-2-A[l-1])
        else:
            return 2 * B[l-1] + 1
    # for i in range(1, X+1):
    #     print(N, i, ':',burg(N, i))
    print(burg(N, X))
    
    # def burger(l):
    #     if l == 0:
    #         return 'P'
    #     else:
    #         return 'B' + burger(l-1) + 'P' + burger(l-1) + 'B'
    # print(burger(3))
    
    # end of main
    # ----------------------------------

    """memo: how to use defaultdict of list
    # initialize
    Dic = defaultdict(list)
    # append / extend
    Dic[x].append(y)
    # three methods for loop: keys(), values(), items()
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    # to make binary digits text
    >>> a = 5
    >>> bin_str_a = format(a, '#06b')
    >>> print(bin_str_a)
    0b0101 # first 2 strings (='0b') indicates it is binary
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, X = map(int, input().split())
a,p = [1],[1]

for i in range(N):
  a.append(2 * a[i] + 3)
  p.append(2 * p[i] + 1)
  
def runrun(N,X):
  if N == 0:
    return 0 if X <= 0 else 1
  elif X<= 1 + a[N-1]:
    return runrun(N-1, X-1)
  else:
    return p[N-1] + 1 + runrun(N-1, X-a[N-1]-2)
    
    
print(runrun(N,X))

Submission status: Accepted

Solution code:
N, X = map(int, input().split())


# 漸化式を立てて解く
def f(n, x):
    return (
        0 if x <= 0 else
        2**(n + 1) - 1 if x >= 2**(n + 2) - 3 else
        f(n - 1, x - 1) +
        f(0, x - (2**(n + 1) - 2)) +
        f(n - 1, x - (2**(n + 1) - 1))
    )


ans = f(N, X)

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from functools import lru_cache

size = [0] * 51

@lru_cache(100000)
def rec(l, x):
	global size
	# print(l, x)
	if l == 0:
		# print(x)
		return x
	mid = size[l] // 2 + 1
	if x == size[l]:
		return 2 * rec(l-1, size[l-1]) + 1
	elif x == mid:
		return rec(l-1, size[l-1]) + 1
	elif x == 1:
		return 0
	elif x > mid:
		return rec(l-1, size[l-1]) + rec(l-1, x-size[l-1]-2) + 1
	else:
		return rec(l-1, x-1)

def main():
	global size
	n, x = map(int, input().strip().split())
	size[0] = 1
	for i in range(1, 51):
		size[i] = 2 * size[i-1] + 3
	# print(rec(1, size[1]))
	print(rec(n, x))

if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
N, X = map(int, input().split())

a = [1] * (N + 1)
p = [1] * (N + 1)
for i in range(N):
    a[i + 1] = a[i] * 2 + 3
    p[i + 1] = p[i] * 2 + 1

def f(n, x):
    if n == 0:
        return 0 if x <= 0 else 1
    elif x <= 1 + a[n - 1]:
        return f(n - 1, x - 1)
    else:
        return p[n - 1] + 1 + f(n - 1, x - 2 - a[n - 1])
    
print(f(N, X))

Submission status: Accepted

Solution code:
N,X = map(int, input().split())

burger_list = []
for i in range(N+1):
    if i == 0:
        burger_list.append([0,1])
    else:
        burger_list.append([2+burger_list[-1][0]*2,1+burger_list[-1][1]*2])

def pty(x,k,List):
    if x == 1:
        y = 0
    elif 1 < x <= sum(List[k-1])+1:
        y = 1
    elif x == 2+sum(List[k-1]):
        y = 2
    elif x == sum(List[k]):
        y = 4
    elif 2+sum(List[k-1]) < x <= 2+sum(List[k-1])*2:
        y = 3
    return y
        
ans = 0
k = N
while X > 0:
    n = pty(X,k,burger_list)
    if n == 0:
        if k == 0:
            ans += 1
        X = 0
    elif n == 2:
        ans += (burger_list[k-1][1]+1)
        X = 0
    elif n == 4:
        ans += burger_list[k][1]
        X = 0
    elif n == 1:
        X -= 1
        k -= 1
    elif n == 3:
        ans += (burger_list[k-1][1]+1)
        X -= (sum(burger_list[k-1])+2)
        k -= 1
print(ans)

Submission status: Accepted

Solution code:
def len_burger(L):
    return 2**(L+2)-3
def num_ban(L):
    return 2**(L+1)-1

def eat(L,X):
    if L == 0: return 1
    if X == 1: return 0
    elif X <= len_burger(L-1)+1: return eat(L-1,X-1)
    elif X == len_burger(L-1)+2: return num_ban(L-1)+1
    elif X < 2*len_burger(L-1)+3: return num_ban(L-1)+1+eat(L-1,X-len_burger(L-1)-2)
    elif X == len_burger(L): return num_ban(L)

def solve():
    N,X = [int(s) for s in input().split() if s]
    
    print(eat(N,X))
    
solve()

Submission status: Accepted

Solution code:
A,P=[1],[1]
for i in range(50):
    A.append(A[i]*2+3)
    P.append(P[i]*2+1)

def n(N, X):
    if X<=0: return 0
    if N==0: return 1
    return n(N-1, X-1) if X <= A[N-1]+1 else P[N-1] + 1 + n(N-1, X-(A[N-1]+2))

print(n(*list(map(int, input().split()))))

Submission status: Accepted

Solution code:
N,X = map(int,input().split())
l = [1]*(N+1)
p = [1]*(N+1)
for i in range(N):
    l[i+1] = 2*l[i]+3
    p[i+1] = 2*p[i]+1
def f(n,x):
    if n==0:return 1
    if x==1:return 0
    if x<= l[n-1]+1:return f(n-1,x-1)
    if x== l[n-1]+2:return 1+p[n-1]
    return 1+p[n-1]+f(n-1,x-2-l[n-1])
print(f(N,X))

Submission status: Accepted

Solution code:
N, X = map(int, input().split())

a = [1]
p = [1]
for i in range(1, N+2):
    a.append(2 * a[i-1] + 3)
    p.append(2 * p[i-1] + 1)

def calc(N, X): #レベルNバーガーの下からX層に含まれるパティの枚数
    if N == 0: #全てパティ
        if X == 0:
            return 0
        else:
            return 1
    if X == 1:
        return 0
    # print (N - 1)
    if 1 < X <= 1 + a[N - 1]:
        # print ('A')
        return calc(N - 1, X - 1)
    if X == 2 + a[N - 1]:
        # print ('B')
        return p[N - 1] + 1
    if 2 + a[N - 1] < X <= 2 + 2 * a[N - 1]:
        # print ('C')
        return p[N - 1] + 1 + calc(N - 1, max(X - 2 - a[N - 1], 0))
    if X == 3 + 2 * a[N - 1]:
        # print ('D')
        return p[N]

print (calc(N, X))

Submission status: Accepted

Solution code:
import numpy as np

n, x = map(int,input().split())
size = [1]
full_p = [1]
for i in range(n):
    size.append(size[i]*2+3)
    full_p.append(full_p[i]*2+1)

# print(size)
def num_p(x,n):
    if n == 0:
        return 1
    burg = size[n-1]
    if x == 1:
        return 0
    elif x == burg+2:
        return full_p[n-1]+1
    elif x < burg +2:
        return num_p(x-1,n-1)
    elif x > burg+2:
        return full_p[n-1]+1+num_p(x-(burg+2),n-1)

# print(size)
ans = num_p(x,n)

print(ans)

Submission status: Accepted

Solution code:
def calc(n,x):
  ans=0
  while 1:
    if x==1:
      break
    elif 2<=x<=lb[n-1]:
      x-=1
      n-=1
    elif x==1+lb[n-1]:
      ans+=pb[n-1]
      break
    elif x==2+lb[n-1]:
      ans+=1+pb[n-1]
      break
    elif 3+lb[n-1]<=x<=1+2*lb[n-1]:
      ans+=1+pb[n-1]
      x-=2+lb[n-1]
      n-=1
    elif x==2+2*lb[n-1]:
      ans+=1+2*pb[n-1]
      break
    elif x==3+2*lb[n-1]:
      ans+=1+2*pb[n-1]
      break
  return ans

n,x=map(int,input().split())
lb=[1]
pb=[1]
for i in range(1,51):
  lb.append(lb[i-1]*2+3)
for i in range(1,51):
  pb.append(pb[i-1]*2+1)
print(calc(n,x))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
#ABC115 D

n,x = map(int,input().split())

burger = [0]*(n+1)#厚み
p = [0]*(n+1)#パテの数
burger[0],p[0] = 1,1
for i in range(n):
    p[i+1] = 2*p[i]+1
    burger[i+1] = 2*burger[i]+3

def f(n,x):
    if n == 0:
        if x <= 0:
            return 0
        else:
            return 1
    if x == 1:
        if n == 0:
            return 1
        else:
            return 0
    elif x <= burger[n-1] + 1:
        return f(n-1,x-1)
    elif x == burger[n-1] + 2:
        return p[n-1] + 1
    elif burger[n-1] + 2 < x <= 2*burger[n-1] + 2:
        return p[n-1] + 1 + f(n-1,x-2-burger[n-1])
    elif x == 2*burger[n-1] + 3:
        return 2*p[n-1] + 1
ans = f(n,x)
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return sys.stdin.readline().strip()
INF = 10 ** 18
MOD = 10 ** 9 + 7

N, X = LI()

def solve():
  
  lenl = [0 for i in range(N+1)]
  for i in range(N+1):
    if i == 0:
      lenl[i] = 1
    else:
      lenl[i] = 2 * lenl[i-1] + 3
  
  npl = [0 for i in range(N+1)]
  for i in range(N+1):
    if i == 0:
      npl[i] = 1
    else:
      npl[i] = 2 * npl[i-1] + 1

  def np(l, x):
    if x <= 0:
      return 0
    if l == 0:
      return 1
    
    if x < lenl[l] // 2:
      return np(l-1, x-1)
    elif x == lenl[l] // 2:
      return npl[l-1]
    elif x == (lenl[l] // 2) + 1:
      return npl[l-1] + 1
    else:
      return npl[l-1] + 1 + np(l-1, x-(lenl[l]//2)-1)
  
  print(np(N, X))
solve()

Submission status: Accepted

Solution code:
N, X = map(int, input().split())


def a(N):
    return 2 ** (N + 2) - 3


def p(N):
    return 2 ** (N + 1) - 1


def f(N, X):
    if N == 0:
        return 1 if X > 0 else 0

    if X == 1:
        return 0
    elif X <= 1 + a(N - 1):
        return f(N - 1, X - 1)
    else:
        return p(N - 1) + 1 + f(N - 1, X - 2 - a(N - 1))


print(f(N, X))

Submission status: Accepted

Solution code:
import math
import copy
from operator import mul
from functools import reduce
from collections import defaultdict
from collections import Counter
from collections import deque
# 直積 A={a, b, c}, B={d, e}:のとき，A×B={(a,d),(a,e),(b,d),(b,e),(c,d),(c,e)}: product(A, B)
from itertools import product
# 階乗 P!: permutations(seq), 順列 {}_len(seq) P_n: permutations(seq, n)
from itertools import permutations
# 組み合わせ {}_len(seq) C_n: combinations(seq, n)
from itertools import combinations
# 一次元累積和
from itertools import accumulate
from bisect import bisect_left, bisect_right

# import numpy as np
# from scipy.misc import perm
# from scipy.misc import comb

def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W

# 四方向: 右, 下, 左, 上
dy = [0, -1, 0, 1]
dx = [1, 0, -1, 0]
 
def i_inpl(): return int(input())
def l_inpl(): return list(map(int, input().split()))
def line_inpl(x): return [i_inpl() for _ in range(x)]

INF = int(1e18)
MOD = int(1e9)+7 # 10^9 + 7

########

N, X = l_inpl()

a, p = [1], [1]
for i in range(N):
    a.append(a[i]*2+3)
    p.append(p[i]*2+1)

def f(N, X):
    if N == 0: # 一番下の層のみ
        if X > 0:
            return 1
        else:
            return 0
    elif X <= 1 + a[N-1]: # 一番下の層 + その上のN-1バーガーの下からX-1層
        return f(N-1, X-1)
    else:
        return p[N-1] + 1 + f(N-1, X-2-a[N-1])

print(f(N, X))

Submission status: Accepted

Solution code:
def thickness(l):
    return 2 ** (l + 2) - 3


def pate(l):
    return 2 ** (l + 1) - 1


def rec(l, x):
    if l == 0:
        return x
    t = thickness(l-1)
    if x <= 1:
        return 0
    elif x <= t + 1:
        return rec(l-1, x-1)
    elif x <= t + 2:
        return pate(l-1) + 1
    elif x <= 2 * t + 2:
        return pate(l-1) + 1 + rec(l-1, x-t-2)
    else:
        return pate(l)


def main():
    n, x = map(int, input().split())
    print(rec(n, x))


main()

Submission status: Accepted

Solution code:
N, X = map(int,input().split())

def keisan(n,x):
    if n == 1:
        if x <= 1:
            return 0
        elif 2 <= x <= 4:
            return x-1
        else:
            return 3
    if x <= 1:
        return 0
    elif 1 < x <= 2**(n+1) - 2:
        return keisan(n-1,x-1)
    elif x == 2**(n+1) - 1:
        return 2**n
    else:
        return 2**n + keisan(n-1,x-(2**(n+1)-1))

print(keisan(N,X))

Submission status: Accepted

Solution code:
p=[1]
b=[1]
for i in range(50):
    p.append(p[i]*2+1)
    b.append(b[i]*2+3)
def main(n,x):
    if n==0:
        if x==1:
            return 1
        return 0
    if b[n]==x:
        return p[n]
    if b[n-1]+1>=x:
        return main(n-1,x-1)
    else:
        return main(n-1,x-b[n-1]-2)+1+p[n-1]
n,x=map(int,input().split())
print(main(n,x))

Submission status: Accepted

Solution code:
def burger(n, x):
    if x < 1:
        return 0

    # base case
    if (n, x) == (0, 1):
        return 1

    if x <= 1 + size[n - 1]:
        return burger(n - 1, x - 1)
    else:
        return p_num[n - 1] + 1 + burger(n - 1, min(x - 2 - size[n - 1], size[n - 1]))
    # x-2-sizeだと前lvバーガー+バンのことがあり、バンを外す


n, x = map(int, input().split())
size, p_num = [1], [1]
for i in range(1, 50 + 1):
    size.append(size[-1] * 2 + 3)
    p_num.append(p_num[-1] * 2 + 1)

print(burger(n, x))

Submission status: Accepted

Solution code:
from collections import defaultdict


def burger(lv, x):
    if d[(lv, x)] >= 0:
        return d[(lv, x)]

    if x < 1 or x > cnt[lv]:
        d[(lv, x)] = 0
        return d[(lv, x)]

    # base case
    if (lv, x) == (0, 1):
        d[(lv, x)] = 1
        return d[(lv, x)]

    half = (cnt[lv] - 1) // 2
    if x <= half:
        d[(lv, x)] = burger(lv - 1, x - 1)
        return d[(lv, x)]
    else:
        d[(lv, x)] = burger(lv - 1, half - 1) + 1 + burger(lv - 1, min(x - 1 - half, half - 1))
        return d[(lv, x)]


n, x = map(int, input().split())
cnt = [1]
for lv in range(1, 50 + 1):
    cnt.append(cnt[-1] * 2 + 3)
d = defaultdict(lambda: -1)

print(burger(n, x))
# print(d)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)

N, X = map(int, input().split())

if X < N :
    print(0)
else :
    pat = [0] * (N + 1)  # パティ数
    ban = [0] * (N + 1)  # バンズ数
    pat[0] = 1
    for i in range(1, N + 1) :
        pat[i] = 2 * pat[i - 1] + 1
        ban[i] = 2 * ban[i - 1] + 2
    def sol(level, height) :
        if height <= 0 :
            return 0
        if level == 0 :
            return 1
        if height <= 1 :
            return 0
        if height < pat[level - 1] + ban[level - 1] :
            return sol(level - 1, height - 1)
        if height == pat[level - 1] + ban[level - 1] + 1 :
            return pat[level - 1]
        if height == pat[level - 1] + ban[level - 1] + 2 :
            return pat[level - 1] + 1
        return pat[level - 1] + 1 + sol(level - 1, height - (pat[level - 1] + ban[level - 1] + 2))

    ans = sol(N, X)
    print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(100000000)

N,X = map(int,input().split())

total_b = [0]
total_p = [1]
total = [1]

for i in range(N):
    b = total_b[-1]*2 + 2
    p = total_p[-1]*2 + 1
    x = b+p
    total_b.append(b)
    total_p.append(p)
    total.append(x)
#print(total,total_b,total_p)

def dfs(x,level):
    if x == 1 or x == 0:
        #print(1)
        return 0
    if x == total[level-1] + 1:
        #print(2)
        return total_p[level-1]
    if x == total[level-1] + 2:
        #print(3)
        return total_p[level-1] + 1
    if x == total[level-1]*2 + 2:
        #print(4)
        return total_p[level-1]*2 + 1
    if x == total[level-1]*2 + 3:
        #print(5)
        return total_p[level-1]*2 + 1
    if x > 1 and total[level-1] + 1 > x:
        #print(6)
        return dfs(x-1,level-1)
    if x > total[level-1] + 2 and total[level-1]*2 + 2 > x:
        #print(7)
        return dfs(x - total[level-1] - 2,level-1) + total_p[level-1] + 1
ans = dfs(X,N)
print(ans)

Submission status: Accepted

Solution code:
N, X = map(int, input().split())
dp_layer = [1] * (N + 1)
dp_numP = [1] * (N + 1)

for i in range(1, N + 1):
	dp_layer[i] = 3 + 2 * dp_layer[i - 1]
	dp_numP[i] = 1 + 2 * dp_numP[i - 1]
	
x = X
countP = 0
i = N

while x > 0:
	if x >= dp_layer[i]:
		x -= dp_layer[i]
		countP += dp_numP[i]
		if x > 0:
			x -= 1
			countP += 1
	else:
		i -= 1
		x -= 1
		
print(countP)

Submission status: Accepted

Solution code:
N,X=map(int,input().split())

hlist=[]
blist=[]
plist=[]
for i in range(N+1):
  hlist.append(2**(i+2)-3)
  #blist.append(2**(i+1)-2)
  plist.append(2**(i+1)-1)
  
#print(hlist)
#print(blist)
#print(plist)

num_p=0
while(True):
  #print(N,X,num_p)
  if N==0:
    num_p+=1
    break
  elif X==1:
    break
  elif X==hlist[N]//2+1:
    num_p+=plist[N-1]+1
    break
  elif X==hlist[N]:
    num_p+=plist[N]
    break
  elif X<hlist[N]//2+1:
    X-=1
    N-=1
  else:
    num_p+=plist[N-1]+1
    X-=hlist[N]//2+1
    N-=1
  
print(num_p)

Submission status: Accepted

Solution code:
n, x = list(map(int, input().split()))

pb = 0
p = 0

def christmas(l, x) :
    global pb, p
    if l == 0 :
        if pb < x :
            pb += 1
            p += 1
    else :
        if pb < x :
            pb += 1
        if pb + 2**(l+1)-3 <= x :
            pb += 2**(l+1)-3
            p += 2**l-1
        elif pb < x :
            christmas(l-1, x)
        if pb < x :
            pb += 1
            p += 1
        if pb + 2**(l+1)-3 <= x :
            pb += 2**(l+1)-3
            p += 2**l-1
        elif pb < x :
            christmas(l-1, x)
        if pb < x :
            pb += 1

christmas(n, x)
print(p)

Submission status: Accepted

Solution code:
def patty_num(N):
    if N == 0:
        return 1
    return 1 + 2 * patty_num(N - 1)

def burger_height(N):
    if N == 0:
        return 1
    else:
        return 3 + 2 * burger_height(N - 1)
    
def f(N, X):
    if X == 1:
        if N == 0:
            return 1
        else:
            return 0
    elif 1 < X and X <= burger_height(N - 1) + 1:
        return f(N - 1, X - 1)
    elif X == burger_height(N - 1) + 2:
        return patty_num(N - 1) + 1
    elif burger_height(N - 1) + 2 < X and X <= 2 * burger_height(N - 1) + 2:
        return patty_num(N - 1) + 1 + f(N - 1, X - 2 - burger_height(N - 1))
    
    return 2 * patty_num(N - 1) + 1
    
N, X = map(int, input().split())
print(f(N, X))

Submission status: Accepted

Solution code:
N, X = map(int, input().split())

a = [1]
p = [1]
for i in range(N):
    a.append(a[i]*2+3)
    p.append(p[i]*2+1)
    
def myfunc(L, X):
    if L==0:
        return 1 if X>0 else 0
    elif X==1:
        return 0
    elif 1<X and X<=a[L-1]+1:
        return myfunc(L-1, X-1)
    elif X==a[L-1]+2:
        return p[L-1]+1
    else:
        return p[L-1]+1+myfunc(L-1, X-a[L-1]-2)

print(myfunc(N, X))

Submission status: Accepted

Solution code:
n,x = list(map(int,input().split()))
def cal(n,x):
    if n==0:
        return 1
    if x==1:
        return 0
    ll = 2**(n+1)-3
    if x<=ll+1:
        return cal(n-1,x-1)
    if x==ll+2:
        return cal(n-1,x-2)+1
    if x<=ll+ll+2:
        return cal(n-1,ll)+1+cal(n-1,x-ll-2)
    if x==ll+ll+3:
        return 2**(n+1)-1

print(cal(n,x))

Submission status: Accepted

Solution code:
N, X = map(int, input().split())

bur = [1]
pati = [1]
for i in range(N):
    bur.append(bur[i] * 2 + 3)
    pati.append(pati[i] * 2 + 1)


def f(N, X):
    if N == 0:
        return 0 if X <= 0 else 1
    elif X <= 1 + bur[N - 1]:
        return f(N - 1, X - 1)
    else:
        return pati[N - 1] + 1 + f(N - 1, X - 2 - bur[N - 1])


print(f(N, X))

Submission status: Accepted

Solution code:
N, X = map(int, input().split())

a, p = [1], [1]
for i in range(N):
    a.append(a[i] * 2 + 3)
    p.append(p[i] * 2 + 1)

def f(N, X):
    if N == 0:
        return 0 if X <= 0 else 1
    elif X <= 1 + a[N-1]:
        return f(N-1, X-1)
    else:
        return p[N-1] + 1 +f(N-1, X-2-a[N-1])

print(f(N, X))

Submission status: Accepted

Solution code:
N, X = map(int, input().split())

cntP = [0]*(N+1)
cntP[0] = 1
for i in range(1, N+1):
    cntP[i] = cntP[i-1] * 2 + 1

layer = 1
for _ in range(N):
    layer = layer * 2 + 3

def calc(n, i, layer):
    if i == 0:
        return 0
    
    if n == 1:
        return "BPPPB"[:i].count("P")
    else:
        if i == layer // 2 + 1:
            return cntP[n-1] + 1
        elif i > layer // 2 + 1:
            return cntP[n-1] + 1 + calc(n-1, i - (layer // 2 + 1), (layer-3) // 2)
        elif i < layer // 2 + 1:
            return calc(n-1, i-1, (layer-3) // 2)

ans = calc(N, X, layer)
print(ans)