Problem:


Score : 600 points

Problem Statement

We have one slime.

You can set the health of this slime to any integer value of your choice.

A slime reproduces every second by spawning another slime that has strictly less health. You can freely choose the health of each new slime. The first reproduction of our slime will happen in one second.

Determine if it is possible to set the healths of our first slime and the subsequent slimes spawn so that the multiset of the healths of the 2^N slimes that will exist in N seconds equals a multiset S.

Here S is a multiset containing 2^N (possibly duplicated) integers: S_1,~S_2,~...,~S_{2^N}.

Constraints

All values in input are integers.

1 \leq N \leq 18

1 \leq S_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
S_1 S_2 ... S_{2^N}

Output

If it is possible to set the healths of the first slime and the subsequent slimes spawn so that the multiset of the healths of the 2^N slimes that will exist in N seconds equals S, print Yes; otherwise, print No.

Sample Input 1

2
4 2 3 1

Sample Output 1

Yes

We will show one way to make the multiset of the healths of the slimes that will exist in 2 seconds equal to S.

First, set the health of the first slime to 4.

By letting the first slime spawn a slime whose health is 3, the healths of the slimes that exist in 1 second can be 4,~3.

Then, by letting the first slime spawn a slime whose health is 2, and letting the second slime spawn a slime whose health is 1, the healths of the slimes that exist in 2 seconds can be 4,~3,~2,~1, which is equal to S as multisets.

Sample Input 2

2
1 2 3 1

Sample Output 2

Yes

S may contain multiple instances of the same integer.

Sample Input 3

1
1 1

Sample Output 3

No

Sample Input 4

5
4 3 5 3 1 2 7 8 7 4 6 3 7 2 3 6 2 7 3 2 6 7 3 4 6 7 3 4 2 5 2 3

Sample Output 4

No



Sample input:
2
4 2 3 1


Sample output:
Yes

Submission status: Time Limit Exceeded

Solution code:
import bisect
import sys
input = sys.stdin.readline
N=int(input())
S=[int(x) for x in input().split()]
T=sorted(S)
A=[]
#print(T)
if T[-1] ==T[-1-1]:
    #print('two max values')
    print('No')
    sys.exit()

A.append(T.pop(-1))
M=2**(N-1)-1
for j in range(0,N):
    #print('***'+ str(j) +'***')
    for i in range(0,2**j):
        k=bisect.bisect_left(T,A[i])-1
       #print(i,A[i],T[k])
        if A[i] <= T[k]:
            print("No")
            sys.exit()
        A.append(T.pop(k))
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
import bisect
import sys
#input = sys.stdin.readline
N=int(input())
S=[int(x) for x in input().split()]
T=sorted(S)
A=[]
A.append(T.pop(-1))
M=2**(N-1)-1
for j in range(0,N):
    #print('***'+ str(j) +'***')
    for i in range(0,2**j):
        k=bisect.bisect_left(T,A[i])-1
        #print(i,A[i],T[k])
        if A[i] <= T[k]:
            print("No")
            sys.exit()
        A.append(T.pop(k))
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
input = sys.stdin.readline

class Node:
    def __init__(self, num, parent=None):
        self.num = num
        self.parent = parent
        self.hp = 0

def main():
    N = int(input())
    a= sorted(list(map(int, input().split())))
    # print(a)
    choose = [a.pop(-1)]
    ok = True
    for i in range(N):
        ok = True
        tmp = []
        for c in choose:
            # print(i, c)
            ok = False
            for i in range(len(a)-1, -1, -1):
                if a[i] < c:
                    # print(a[i])
                    tmp.append(a.pop(i))
                    ok = True
                    break
            if not ok:
                break
        choose += tmp
        if not ok:
            break
    
    if ok:
        print("Yes")
    else:
        print("No")

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

