Do you know the story about the three musketeers? Anyway, you must help them now.

Richelimakieu is a cardinal in the city of Bearis. He found three brave warriors and called them the three musketeers. Athos has strength *a*, Borthos strength *b*, and Caramis has strength *c*.

The year 2015 is almost over and there are still *n* criminals to be defeated. The *i*-th criminal has strength *t*<sub class="lower-index">*i*</sub>. It's hard to defeat strong criminals — maybe musketeers will have to fight together to achieve it.

Richelimakieu will coordinate musketeers' actions. In each hour each musketeer can either do nothing or be assigned to one criminal. Two or three musketeers can be assigned to the same criminal and then their strengths are summed up. A criminal can be defeated in exactly one hour (also if two or three musketeers fight him). Richelimakieu can't allow the situation where a criminal has strength bigger than the sum of strengths of musketeers fighting him — a criminal would win then!

In other words, there are three ways to defeat a criminal.
 -  A musketeer of the strength *x* in one hour can defeat a criminal of the strength not greater than *x*. So, for example Athos in one hour can defeat criminal *i* only if *t*<sub class="lower-index">*i*</sub> ≤ *a*. -  Two musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of strengths of these two musketeers. So, for example Athos and Caramis in one hour can defeat criminal *i* only if *t*<sub class="lower-index">*i*</sub> ≤ *a* + *c*. Note that the third remaining musketeer can either do nothing or fight some other criminal. -  Similarly, all three musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of musketeers' strengths, i.e. *t*<sub class="lower-index">*i*</sub> ≤ *a* + *b* + *c*. 
Richelimakieu doesn't want musketeers to fight during the New Year's Eve. Thus, he must coordinate their actions in order to minimize the number of hours till all criminals will be defeated.

Find the minimum number of hours to defeat all criminals. If musketeers can't defeat them all then print "-1" (without the quotes) instead.
The first line of the input contains a single integer *n* (1 ≤ *n* ≤ 200 000) — the number of criminals.

The second line contains three integers *a*, *b* and *c* (1 ≤ *a*, *b*, *c* ≤ 10<sup class="upper-index">8</sup>) — strengths of musketeers.

The third line contains *n* integers *t*<sub class="lower-index">1</sub>, *t*<sub class="lower-index">2</sub>, ..., *t*<sub class="lower-index">*n*</sub> (1 ≤ *t*<sub class="lower-index">*i*</sub> ≤ 10<sup class="upper-index">8</sup>) — strengths of criminals.
In the first sample Athos has strength 10, Borthos 20, and Caramis 30. They can defeat all criminals in two hours:
 -  Borthos and Caramis should together fight a criminal with strength 50. In the same hour Athos can fight one of four criminals with strength 1. -  There are three criminals left, each with strength 1. Each musketeer can fight one criminal in the second hour. 
In the second sample all three musketeers must together fight a criminal with strength 51. It takes one hour. In the second hour they can fight separately, each with one criminal. In the third hour one criminal is left and any of musketeers can fight him.
5
10 20 30
1 1 1 1 50
2
5
10 20 30
1 1 1 1 51
3
7
30 20 10
34 19 50 33 88 15 20
-1
6
10 5 10
10 9 5 25 20 5
3
9
10 20 30
5 5 5 5 5 5 45 45 45
4
3
1 1 1
2 2 2
3
3
2 2 2
1 1 1
1
20
43 36 6
6 49 22 40 17 48 44 19 26 38 23 2 19 31 48 25 11 2 6 4
8
15
3 46 35
16 34 37 33 47 4 3 36 20 43 17 2 24 10 30
7
30
34938093 71279712 25853338
29827587 21741565 52179990 30235076 83272806 10815432 98887688 94542207 99870240 97586453 21739186 30460781 75347784 50711354 12162179 74306503 97398492 88466481 52489587 67579359 53177356 75077523 86044366 14405531 73916272 78242091 49321886 41937821 89258359 51438752
18
5
85660180 78921313 51382024
32512548 57103200 41738413 42188816 57569714
2
1
1 1 1
1
1
1
1 1 1
100000000
-1
1
100000000 100000000 100000000
1
1
1
100000000 100000000 100000000
100000000
1
4
6 7 8
8 8 8 12
2
from collections import OrderedDict
from collections import deque
import time
import random
import sys
import re 