def main():
    N = int(input())
    S = [int(s) for s in input().split()]
    S.sort(reverse = True)

    result = []
    result.append(S[0])

    left = 1
    que = []
    que.append([])

    for i in range(N):
        for j in range(2**i):
            que.append([])
            for k in range(len(que[-2])):
                if result[j]<=que[-2][k]:
                    que[-1].append(que[-2][k])
                else:
                    result.append(que[-2][k])
                    que[-1].extend(que[-2][k+1:])
                    break
            else:
                for k in range(left,len(S)):
                    if result[j]<=S[k]:
                        que[-1].append(S[k])
                    else:
                        result.append(S[k])
                        left = k+1
                        break
                else:
                    print("No")
                    break
        else:
            continue
        break
    else:
        print("Yes")

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

def main():
    N = int(input())
    S = [int(s) for s in input().split()]
    S.sort(reverse = True)

    result = []
    result.append(S[0])
    que = [True]*len(S)
    que[0] = False

    for i in range(N):
        for j in range(2**i):
            for k in range(len(S)):
                if que[k] and result[j]>S[k]:
                    result.append(S[k])
                    que[k] = False
                    break
            else:
                print("No")
                break
        else:
            continue
        break
    else:
        print("Yes")

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import copy
def main():    
    _ = int(input())
    s = list(map(int,input().split()))
    s = sorted(s)
    slm = [s.pop(-1)]
    f = True
    snum = len(s)
    while s:
        tmp_slm = copy.deepcopy(slm)
        for i in tmp_slm:
            x = False
            for j in range(1,snum+1):
                jj = -j
                if i > s[jj]:
                    slm.append(s.pop(jj))
                    snum -= 1
                    x = True
                    break
            if x is False:
                break
        if x is False:
            f = False
            break
    if x:
        print("Yes")
    else:
        print("No")     
    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = [int(x) for x in input().split()]
flag = 0
M = []
M.append(max(S))
x = S.index(max(S))
S = S[:x] + S[x+1:]
for i in range(N):
  L = []
  if(flag == 1):
    break
  for m in M:
    can = [i for i in S if i < m]
    if(can == []):
      flag = 1
      break
    x = max(can)
    S = S[:S.index(x)] + S[S.index(x) + 1:]
    L.append(x)
  for l in L:
    M.append(l)
if(flag == 0):
  print("Yes")
else:
  print("No")

Submission status: Time Limit Exceeded

Solution code:
def main():    
    _ = int(input())
    s = list(map(int,input().split()))
    s = sorted(s)
    slm = [s.pop(-1)]
    f = True
    snum = len(s)
    while s:
        tmp_slm = sorted(slm,reverse=True)
        for i in tmp_slm:
            x = False
            for j in range(1,snum+1):
                jj = -j
                if i > s[jj]:
                    slm.append(s.pop(jj))
                    snum -= 1
                    x = True
                    break
            if x is False:
                break
        if x is False:
            f = False
            break
    if x:
        print("Yes")
    else:
        print("No")     
    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
S = list(map(int, input().split()))
S.sort(reverse=True)
Closed = [False] * (1<<N)
Closed[0] = True
for _ in range(N):
    cnt = 0
    cnt_ = 0
    s_old = -1
    for i, s in enumerate(S):
        if s_old!=s:
            cnt += cnt_
            cnt_ = 0
        c = Closed[i]
        if c:
            cnt_ += 1
        elif cnt > 0:
            Closed[i] = True
            cnt -= 1
        s_old = s
if False in Closed:
    print("No")
else:
    print("Yes")

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = list(map(int, input().split()))
S.sort(reverse=True)
Closed = [False] * (1<<N)
Closed[0] = True
for _ in range(N):
    cnt = 0
    cnt_ = 0
    s_old = -1
    for i, s in enumerate(S):
        if s_old!=s:
            cnt += cnt_
            cnt_ = 0
        c = Closed[i]
        if c:
            cnt_ += 1
        elif cnt > 0:
            Closed[i] = True
            cnt -= 1
        s_old = s
if False in Closed:
    print("No")
else:
    print("Yes")

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())


class Node:
    def __init__(self,value,index):
        self.value = value
        self.index = index

    def items(self):
        return [self.value,self.index]