def sizeof(t):
    return sys.getsizeof(t)

def pr(x):
    print(x)

def ti():
    return time.time()

#Function profiler. Sorting options: 0-by call number, 1-by function inner time, 2-by function cumulative time.
def profile(s,sort=1):
    import cProfile
    cProfile.run(s,sort=sort)

#Use @initializer wrapper. Checks for defaults existence. Why do we need to go in reverse direction? 
#How much slower it is than usual init? 
from functools import wraps
import inspect

def inize(fun):
    names, varargs, keywords, defaults = inspect.getargspec(fun)
    @wraps(fun)
    def wrapper(self, *args, **kargs):
        self.inited=False
        for name, arg in list(zip(names[1:], args)) + list(kargs.items()):
            setattr(self, name, arg)
        
        if defaults:
            for i in range(len(defaults)):
                index = -(i + 1)
                if not hasattr(self, names[index]):
                    setattr(self, names[index], defaults[index])
        fun(self, *args, **kargs)
        self.inited=True
    return wrapper

#To avoid problems with default empty lists.
def denone(fun):
    def wrap(*args,**kws):
        largs=inspect.getargspec(fun)[0]
        if largs[-1] not in kws and len(args)<len(largs): kws[largs[-1]]=[]
        return fun(*args, **kws)
    return wrap

def lfy(f):
    def wrap(*a):
        return list(f(*a))
    return wrap


def fread(s):
    return open(s,'r').read()

def hardread(s):
     return open(s,'r',encoding="utf8").read()

def fwrite(f,s):
    return open(f,'w',encoding="utf8").write(s)

#Helper functions zone. 

def tel(n=5):
    return [i+1 for i in range(n)]

def tel2(n=4,m=None):
    if m==None: m=n
    return [[i*m+j+1 for j in range(m)] for i in range(n)]

def tels(n=5):
    return 'abcde'*2

def abc(n):
    return list(map(chr, range(97, 123)))[n]


'''Operations'''

def lflat2(l):
    if ist(l[0], list): return [x for y in l for x in y]
    else: return l
    
def lflat(l):
    return lflat2(l)

def lflat(l):
    nl=[]
    for x in l:
        if (isiter(x)): 
            nl+=lflat(x) 
        else: 
            nl.append(x)
    return nl

def ist(o,t):
    return isinstance(o,t)

def antinone(l):
    if l==None: return []
    else: return l
    
def getl(f):
    return f().split()

def getint(f):
    return int(f())

def getints(s):
    return lm(int, s.split())

def stoints(s):
    return lm(int, s.split())

def enum(l):
    return enumerate(l)

def sign(x):
    if x>0: return 1
    if x<0: return -1
    return 0

global la
la={
    '^': lambda x,y:x**y,
    '**':lambda x,y:x**y,
    '+': lambda x,y:x+y,
    '-': lambda x,y:x-y,
    '*': lambda x,y:x*y,
    '/': lambda x,y:x/y,
    '//': lambda x,y:x//y,
    '%': lambda x,y:x%y,
    '1': lambda x,y:x,
    '2': lambda x,y:y,
    '>': lambda x,y:x>y,
    '=>':lambda x,y:x>=y,
    '<': lambda x,y:x<y,
    '<=': lambda x,y:x<=y,
    '!=': lambda x,y:x!=y,
    '==': lambda x,y:x==y,
    'in': lambda x,y:x in y,
    'nin': lambda x,y:x not in y,
    'and': lambda x,y:x and y,
    'or': lambda x,y:x or y,

}


#Shortcut-functions processor. Allow fixing of the second arg. 
def tof(f,a2=None):
    if ist(f,str): f=la[f]
    return f if not a2 else lambda x:f(x,a2)

def isiter(o):
    try:
        iterator = iter(o)
    except TypeError:
        return 0
    else:
        return 1

def isarray(o):
    if isiter(o) and not ist(o,str): return 1
    else: return 0    

def lm(f,*l):
    f=tof(f)
    return list(map(f,*l))

#Multifunction
def mf(f,*l):
    return lm(f,l)

def fitem(i=0):
    return lambda x:x[i]

fself=lambda x:x

def lf(l,f):
    return [x for x in l if f(x)]


def lzip(*l):
    return list(zip(*l))

#fzip('+', [1,2,3])=6. Problem: list doesn't change? You shouldn't copy it, choose indeces instead. 
#Note! It takes list of arguments, not tuple!
def fzip(f,l):
    f=tof(f)
    for i in range(1,len(l)):
        l[i]=f(l[i-1],l[i])
    return l[-1]
        
def allwith(s,l):
    return [x for x in l if s in x]

class Op:  
    def __init__ (self,l=None):
        self.l=l
    
    def __add__(self,s):
        return self.act('+',s)
    
    def __sub__(self,s):
        return self.act('-',s)
    
    def __mul__(self,s):
        return self.act('*',s)
    
    def __truediv__(self,s):
        return self.act('/',s)
    
    def __pow__(self,s):
        return self.act('**',s)
    
    def __lt__(self,s):
        return self.act('<',s)
        
    def __gt__(self,s):
        return self.act('>',s)
        
    def __le__(self,s):
        return self.act('<=',s)
        
    def __ge__(self,s):
        return self.act('>=',s)
    
    def __eq__(self,s):
        op='in' if isiter(s) else '=='
        return self.act(op,s)
        
    def __ne__(self,s):
        op='nin' if isiter(s) else '!='
        return self.act(op,s)

class oneof(Op): 
    def act(self,op,s):
        l=[tof(op)(x,s) for x in self.l]
        return fzip('or',l)

class allof(Op):   
    def act(self,op,s):
        l=[tof(op)(x,s) for x in self.l]
        return fzip('and',l)
        
class lif(Op):
    @inize
    def __init__(c,l,key=fself): pass
    
    #key acts on values before filtering. 
    def act(self,op,y):
        return lf(self.l, lambda x:tof(op)(self.key(x),y))   
    
#Super lambda. But what if there are several variables? No complex statements lik X**2+10?
class X(Op):
    def act(c,op,y):
        return tof(op,y)

X=X()

#Eg lop(l)*3
class lop(Op):
    def act(self,op,y):
        f=tof(op)
        return [f(x,y) for x in self.l]

'''Dicts and lists'''    

#Transpose table.
def ltrans(l):
    return [[x[k] for x in l] for k in range(0,len(l[0]))]

class D(dict):
    def __init__(c,d):
        dict.__init__(c,d)
        for x in d:
            setattr(c,x,d[x])  
        
    def __setattr__(c,x,v):
        c.__dict__[x]=v
        c[x]=v
        
#New array with specific dimensions. 
def lnew(*n,fill=0):
    l=[]
    for i in range(n[0]):
        if len(n)>1: l.append(lnew(*n[1:],fill=fill))
        else: l.append(fill)
    return l

def lsort(l,rev=1,key=fself):
    return sorted(l,reverse=rev,key=key)
    
def firstFalse(l,cond):
    for x in l:
        if not cond(x): return x
    return None

#What about use of external variable, does it first looks in context of outer function? 
#If so, then why can't you use ext-variables in body? Cause it's compilator-level error. 
def firstTrue(l,cond):
    for x in l:
        if cond(x): return x
    return None

def fcount(f):
    t=0
    while 1:
        t+=1
        step=f()
        if not step: break
    return t

#Fast dict from list. Works for words list to, cause maintains unique keys.
#Problem with empty list, binded to function. 
def dnew(l, fill=0):
    d={}
    for x in l: d[x]=fill
    return d

def dlnew(l):
    d={}
    for x in l: d[x]=[]
    return d

def odnew(l=None, fill=0):
    d=OrderedDict()
    if not l: return d
    
    for x in l: d[x]=fill
    return d

def odlnew(l=None):
    d=OrderedDict()
    if not l: return d
    
    for x in l: d[x]=[]
    return d

def od(l):
    return OrderedDict(l)

def odit(d,i):
    return d[list(d)[i]]