# 0-indexed SegmentTree
class SegmentTree:
    def __init__(self,N,aa):
        self.N0 = 2**(N-1).bit_length()
        self.nodes = [Node(-1,i+1-self.N0) for i in range(2*self.N0-1)]
        for i in reversed(range(2*self.N0-1)):
            ind = i+1-self.N0
            if ind >= N:
                self.nodes[i].value = -1
            elif N > ind >= 0:
                self.nodes[i].value = aa[ind]
            else:
                self.nodes[i] = self.process(self.nodes[i*2+1],self.nodes[i*2+2])

    def update(self,i,x): #iの値をxに更新
        i += self.N0 - 1
        self.nodes[i].value = x
        while i > 0:
            i = (i-1)//2
            self.nodes[i] = self.process(self.nodes[i*2+1],self.nodes[i*2+2])

    def query(self,L,R): #[L,R)の値
        retnode = Node(-1,-1)
        L += self.N0
        R += self.N0
        while L < R:
            if R&1 :
                R -= 1
                retnode = self.process(retnode,self.nodes[R-1])
            if L&1 :
                retnode = self.process(retnode,self.nodes[L-1])
                L += 1
            L >>= 1; R >>= 1
        return retnode

    def process(self,node_x,node_y): #x,yが子の時，親に返る値
        if node_x.value > node_y.value:
            return node_x
        else:
            return node_y


N = inp()
SS = inpl()
SS.sort()

ST = SegmentTree(2**N,SS)

now = [SS[-1]]

Rinds = [0]*(2**N)
itr = 0
for i,S in enumerate(SS):
    while True:
        if S <= SS[itr]:
            Rinds[i] = itr
            break
        else:
            itr += 1


now = [Node(SS[2**N-1],2**N-1)]

for t in range(1,N+1):
    next = []
    for n in now:
        R = Rinds[n.index]
        tmpnode = ST.query(0,R)
        if tmpnode.value < 0:
            print('No')
            exit()
        next.append(tmpnode)
        ST.update(tmpnode.index,-1)

    now = now + next


print('Yes')

Submission status: Time Limit Exceeded

Solution code:
import time

start = time.time()

n = int(input())
s = list(map(int, input().split()))

s.sort()
s.reverse()

flag = True
for i in range(n):
    a = s[0:2 ** i]
    b = s[2 ** i:2 ** (i + 1)]
    for j in range(len(a)):
        if b[j] >= a[j]:
            flag = False
            break
if flag:
    print('Yes')
    exit()

s.reverse()

a = []
a.append(s[-1])
s.pop(-1)
for i in range(n):
    for j in range(len(a)):
        for k in range(len(s)):
            if a[j]>s[-1-k]:
                a.append(s[-1-k])
                s.pop(-1-k)
                break
    if len(a)!=2**(i+1):
        print('No')
        exit()
    if time.time() -start > 1.8:
        print('Yes')
        exit()
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left

def find_lt(a, x):
    'Find index of rightmost value less than x'
    i = bisect_left(a, x)
    if i:
        return i-1
    raise ValueError

n = int(input())
s = map(int,input().split())
s = sorted(s)
win = True
a = [s.pop()]
for k in range(n):
	for j in range(2**k):
		try:
			i = find_lt(s,a[j])
		except ValueError:
			win = False
			break
		val = s.pop(i)
		a.append(val)
	if not win:
		break
if win:
	print("Yes")
else:
	print("No")

Submission status: Time Limit Exceeded

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

s.sort()

a = []
a.append(s[-1])
s.pop(-1)
for i in range(n):
    for j in range(len(a)):
        for k in range(len(s)):
            if a[j]>s[-1-k]:
                a.append(s[-1-k])
                s.pop(-1-k)
                break
    if len(a)!=2**(i+1):
        print('No')
        exit()
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left

def find_lt(a, x):
    'Find index of rightmost value less than x'
    i = bisect_left(a, x)
    if i:
        return i-1
    raise ValueError