#Enumerated keys. 
def ekeys(d):
    return enum(list(d))

def dfill(d,fill):
    for x in d: d[x]=fill
    return d

def dtol(d): 
    return list(d.items())

def dvals(d):
    return list(d.values())

#Dsort by key. 
def dksort(d,rev=1):
    l=sorted(dtol(d),reverse=rev)
    return OrderedDict(l)

def dvsort(d,rev=1):
    l=sorted(dtol(d),reverse=rev,key=lambda x:x[1])
    return OrderedDict(l)
    

def combzip(l1,l2):
    return [(x,y) for x in l1 for y in l2]

#Place numbers in ascending order. Maybe better to use yield?  
def comb(state,k,n,l):
    p=len(state)
    if p==k: l.append(lm(int,state))
    else:
        prev=int(state[-1]) if state!=[] else -1
        for x in range(prev+1,n-k+p+1):
            comb(state+[x],k,n,l)
        
def combs(k,n):
    l=[]
    comb([],k,n,l)
    return l

def mapfilt(l,lf):
    return [x for i,x in enum(l) if lf[i]]

def lcombs(l,k):
    return [[l[i] for i in x] for x in combs(k,len(l))]

def lcomb(state,k,l,lbase):
    p=len(state)
    if p==k: l.append(lm(int,state))
    else:
        for x in lbase: lcomb(state+[x],k,l,lbase)

def lprod(lbase,k):
    l=[]
    lcomb([],k,l,lbase)
    return l

from itertools import product
@lfy
def lprod(l,k):
    return product(l,repeat=k)

def clad(c):
    return c.__dict__

def saferec(x):
    return 1/x if x!=0 else float('inf')

def safef(f,*x):
    try:
        return f(*x)
    except: return x
    
#Isn't possible!
def safev(x):
    try: return x
    except: return 'Hey!'
    return
   

#Real copy of dict to avoid iterating over changing structure
def dits(d):
    return list(d.items())

def fastd(l):
    return {x[0]:x[1:] for x in l}

def bifind(l,v,key=fself):
    #Note that assignemt to var makes it innermost local.
    def f(k,n):
        
        #Take the closest lower item. 
        if k>=n: 
            if key(l[k])>v and k!=0:k-=1
            return k
        
        i=(k+n)//2; x=key(l[i])
        
        if x==v: return i
        if v<x: return f(k,i-1)
        else: return f(i+1,n)
        
    n=len(l); k=0
    return l[f(k,n-1)]

def idict(l):
    return {x[0]:[i]+x[1:] for i,x in enum(l)}

#Table indexer. Takes table and column number. Returns sorted and indexed list based on this column.
def lindex(l,k):
    l.sort(key=lambda x:x[k],reverse=True)
    #Adds index column. list(x) operation handles one-dimensional table.
    for i,x in enumerate(l): l[i]=[i+1]+list(x)
    return l

def fitem(i):
    return lambda x:x[i]

def tabsort(l,k=0,rev=1):
    return sorted(l,key=fitem(k),reverse=rev)

def safedit(d,k,safe=0):
    return d[k] if k in d else safe
    

def antific(s):
    s=s.replace('”',"'")
    s=s.replace('“',"'")
    s=s.replace('…','...')
    return s

'''Classes'''
#Where the univeral class, which was target of so pride? You checked types of incoming objects.
#Based on this you choose: use __new__ or __init__. Inmutable vs mutable. 
#Needs new to initialize str or int children. No argument auto-inize here? 
class Str(str):
    def __new__(c,s,**kw):
        obj = str.__new__(c, s)
        
        for k in kw:
            obj.__dict__[k]=kw[k]
        return obj
    
class L(list):
    @inize
    def __init__(c,l=None,*a,**kw):
        if l==None: l=[]
        init(c,l)

#How to make empty class? Check for Nones? 
#Kill non-kw args to allow empty class? Or make spec-class? 
def Class(x,**kw):
    
    t=type(x)
    class X(t):
    
        def __new__(c,x,**kw):
            obj =t.__new__(c, x)

            for k in kw:
                obj.__dict__[k]=kw[k]
            return obj

        #Inize doesn't work for inner classes? 
        @inize
        def __init__(c,l=None,**kw):
            if t in [str, tuple, int, bool, float]: return c
            if l==None: l=[]
            init(c,l)
            
    return X(x,**kw)

#Class with dict of pars as it's value. No chance to get args order?  Note, it doesn't track par changes. 
#Track print function? So it even doesn't need init?  When object in container use __repr__?

def Eclass(**kw):
    class X(dict): 
        def __init__(c,**kw):
            for k in kw: c.__dict__[k]=kw[k]
            
        def __str__(c):
            return str(c.__dict__)
        
        def __repr__(c):
            return str(c.__dict__)
        
        def __bool__(c):
            return True
            
    return X(**kw)

def getpar(c):
    return c.__class__.__bases__[0]

#Would be problem with grandfather class in vertical chain of calls.  
#That's why we create spec variable to track class in this multi-level process.
def autoclass(f):
    def wrap(c,*args): 
        #Note that _par is class, not instance, that's why getpar doesn't work there.
        par=c._par.__bases__[0] if '_par' in c.__dict__ else getpar(c)
        c._par=par
        f(c,*args)
        #Don't forget to kill variable at the end.
        if '_par' in c.__dict__: del(c._par)
    return wrap

@autoclass
def init(c,*args):
    c._par.__init__(c,*args)
    
@autoclass
def parcall(c,*args):
    return c._par.__call__(c,*args)

@autoclass
def parset(c,*args):
    return c._par.__setattr__(c,*args)

def revbool(b):
    if b: b=False
    else: b=True
    return b

def fa(p,s):
    return re.findall(p,str(s),re.DOTALL)

#Doesn't take last part. 
def spliton(s,chars):
    return fa('.*?[{}]'.format(chars),s)
    
def skick(s,sub):
    return ''.join(s.split(sub))

def strip(s):
    return s.strip()

def sentsplit(s):
    s=skick(s,'\n')
    l=spliton(s,'.?!')
    l=lif(l)!=''
    l=lm(strip,l)
    
    return l

from inspect import getsource

def pr(x):
    return print(x)

def row(s):
    return s+'\n'

def coderows(s,gap):
    return ''.join([gap+row(x) for x in s.split(';')])

#Look at module where function is defined. Take space of this module. 
def fspace(f):
    mod=f.__module__
    if mod=='__main__': dglob=globals()
    else: dglob=globals()[mod].__dict__
    return dglob

def split(s,c):
    return s.split(c)

#Wish-lists: add auto-trailing of exception. Show value and go to fucntions where program breaks.
#Also problems with things like: p,s=l. And l.append. Changes var, but we don't see how.  
#And things like '+=' and '-='.
#Also problems with decorators and internal functions in general.
#Also no yield processing. Also recursion problems. 
#Also inline returns. 