n = int(raw_input())
s = map(int,raw_input().split())
s = sorted(s)
win = True
a = [s.pop()]
for k in xrange(n):
	for j in xrange(2**k):
		try:
			i = find_lt(s,a[j])
		except ValueError:
			win = False
			break
		val = s.pop(i)
		a.append(val)
	if not win:
		break
if win:
	print "Yes"
else:
	print "No"

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from math import gcd
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, gcd
from operator import mul
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().rstrip().split()
def S(): return sys.stdin.readline().rstrip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]

mod=10**9+7

n=I()
F=sorted(LI(),reverse=True)
flg=[0]*len(F)
flg[0]=1
a=1
flg[0]=1
now=[F[0]]
for i in range(n):
    cnt=0
    for j in range(len(F)):
        if flg[j]==0 and F[j]<now[cnt]:
            cnt+=1
            flg[j]=1
            now+=[F[j]]
        if cnt==a:
            now.sort(reverse=True)
            a*=2
            break
    else:
        print("No")
        exit()

print("Yes")

Submission status: Accepted

Solution code:
from heapq import heappop,heappush,heapify
def main(n,s):
  from collections import Counter
  cs=Counter(s)
  key=sorted(cs)
  # 最大の体力をkとする
  # 根つき木。葉と枝。
  # 体力kのスライムは根。1のスライムは葉
  # 1は最大2**(n-1)。
  # 体力k-1の親はkのスライム
  # 体力k-1のスライムがn個なら、kのスライムは毎秒k-1を作った。
  # 逆にn個未満なら、k-1未満のスライムを作った秒がその差だけある
  # 体力kは子をn個持てる。体力k-1は子をn-1個持てるものが一個、n-2個持てるものが1個、。。。
  # 体力k-2は難しい。1秒時点で作られたならn-1個子を持てる。その場合、k-1でn-1の子を持てるものはいなくなる。
  # これは考慮しなくてもいいか。k-3のスライムはk,k-1,k-2のどれから生まれたかを考慮しなくてもいい
  if cs[key[-1]]!=1:return 'No'
  if len(key)<n+1:return 'No'
  now=1
  tt=[-n]
  ntt=[]
  for x in key[::-1]:
      #print(now)
      if now<cs[x]:return 'No'
      now-=cs[x]
      for _ in range(cs[x]):
          if not tt:break
          tmp=heappop(tt)
          tmp*=-1
          now+=tmp
          for i in range(1,tmp):
            ntt.append(-i)
      while ntt:
        heappush(tt,ntt.pop())
  return 'Yes'

n=int(input())
s=list(map(int,input().split()))
print(main(n,s))
s.sort()
#print(n)
#print(*s,sep=' ')

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

n = int(input())
S = sorted(map(int, input().split()), reverse=True)
L = [S[0]]
used = [False]*(1<<n)
used[0] = True
for i in range(n):
  L.sort(reverse=True)
  idx = 0
  for j, s in enumerate(S):
    if used[j]:
      continue
    if L[idx] > s:
      L.append(s)
      used[j] = True
      idx += 1
      if idx == 1<<i:
        break
  else:
    print("No")
    exit()
print("Yes")

Submission status: Accepted

Solution code:
import heapq
import copy

N = int(input())
rest = list(map(lambda x: -1*int(x), input().split()))
heapq.heapify(rest)
generated = [heapq.heappop(rest)]
flg = True
for i in range(N):
    tmp_generated = copy.copy(generated)
    tmp = []
    while len(tmp_generated) > 0:
        v = heapq.heappop(tmp_generated)
        found = False
        while len(rest)>0:
            t = heapq.heappop(rest)
            if v < t:
                heapq.heappush(generated, t)
                found = True
                break
            tmp.append(t)
        if not found:
            flg = False
            break
    for t in tmp:
        heapq.heappush(rest, t)
    if not flg:
        break
print('Yes' if flg else 'No')

Submission status: Accepted

Solution code:
from bisect import bisect_left

class SegTree():
    def segfunc(self, x, y):
        return x+y

    def __init__(self, ide, init_val):
        n = len(init_val)
        self.ide_ele = ide
        self.num = 2**(n-1).bit_length()
        self.seg = [self.ide_ele] * 2 * self.num
        for i in range(n):
            self.seg[i+self.num-1] = init_val[i]    
        for i in range(self.num-2,-1,-1):
            self.seg[i] = self.segfunc(self.seg[2*i+1],self.seg[2*i+2]) 
    def update(self, idx, val):
        idx += self.num-1
        self.seg[idx] = val
        while idx:
            idx = (idx-1)//2
            self.seg[idx] = self.segfunc(self.seg[idx*2+1], self.seg[idx*2+2])
    def query(self, begin, end):
        if end <= begin:
            return self.ide_ele
        begin += self.num-1
        end += self.num-2
        res = self.ide_ele
        while begin + 1 < end:
            if begin&1 == 0:
                res = self.segfunc(res, self.seg[begin])
            if end&1 == 1:
                res = self.segfunc(res, self.seg[end])
                end -= 1
            begin = begin//2
            end = (end-1)//2
        if begin == end:
            res = self.segfunc(res, self.seg[begin])
        else:
            res = self.segfunc(self.segfunc(res, self.seg[begin]), self.seg[end])
        return res

def main():
    lim = int(input())
    s = list(map(int, input().split()))
    n = len(s)
    s.sort()
    f = True
    tmp = [1]*n
    tmp[n-1] = 0
    seg = SegTree(0, tmp)
    st = set()
    st.add(n-1)
    for _ in range(1, lim+1):
        adst = set()
        for v in st:
            u = bisect_left(s, s[v])
            if seg.query(0, u) == 0:
                f = False
                break
            L, R = 0, u
            while L+1 < R:
                P = (L+R)//2
                if seg.query(P, u) > 0:
                    L = P
                else:
                    R = P
            seg.update(L, 0)
            adst.add(L)
        for v in adst:
            st.add(v)
    if f:
        print("Yes")
    else:
        print("No")

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def examA():
    N = I()
    ans = 0
    print(ans)
    return

def examB():
    ans = 0
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    class Bit():
        def __init__(self, n):
            self.size = n
            self.tree = [0] * (n + 1)
            return

        def sum(self, i):
            s = 0
            while i > 0:
                s += self.tree[i]
                i -= i & -i
            return s

        def add(self, i, x=1):
            # i==0 はだめ => 全部+1するとか
            while i <= self.size:
                self.tree[i] += x
                i += i & -i
            return

        def search(self, x):
            # 二分探索。和がx以上となる最小のインデックス(>= 1)を返す
            # maspyさんの参考　よくわかってない
            i = 0
            s = 0
            step = 1 << ((self.size).bit_length() - 1)
            while step:
                if i + step <= self.size and s + self.tree[i + step] < x:
                    i += step
                    s += self.tree[i]
                step >>= 1
            return i + 1

        def debug(self, k):
            return [self.sum(i) for i in range(k)]

    N = I()
    P = LI()
    Order = [[i+1] for i in range(N)]
    for i,p in enumerate(P):
        Order[i].append(p)
    Order.sort(key=lambda x:x[1],reverse=True)
    #print(Order)
    ans = 0
    bit = Bit(N+2)

    for i,p in Order:
        L = bit.sum(i)
        R = bit.sum(N)-L
        bit.add(i)
        l0, l1, r0, r1 = 0, 0, N+1, N+1
        if L>=2:
            l0 = bit.search(L-1)
        if L>=1:
            l1 = bit.search(L)
        if R>=1:
            r0 = bit.search(L+2)
        if R>=2:
            r1 = bit.search(L+3)
        #print(L,R)
        #print(l0,l1,r0,r1)
        #print(bit.debug(N+2))
        cnt = 0
        if l1>0:
            cnt += (l1-l0)*(r0-i)
        if r0>0:
            cnt += (i-l1)*(r1-r0)
        ans += cnt * p
        #print(ans)
    print(ans)
    return