#We safely can add var there. Even if it's overwritten function remembers initial value. 
#And function is defined near the value. 
ndeb=200
def deb(f,v=None,n=ndeb):
    #Allow one variable or list of vars.
    if ist(v,str): v=[v]
    #Get source of inner function. 
    try: source=getsource(f.__wrapped__)
    except: source=getsource(f)
        
    l=source.split('\n')
    s=''; first=1
    for i,x in enum(l):
        
        line=strip(x)
        #Avoid comments and decorators? Yes, but add them to source. So you don't block decorator accidentally.
        #But then it breaks work of analyzers? 
        if not line or line[0] in '#@': 
            s+=row(x)
            continue
        
        #Avoid looking into long dicts
        if ('{' in x and '}' not in x):
            s+=row(x)
            continue
        gap=fa(' *',x)[0]
        #Turn string into code string (with indent and \n symbol). Works on function source.
        fcode=lambda x:gap+row(x)
        showcode=lambda x: fcode('print("code:{}\\n")'.format(strip(x)))
        
        #Print function name if it's a first inner line.
        if first and not line.startswith('def '): 
            first=0
            s+=fcode('print("Function: {}")'.format(f.__name__))
            #Print function values. Good for recursion. 
            s+=fcode('print(getargvalues(stack()[0][0]).locals,"\\n")')
            #Add f to source, to use it later. 
            s+=fcode('fcut=lambda x:str(x)[:{}]'.format(n))
        
        kwords=('for ','if ','else:','try:','except:','finally:')
        if any([strip(x).startswith(kw) for kw in kwords]):
            #Don't forget that slicing has it too, like "if x[1:]>3: y=x[1:]".
            bef,aft=x.split(':')
            if strip(aft)!='':
                s+=row(bef+':')
                #Don't forget to increase gap and strip new line.
                gap+=' '*4; x=gap+strip(aft)
            
        
        lvar=fa('(\w+)=[^=]',x)
        
        
        
        #Check if vars in debug vars? Check for none to allow giving v=[] as to show only return values. 
        #i>0 to avoid looking at default values of function. Better to check explicitly. Problem with inner f?
        if lvar and not line.startswith('def ') and (v==None or lvar[0] in v):
            var=lvar[0]

            #We can't use it cause x is var name, not value. deb runs before function itself. 
            #fcut=lambda x:str(x)[:n]
            
            #String for prev calculation. Don't override native prevs. Use _.
            sprev=coderows('try: _prev={};except: _prev="empty"'.format(var),gap)
            #Add prev and f calculation. 
            s+=sprev+row(x)
            #Show prev and next. Escape \n, so it wouldn't split function code.  
            s+=fcode('print("{0}:",fcut(_prev),"\\n->",fcut({0}))'.format(var))
            #Show function. We could have print it outside of function? 
            #No it should be activated when we go there, not when we replace the function. 
            s+=showcode(x)
        else: 
            #What function sends us? 
            if line.startswith('return '):
                #Dont' forget to use '+', so it would capture at least something. 
                #Use any sym to allow for list-generator. Allow any number of space betw return and value. 
                res=fa('return[ ]+(.+)',x)[0]
                s+=fcode('print("Returns",{})'.format(res))
                s+=showcode(x)
            s+=row(x)
        #Note that '\t' didn't work there. We use ' '*4. Print function
        #if strip(x)[:4]=='def ': s+=gap+' '*4+'print("Function: {}\\n")\n'.format(f.__name__)
        
        
 
    #Deals with functions from other modules. 
    #Takes values from global scope, uses it's own local namespace. Good to not pollute global one. 
    #Problem: wouldn't work for debug of inner function. Should use some temp variables? 
    #Maybe some hacks with namespace containers. Actually we make temp change to global vars. 
    
    #print(source)
    #print(s)
    
    #You should create dict for local namespace before hand?
    d={}; exec(s,fspace(f),d)
    return d[f.__name__]

#Deep deb. How can we place kw arguments without redefenition of defaults? Was solved with global constants? 
#Works bad with decorated inner functions? 
#Add ability to work with several functions?
from inspect import currentframe, getframeinfo, getouterframes, stack, getargvalues
def ddeb(f0,*a,f=None, v=None,nodeb=False, n=ndeb, prof=0):
    if nodeb: 
        if not prof: return f0(*a)
       
        
        #Doesn't work with local vars? Turn them into global format? 
        else: 
            #Problem: overrides quotes around str. Add double quotes eveywhere?
            s=','.join(lm(lambda x:'"{}"'.format(x),a))
            s='{0}({1})'.format(f0.__name__,s)
            print(s)
            return profile(s,prof)
    #Allow for shallow functions. Replace namespace anyway for recursive reasons. 
    if f==None:
        f=f0
        f0=deb(f0,v=v,n=n)
        
    if not ist(f,list): f=[f]
    for x in f:
        name=x.__name__
        
        #Problem: how to restore the namespace for list? Go througth this procedure again? 
        d=fspace(x)
        #Doesn't if do it twice for main function? No, f is before deb-processing. 
        d[name]=deb(x,v=v,n=n)
    
    #Catch exception, but restore namespace afterwards.
    try: print('Full result:',f0(*a))
    finally:
        for x in f:
            name=x.__name__
            fspace(x)[name]=x
            
#Problem: shows results in chaotic form, not by length growth. 
@lfy
def allcombs(l):
    n=len(l); v=2**n
    for x in range(0,v):
        #Problem: removes leading zeroes. Add them explicitly.
        x=bin(x)[2:]; x='0'*(n-len(x))+x
        yield mapfilt(l,lm(int,x))
    pass