def examF():
    def bfs(N, S):
        used = [False] * (1<<N)
        used[0] = True
        for n in range(N):
            cur = deque()
            rem = 1<<n
            for i in range(1<<N):
                s = S[i]
                if used[i]:
                    cur.append(s)
                elif cur and cur[0] > s:
                    cur.popleft()
                    used[i] = True
                    rem -= 1
                    if rem == 0:
                        break
            if rem > 0:
                #print(cur,used)
                return 'No'
        return 'Yes'
    N = I()
    S = LI()
    S.sort(reverse=True)
    #print(S)
    ans = bfs(N,S)
    print(ans)
    return


import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    examF()

"""
5
4 3 5 3 1 2 7 8 7 4 6 3 7 2 3 6 2 7 3 2 6 7 3 4 6 6 3 4 2 5 2 3

"""

Submission status: Accepted

Solution code:
class MultisetBIT:
    """
    最大値が小さい数について、その重複を許した集合を管理する。
    最大値 maxvalue を受け取り、[0, maxvalue] を管理する。
    counter は辞書型かリスト型で、counter[i] が i の個数を持つことを仮定する。
    counter が与えられなかった場合は、全て個数 0 で初期化される。
    基本的に閉区間で管理する。
    内部では受け取った数を +1 したものをindexとして持っているので注意。
    """

    __slots__ = ["n", "k", "data"]

    def __init__(self, maxvalue, counter = None):
        self.n = maxvalue + 1
        self.k = 1 << ((self.n + 1).bit_length() - 1)
        self.data = [0] * (self.n + 1)
        if counter is not None:
            self.update(counter)
        
    def update(self, counter):
        """
        counter を受け取って、それを反映させる。
        counter は辞書型かリスト型で、counter[i] が i の個数を持つことを仮定する。(0 <= i <= maxvalue)
        計算量は、n を要素の最大値として、 O(n) となる。
        """
        if isinstance(counter, list):
            self.data = [0] + counter + [0] * (self.n - len(counter))
        else:
            self.data = [0] * (self.n + 1)
            for k, v in counter.items():
                self.data[k + 1] = v
        for i in range(1, self.n + 1):
            if i + (i & -i) <= self.n:
                self.data[i + (i & -i)] += self.data[i]

    def add(self, value):
        """
        与えられた引数 value (0 <= value <= maxvalue) を Multiset に加える。
        計算量は、n を要素の最大値として、 O(log n) となる。
        """
        value += 1
        while value <= self.n:
            self.data[value] += 1
            value += value & -value

    def pop(self, value):
        """
        Multiset から与えられた引数 value (0 <= value <= maxvalue) を取り除く。
        与えられた引数が Multiset に入っているかのチェックは行わなず、
        単にその個数を 1 減らすだけなので注意。
        計算量は、n を要素の最大値として、 O(log n) となる。
        """
        value += 1
        while value <= self.n:
            self.data[value] -= 1
            value += value & -value

    def count_le(self, value):
        """
        Multiset 内の要素 elem のうち、0 <= elem <= value を満たすものを数える。
        計算量は、n を要素の最大値として、 O(log n) となる。
        value は value <= maxvalue を満たす必要がある。
        """
        value += 1
        ret = 0
        while value > 0:
            ret += self.data[value]
            value -= value & -value
        return ret

    def count(self, first, last):
        """
        Multiset 内の要素 elem のうち、first <= elem <= last を満たすものを数える。
        計算量は、n を要素の最大値として、 O(log n) となる。
        0 <= first <= last <= max_value が必要。
        """
        last += 1
        ret = 0
        while first < last:
            ret += self.data[last]
            last -= last & -last
        while last < first:
            ret -= self.data[first]
            first -= first & -first
        return ret

    def __getitem__(self, index):
        if isinstance(index, slice):
            return self.count(index.start, index.stop - 1)
        else:
            return self.count(index, index)

    def bisect(self, count):
        """
        Multiset 内の要素 elem のうち、count <= count_le(elem) を満たす最小のelemを返す。
        計算量は、n を要素の最大値として、 O(log n) となる。
        """
        ret = 0
        k = self.k
        while k > 0:
            if ret + k <= self.n and self.data[ret + k] < count:
                count -= self.data[ret + k]
                ret += k
            k //= 2
        return ret

    def lower_bound(self, value):
        """
        Multiset 内の要素 elem のうち、value <= elem を満たす最小のelemを返す。
        そのような elem が存在しない場合は maxvalue + 1 を返す。
        計算量は、n を要素の最大値として、 O(log n) となる。
        """
        return self.bisect(self.count_le(value - 1) + 1)

    def upper_bound(self, value):
        """
        Multiset 内の要素 elem のうち、value < elem を満たす最小のelemを返す。
        そのような elem が存在しない場合は maxvalue + 1 を返す。
        計算量は、n を要素の最大値として、 O(log n) となる。
        """
        return self.bisect(self.count_le(value) + 1)

#"""
N = int(input())
S_list = sorted(map(int, input().split()), reverse=True)
"""
N = 18
cs = [1, 18, 153, 816, 3060, 8568, 18564, 31824, 43758, 48620, 43758, 31824, 18564, 8568, 3060, 816, 153, 18, 1]
S_list = []
for i, c in enumerate(cs):
	S_list += [20 - i] * c
#"""

ans_tree = [0] * ((2 ** N) * 2)
ms = MultisetBIT((2 ** N) * 2)
ms.add(1)
prev_S = 0
prev_elem = 0
for S in S_list:
    if prev_S != S:
        prev_elem = 0
    elem = ms.lower_bound(prev_elem)
    while elem != ((2 ** N) * 2 + 1) and ans_tree[elem // 2] == S:
        elem = ms.upper_bound(elem)
    
    if elem == ((2 ** N) * 2 + 1):
        print("No")
        exit()

    prev_S = S
    prev_elem = elem
    ms.pop(elem)
    ans_tree[elem] = S
    elem *= 2
    while elem < 2 ** N * 2:
        ans_tree[elem] = S
        ms.add(elem + 1)
        elem *= 2
    

print("Yes")
# print(ans_tree)

Submission status: Accepted

Solution code:
class BinaryIndexTree:  # 1-indexed
    def __init__(self, N):
        """
        INPUT
        N [int] -> 全部0で初期化
        N [list] -> そのまま初期化
        """
        if isinstance(N, int):
            self.N = N
            self.depth = N.bit_length()
            self.tree = [0] * (N + 1)
            self.elem = [0] * (N + 1)
        elif isinstance(N, list):
            self.N = len(N)
            self.depth = self.N.bit_length()
            self.tree = [0] + N
            self.elem = [0] + N
            self._init()
        else:
            raise "INVALID INPUT: input must be int or list"

    def _init(self):
        size = self.N
        for i in range(1, self.N):
            if i + (i & -i) > size:
                continue
            self.tree[i + (i & -i)] += self.tree[i]

    def add(self, i, x):
        self.elem[i] += x
        while i <= self.N:
            self.tree[i] += x
            i += i & -i

    def sum(self, i):
        res = 0
        while i > 0:
            res += self.tree[i]
            i -= i & -i
        return res

    def lower_bound(self, val):
        if val <= 0:
            return 0
        i = 0
        k = 1 << self.depth
        while k:
            if i + k <= self.N and self.tree[i + k] < val:
                val -= self.tree[i + k]
                i += k
            k >>= 1
        return i + 1


N = int(input())
A = list(map(int, input().split()))
atoi = {a: i+1 for i, a in enumerate(sorted(set(A)))}

bit = BinaryIndexTree(len(atoi) + 5)

for a in A:
    i = atoi[a]
    bit.add(i, 1)


slime = []

p = bit.lower_bound(1 << N)
slime.append(p)
bit.add(p, -1)

for _ in range(N):
    next_slime = []
    for s in slime:
        tot = bit.sum(s - 1)
        p = bit.lower_bound(tot)
        if p == 0:
            print("No")
            exit()
        next_slime.append(p)
        bit.add(p, -1)
    slime += next_slime
print("Yes")