@lfy
def allcombs(l):
    #To make trivial combs;
    if ist(l,int): l=range(l)
    
    res=[] 
    for k in range(1,len(l)+1):
        res+=lcombs(l,k)
    return res

#Distribute values by tiers or segments. Should go from highest to lowest. Has max, but no min. 
#So how result will look? Dict of tiers with values? 
def layerfy(l,d):
    l=lsort(l)
    if l[0]>odit(d,0): return None
    i=0; nd=odlnew(d)
    for j,k in ekeys(d):
        while (i<len(l)) and (j+1==len(d) or (l[i]>odit(d,j+1))):
            nd[k].append(l[i]); i+=1
    return nd
            

#Kills all groups weaker than smaller groups: they are inefficient. Sorted by strength. 
def getstrongs(B):
    #Maybe it's easier to make all ops on lists and then turn to od? 
    B=od(lsort(dtol(B),key=lambda x:(x[1],-len(x[0]))))
    
    nl=[]; kmax=len(B)
    #It's easy to deal with strictly decreasing list. What when values are same? Presort list by keys length. 
    for key in list(B): 
        k=len(key)
        if k>kmax: del(B[key])
        if k<kmax: kmax=k
    return B

def firstFalse(l,cond):
    for x in l:
        if not cond(x): return x
    return None

#What about use of external variable, does it first looks in context of outer function? 
#If so, then why can't you use ext-variables in body? Cause it's compilator-level error. 
def firstTrue(l,cond):
    for x in l:
        if cond(x): return x
    return None

def fcount(f):
    t=0
    while 1:
        t+=1
        step=f()
        if not step: break
    return t

def nextgroup(lg,mbus):
    for g in x.lg: 
        if mbus.intersection(g.k) or g.n==0: continue
        return g
    else: return 0

def nextstep(M,B1,B):
    mbus=set(); lfail=[]; step=[] 
    for x in M:
        if x.i in mbus: continue
        #g=nextgroup(x.lg,mbus)
        
        ishelp=''
        g=firstFalse(x.lg, lambda g: mbus.intersection(g.k) or g.n==0)
        #We don't update busy for helpers.
        if g: mbus.update(g.k)
        if not g: 
            #Why it worked before and doesn't work now? 
            g=firstTrue(B1[x.i:], lambda g: g.n>0)
            ishelp=str(x.i)+' helps'
        if not g: 
            lfail.append(x.v); continue
        
        g.n-=1; step.append((ishelp,[g.k,g.n]))
        
    if len(lfail)==2: 
        g=firstTrue(B, lambda g: g.n>0 and g.v<=sum(lfail))
        if g: g.n-=1; step.append(('grouphelp', [g.k,g.n]))
        
    #print(step)
    if all([x.n==0 for x in B]): return None
        
    return step

#Problem: polution of namespace with lm, lc. 
#Type choice. Why do you need od, instead of lclass? For layerfy? Also easier to del keys. 
#Can you make M and B sets? No, they need order. 

def muskplan(M,C): 
    M=lsort(M,rev=0)
    #Get musks groups. 
    l=allcombs(len(M))
    
    #B ex for 10,20,30. (0,1):30, (0,1,2):60. 
    B=od([tuple(x),sum([M[i] for i in x])] for x in l)
    B=getstrongs(B)
    d=layerfy(C,B)
    
    for i,x in enum(M): M[i]=Eclass(i=i,v=x,lg=[])
    for x in B: 
        v=B[x]; n=len(d[x])
        B[x]=Eclass(k=x,v=v,n=n)
        for y in x: M[y].lg.append(B[x])
    B=dvals(B)
    
    #Reverse after all ops. But you would need real indeces while checking busy? Explicitly give name to M? 
    M=M[::-1]
    B1=B[-len(M):]
    t=fcount(lambda:nextstep(M,B1,B))
                
                
                
    
    return t
    return B
    
    
    
            
n=input()
M=input().split()
C=input().split()

print(muskplan(M,C))