Problem:
 Score : 300 points    Problem Statement You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N , respectively.  Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C . For that, you can use the following three kinds of magics any number:   Extension Magic: Consumes 1  MP (magic point). Choose one bamboo and increase its length by 1 .  Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1 .  Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)   At least how much MP is needed to achieve the objective?      Constraints  3 \leq N \leq 8  1 \leq C < B < A \leq 1000  1 \leq l_i \leq 1000  All values in input are integers.         Input Input is given from Standard Input in the following format:  N  A  B  C  l_1  l_2  :  l_N       Output Print the minimum amount of MP needed to achieve the objective.        Sample Input 1 5 100 90 80
98
40
30
21
80      Sample Output 1 23  We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80 . We already have a bamboo of length 80 , and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.   Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100 . (MP consumed: 2 )  Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70 . (MP consumed: 10 )  Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20 . (MP consumed: 1 )  Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90 . (MP consumed: 10 )        Sample Input 2 8 100 90 80
100
100
90
90
90
80
80
80      Sample Output 2 0  If we already have all bamboos of the desired lengths, the amount of MP needed is 0 . As seen here, we do not necessarily need to use all the bamboos.       Sample Input 3 8 1000 800 100
300
333
400
444
500
555
600
666      Sample Output 3 243

Solution (Python):
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i for _ in range(j)]




import itertools

N, *A = mi()
L = [ii() for _ in range(N)]
L_ = [L[i] for i in range(N)]
N_ = N

A = sorted(A)

tmp = [0] * 3
ans = float('inf')

for k in itertools.product([0,1], repeat=N_):
    N = sum(k)
    if N < 3:
        continue
    L = []
    for x in range(N_):
        if k[x]:
            L.append(L_[x]*k[x])
    
    sum_l = sum(L)

    for i in range(1, N+1):
        for koho_i in range(1, 2**i):
            for koho_j in range(1, 2**i):
                j = i
                
                if koho_i & koho_j:
                    continue
                
                tmp[0] = sum([L[x]*min((koho_i & 1<<x), 1) for x in range(i)])
                
                tmp[1] = sum([L[x]*min((koho_j & 1<<x), 1) for x in range(j)])
                tmp[2] = sum_l - tmp[0] - tmp[1]
                

                if 0 in tmp:
                    continue

                tmp = sorted(tmp)
                cost = (N-3) * 10 + sum([abs(tmp[x]-A[x]) for x in range(3)])
                
                    
                
                    
                ans = min(ans, cost)

print(ans)

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    inf=10**9
    n,*abc=MI()
    abc.sort()
    a,b,c=abc
    dp={(0,0,0):0}
    for _ in range(n):
        l=II()
        ndp={}
        for xyz,s in dp.items():
            ndp.setdefault(xyz,inf)
            ndp[xyz]=min(ndp[xyz],s)
            for i in range(3):
                nx=list(xyz)
                ns=s+10 if nx[i] else s
                nx[i]+=l
                t=tuple(sorted(nx))
                ndp.setdefault(t,inf)
                ndp[t]=min(ndp[t],ns)
            dp=ndp

    ans=inf
    for (x,y,z),s in dp.items():
        if x*y*z==0:continue
        cur=abs(x-a)+abs(y-b)+abs(z-c)+s
        ans=min(ans,cur)

    print(ans)

main()

Solution (Python):
from itertools import product
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    inf=10**16
    n,*abc=MI()
    ll=[II() for _ in range(n)]

    ans=inf
    for pp in product(range(4),repeat=n):
        ss=[0]*3
        cnt=[0]*3
        for l,p in zip(ll,pp):
            if p==3:continue
            ss[p]+=l
            cnt[p]+=1
        cur=0
        for i in range(3):
            if cnt[i]==0:
                cur=inf
                break
            cur+=(cnt[i]-1)*10+abs(abc[i]-ss[i])
        
        ans=min(ans,cur)

    print(ans)

main()

Solution (Python):
from sys import stdin

readline=stdin.readline
inf=10**9
n,a,b,c=map(int,readline().split())
l=[int(readline()) for _ in range(n)]

def dfs(now,x,y,z):
    if now==n:
        return abs(a-x)+abs(b-y)+abs(c-z)-30 if min(x,y,z)>0 else inf
    else:
        res1=dfs(now+1,x,y,z)
        res2=dfs(now+1,x+l[now],y,z)+10
        res3=dfs(now+1,x,y+l[now],z)+10
        res4=dfs(now+1,x,y,z+l[now])+10
        return min(res1,res2,res3,res4)

print(dfs(0,0,0,0))

Solution (Python):
n,a,b,c=map(int,input().split())
l=[int(input()) for _ in range(n)]
def func(g):
  if len(g[0])==0 or len(g[1])==0 or len(g[2])==0:return -1
  ret=0
  ret+=10*(len(g[0])-1)
  ret+=10*(len(g[1])-1)
  ret+=10*(len(g[2])-1)
  a_=sum([l[i] for i in g[0]])
  b_=sum([l[i] for i in g[1]])
  c_=sum([l[i] for i in g[2]])
  ret+=abs(a-a_)
  ret+=abs(b-b_)
  ret+=abs(c-c_)
  return ret
m=n*2
ans=pow(10,9)
for i in range(2**m):
  g=[[]for _ in range(4)]
  for j in range(n):
    g[(i//pow(4,j))%4].append(j)
  tmp=func(g)
  if tmp>=0:
    ans=min(ans,tmp)

print(ans)

Solution (Python):
def f(x):
    if len(x) == n:
        p.append(x)
    else:
        for i in S:
            f(x+[i])

n , a , b , c = map(int,input().split())
take = [int(input()) for i in range(n)]
S = [0,1,2,3]
p = []
f([])
ans = 10**9
for i in range(len(p)):
    sai = [0,0,0]
    cou = 0
    for j in range(n):
        if p[i][j] != 3:
            if sai[p[i][j]] == 0:
                cou -= 10
            sai[p[i][j]] += take[j]
            cou += 10
    sai.sort()
    if sai[0] == 0:
        continue
    cou += abs(sai[0]-c)+abs(sai[1]-b)+abs(sai[2]-a)
    ans = min(ans,cou)
    
print(ans)

Solution (Python):
from collections import defaultdict
from itertools import combinations, permutations
from operator import itemgetter
n, a, b, c, *L = map(int, open(0).read().split())
L.sort()
A = [a, b, c]
dicts = [defaultdict(lambda: 10**5) for _ in range(3)]
for i in range(n-2):
    for x in combinations(enumerate(L), i+1):
        k = tuple(i for i, l in x)
        v = sum(l for i, l in x)
        for d, x in zip(dicts, A):
            d[k] = min(d[k], abs(x-v) + 10*i)
scores = [sorted(d.items(), key=itemgetter(1)) for d in dicts]

ans = 10**5
for p1, p2, p3 in permutations(range(3)):
    k1, v1 = scores[p1][0]
    k1 = set(k1)
    for k2, v2 in scores[p2]:
        k2 = set(k2)
        if len(k1 & k2) == 0:
            break
    for k3, v3 in scores[p3]:
        k3 = set(k3)
        if len(k1 & k3) + len(k2 & k3) == 0:
            break
    ans = min(ans, sum([v1, v2, v3]))
print(ans)

Solution (Python):
n,a,b,c = map(int,input().split())
m = [a,b,c]
l = sorted([int(input()) for i in range(n)])

import itertools 
data = list(itertools.product(range(4), repeat = n))

ans = float('inf')
for d in data:
    x = [[] for i in range(4)]
    for i in range(n):
        x[d[i]].append(l[i])
    if len(x[0])<1 or len(x[1])<1 or len(x[2])<1:
        continue
    buf = 0
    for i in range(3):
        buf += 10*(len(x[i])-1)
        buf += abs(sum(x[i])-m[i])

    ans = min(ans,buf)
print(ans)

Solution (Python):

N,A,B,C = map(int, input().split())
bamboos = [int(input()) for _ in range(N)]

INF = float("inf")
ans = INF
def solve(idx, cnt_merge, a, b, c):

    if idx == N:
        if min(a,b,c) > 0:
            return abs(A - a) + abs(B - b) + abs(C - c) + 10 * (cnt_merge-3)
        else:
            return INF

    pa = solve(idx+1, cnt_merge+1, a+bamboos[idx], b, c)
    pb = solve(idx+1, cnt_merge+1, a, b+bamboos[idx], c)
    pc = solve(idx+1, cnt_merge+1, a, b, c+bamboos[idx])
    pn = solve(idx+1, cnt_merge, a, b, c)
    return min(pa, pb, pc, pn)


print(solve(0,0,0,0,0))

Solution (Python):

N,A,B,C = map(int, input().split())
bamboos = [int(input()) for _ in range(N)]

ans = float("inf")
def solve(lst, idx):
    global ans
    if idx == N:
        
        for i in range(3):
            if len(lst[i]) == 0:
                return

        
        pa = 10 * (len(lst[0])-1) + abs(A - sum(lst[0]))
        pb = 10 * (len(lst[1])-1) + abs(B - sum(lst[1]))
        pc = 10 * (len(lst[2])-1) + abs(C - sum(lst[2]))
        
        ans = min(ans, pa + pb + pc)
        
        return

    
    for i in range(4):
        nxt_lst = [lst[0][:], lst[1][:], lst[2][:], lst[3][:]]
        nxt_lst[i].append(bamboos[idx])
        
        
        solve(nxt_lst, idx+1)

empty_lst =  [[], [], [], []]   
solve(empty_lst, 0)
print(ans)

Solution (Python):
n,a,b,c = map(int,input().split())
t = [int(input()) for i in range(n)]
ans = float('inf')
for i in range(1<<(n*2)):
    tmp,cnt,a_t,b_t,c_t = i,0,0,0,0
    for j in range(n):
        if tmp&3==1:
            a_t+=t[j]
            if a_t!=t[j]: cnt+=10
        elif tmp&3==2:
            b_t+=t[j]
            if b_t!=t[j]: cnt+=10
        elif tmp&3==3:
            c_t+=t[j]
            if c_t!=t[j]: cnt+=10
        tmp >>= 2
    if a_t==0 or b_t==0 or c_t==0: continue
    tmp = abs(a-a_t)+abs(b-b_t)+abs(c-c_t)+cnt
    ans = min(ans,tmp)
print(ans)

Solution (Python):






from collections import deque



import bisect

n,A,B,C=map(int,input().split())
l=[int(input()) for _ in range(n)]
inf=10**9
def rec(i,a,b,c):
    if i==n:
        if not a or not b or not c:
            return inf
        return abs(A-a)+abs(B-b)+abs(C-c)
    res=rec(i+1,a,b,c)
    res=min(res,rec(i+1,a+l[i],b,c)+(10 if a else 0))
    res=min(res,rec(i+1,a,b+l[i],c)+(10 if b else 0))
    res=min(res,rec(i+1,a,b,c+l[i])+(10 if c else 0))

    return res
print(rec(0,0,0,0))

Solution (Python):
from itertools import product


def main():
    n, a, b, c = map(int, input().split())
    l = [int(input()) for _ in range(n)]
    ans = 10**4
    for p in product(range(4), repeat=n):
        abc = [[], [], []]
        for i, pi in enumerate(p):
            if pi > 0:
                abc[pi - 1].append(i)
        fl = False
        for i in abc:
            fl |= len(i) == 0
        if fl:
            continue
        cost = 0
        for i in range(3):
            cost += abs(sum(l[j] for j in abc[i]) - (a, b, c)[i]) + 10 * (len(abc[i]) - 1)
        ans = min(ans, cost)
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
N, A, B, C = list(map(int,input().split()))
l = [int(input()) for _ in range(N)]

def dfs(i, a, b, c):
    if i == N:
        if a and b and c:
            return abs(a - A) + abs(b - B) + abs(c - C)
        else:
            return 10 ** 9 + 7
    else:
        ret1 = dfs(i + 1, a + l[i], b, c) + 10
        ret2 = dfs(i + 1, a, b + l[i], c) + 10
        ret3 = dfs(i + 1, a, b, c + l[i]) + 10
        ret4 = dfs(i + 1, a, b, c)
        ret = min(ret1, ret2, ret3, ret4)
        return ret
    
ans = dfs(0, 0, 0, 0)
print(ans - 30)

Solution (Python):
n,a,b,c = map(int,input().split())
l = []
for i in range(n):
    l.append(int(input()))
mi = 10**18
aa = []
ba = []
ca = []
da = []
def dfs(ai,bi,ci,di,i):
    global mi
    if i == n:
        if len(ai) == 0 or len(bi) == 0 or len(ci) == 0:
            return mi
        tmp = 0
        if len(ai) > 1:
            tmp += 10 * (len(ai) - 1)
        if len(bi) > 1:
            tmp += 10 * (len(bi) - 1)
        if len(ci) > 1:
            tmp += 10 * (len(ci) - 1)
        tmp += abs(a - sum(ai))
        tmp += abs(b - sum(bi))
        tmp += abs(c - sum(ci))
        mi = min(mi,tmp)
        return mi
    else:
        return min(min(dfs(ai+[l[i]],bi,ci,di,i+1),dfs(ai,bi+[l[i]],ci,di,i+1)),min(dfs(ai,bi,ci+[l[i]],di,i+1),dfs(ai,bi,ci,di+[l[i]],i+1)))
print(dfs(aa,ba,ca,da,0))

Solution (Python):
def main():
  n, a, b, c = map(int, input().split())

  l = [int(input()) for i in range(n)]

  def test(i, x, y, z):
    if(i == n):
      if(x == 0 or y == 0 or z == 0):
        return float('inf')
      return abs(a - x) + abs(b - y) + abs(c - z)

    res = test(i + 1, x, y, z)

    res = min(res, (test(i + 1, x + l[i], y, z) + (0 if x == 0 else 10))) 
    res = min(res, (test(i + 1, x, y + l[i], z) + (0 if y == 0 else 10))) 
    res = min(res, (test(i + 1, x, y, z + l[i]) + (0 if z == 0 else 10))) 

    return res

  print(test(0, 0, 0, 0))

if __name__ == '__main__':
  main()

Solution (Python):





N, A, B, C = list(map(int, input().split()))
L = [int(input()) for _ in range(N)]


inf = 10**9


def dfs(cur, a, b, c):
    if cur == N:
        return abs(a - A) + abs(b - B) + abs(c - C) - 30 if min(a, b, c) > 0 else inf

    ret0 = dfs(cur + 1, a, b, c)
    ret1 = dfs(cur + 1, a + L[cur], b, c) + 10
    ret2 = dfs(cur + 1, a, b + L[cur], c) + 10
    ret3 = dfs(cur + 1, a, b, c + L[cur]) + 10

    return min(ret0, ret1, ret2, ret3)


print(dfs(0, 0, 0, 0))

Solution (Python):
n, a, b, c = map(int, input().split())
x = [int(input()) for _ in range(n)]

from itertools import permutations

def dfs(idx):
    if idx == n:
        return [[[], [], []]]

    ret = []
    for ll in dfs(idx + 1):
        ret.append(ll)

        for i in range(3):
            ll2 = [ll[0][:], ll[1][:], ll[2][:]]
            ll2[i].append(idx)
            ret.append(ll2)

    return ret

lists = dfs(0)

target = [a, b, c]

ans = float('inf')
for _lists in lists:
    if [] not in _lists:

        point = 0
        l = []
        for lis in _lists:
            l.append(sum([x[i] for i in lis]))
            point += 10 * (len(lis) - 1)

        for perm in permutations(l):
            point2 = point
            for i in range(3):
                point2 += abs(target[i] - perm[i])

            ans = min(point2, ans)

print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n,a,b,c=MI()
mn=inf
lis=[I() for i in range(n)]
for i in list(product([0,1,2,3],repeat=n)):
    x=[]
    y=[]
    z=[]
    for j in range(n):
        if i[j]==0:
            x.append(lis[j])
        elif i[j]==1:
            y.append(lis[j])
        elif i[j]==2:
            z.append(lis[j])
    if len(x)==0 or len(y)==0 or len(z)==0:
        ans=inf
    else:
        ans=abs(sum(x)-a)+10*(len(x)-1)+abs(sum(y)-b)+10*(len(y)-1)+abs(sum(z)-c)+10*(len(z)-1)
    
    if ans<mn:
        mn=ans
        X=x
        Y=y
        Z=z
print(mn)
'''print(X)
print(Y)
print(Z)
'''

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n,a,b,c=MI()
mn=inf
lis=[I() for i in range(n)]
for i in list(product([0,1,2,3],repeat=n)):
    x=[]
    y=[]
    z=[]
    for j in range(n):
        if i[j]==0:
            x.append(lis[j])
        elif i[j]==1:
            y.append(lis[j])
        elif i[j]==2:
            z.append(lis[j])
    if len(x)==0 or len(y)==0 or len(z)==0:
        ans=inf
    else:
        ans=abs(sum(x)-a)+10*(len(x)-1)+abs(sum(y)-b)+10*(len(y)-1)+abs(sum(z)-c)+10*(len(z)-1)
    
    if ans<mn:
        mn=ans
        X=x
        Y=y
        Z=z
print(mn)
'''print(X)
print(Y)
print(Z)
'''

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n,a,b,c=MI()
mn=inf
lis=[I() for i in range(n)]
for i in list(product([0,1,2,3],repeat=n)):
    x=[]
    y=[]
    z=[]
    for j in range(n):
        if i[j]==0:
            x.append(lis[j])
        elif i[j]==1:
            y.append(lis[j])
        elif i[j]==2:
            z.append(lis[j])
    if len(x)==0 or len(y)==0 or len(z)==0:
        ans=inf
    else:
        ans=abs(sum(x)-a)+10*(len(x)-1)+abs(sum(y)-b)+10*(len(y)-1)+abs(sum(z)-c)+10*(len(z)-1)
    
    if ans<mn:
        mn=ans
        X=x
        Y=y
        Z=z
print(mn)
'''print(X)
print(Y)
print(Z)
'''

Solution (Python):
from itertools import product
import bisect

N, A, B, C = map(int, input().split()) 
tl = [C,B,A]

ll = []
for _ in range(N):
    ll.append(int(input()))



ans = 10**8
ite = product(range(4),repeat=N)
for pattern in ite:
    bag = [[],[],[]]
    singles = []
    mp = 0
    for i, p in enumerate(pattern):
        if p == 3: singles.append(ll[i])
        else: bag[p].append(ll[i])
    
    zero_cnt = 0
    for b in bag:
        if not b: zero_cnt+=1
        else: mp += (len(b)-1)*10
    if not singles: zero_cnt+=1
    if zero_cnt >= 2: continue

    bamboos = []
    for b in bag:
        if b: bamboos.append(sum(b))
    for s in singles:
        bamboos.append(s)

    bamboos.sort()
    
    
    for t in tl:
        curr_min = 10000
        curr_min_i = 0
        for i, ba in enumerate(bamboos):
            if abs(ba - t) < curr_min:
                curr_min = abs(ba-t)
                curr_min_i = i
        mp += curr_min
        bamboos.pop(curr_min_i)

    ans = min(ans,mp)

print(ans)

Solution (Python):
from itertools import product
import bisect

N, A, B, C = map(int, input().split()) 
tl = [C,B,A]

ll = []
for _ in range(N):
    ll.append(int(input()))



ans = 10**8
ite = product(range(4),repeat=N)
for pattern in ite:
    bag = [[],[],[]]
    singles = []
    mp = 0
    for i, p in enumerate(pattern):
        if p == 3: singles.append(ll[i])
        else: bag[p].append(ll[i])
    
    zero_cnt = 0
    for b in bag:
        if not b: zero_cnt+=1
        else: mp += (len(b)-1)*10
    if not singles: zero_cnt+=1
    if zero_cnt >= 2: continue

    bamboos = []
    for b in bag:
        if b: bamboos.append(sum(b))
    for s in singles:
        bamboos.append(s)

    bamboos.sort()
    
    
    for t in tl:
        curr_min = 10000
        curr_min_i = 0
        for i, ba in enumerate(bamboos):
            if abs(ba - t) < curr_min:
                curr_min = abs(ba-t)
                curr_min_i = i
        mp += curr_min
        bamboos.pop(curr_min_i)

    ans = min(ans,mp)

print(ans)

Solution (Python):
n, a, b, c = map(int, input().split())
take = []

for i in range(n):
    t = int(input())
    take.append(t)

def Base_10_to_n(X, n):
    X_dumy = X
    out = ''
    while X_dumy>0:
        out = str(X_dumy%n)+out
        X_dumy = int(X_dumy/n)
    return out

def cal_cost(li, a):
    if li == []:
        return 10**12
    co = 0
    if len(li) == 1:
        co += abs(li[0] - a)
    else:
        co += abs(sum(li) - a)
        co += (len(li) - 1) * 10
    return co

min_cost = 10**12
for i in range(4**n):
    cost = 0
    num = Base_10_to_n(i, 4).zfill(n)
    for_A = []
    for_B = []
    for_C = []
    for j in range(n):
        if num[j] == '1':
            for_A.append(take[j])
        elif num[j] == '2':
            for_B.append(take[j])
        elif num[j] == '3':
            for_C.append(take[j])
    cost += cal_cost(for_A, a)
    cost += cal_cost(for_B, b)
    cost += cal_cost(for_C, c)
    if cost < min_cost:
        min_cost = cost

print(min_cost)

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
from collections import defaultdict
from collections import deque
from functools import lru_cache






MOD = 10**9+7
INF = float('inf')






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)



def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b:
        a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count




N,A,B,C = IL()
L = ILs(N)

def make_take(T,x,b):
  n = len(T)
  Tdic = DD(int)
  for t in T:
    Tdic[t] += 1
  if n == 0:
    return INF,T
  choose = 0
  number = 0
  for i in range(n):
    if (b>>i)&1 == 1:
      Tdic[T[i]] -= 1
      choose += T[i]
      number += 1
  MP = abs(choose-x)+(number-1)*10
  T = []
  for k,v in Tdic.items():
    T.extend([k]*v)
  return MP,T

MIN = INF
n1 = len(L)
for b1 in range(1,1<<n1):
  MP1,L1 = make_take(L,A,b1)
  n2 = len(L1)
  for b2 in range(1,1<<n2):
    MP2,L2 = make_take(L1,B,b2)
    n3 = len(L2)
    for b3 in range(1,1<<n3):
      MP3,L3 = make_take(L2,C,b3)
      MIN = min(MIN,MP1+MP2+MP3)
print(MIN)

Solution (Python):
import sys
sys.setrecursionlimit(500000)

N, A, B, C = map(int, input().split())
L = [int(input()) for i in range(N)]

kumi = []
abcx = ['A', 'B', 'C', 'X']

def dfs(arr: list):
    if len(arr) == N:
        kumi.append(arr[:])
        return
    for k in ['A', 'B', 'C', 'X']:
        arr.append(k)
        dfs(arr)
        arr.pop()

dfs([])

ans = float('inf')
for k in kumi:
    if set(k) & set(['A', 'B', 'C']) != set(['A', 'B', 'C']):
        continue
    tmp = 0
    a = 0
    b = 0
    c = 0
    for i in range(N):
        if k[i] == 'A':
            if a > 0:
                tmp += 10
            a += L[i]
        elif k[i] == 'B':
            if b > 0:
                tmp += 10
            b += L[i]
        elif k[i] == 'C':
            if c > 0:
                tmp += 10
            c += L[i]
    tmp += abs(A-a)
    tmp += abs(B-b)
    tmp += abs(C-c)
    ans = min(ans, tmp)

print(ans)

Solution (Python):


from collections import deque

n, a, b, c = map(int, input().split())
l = [int(input()) for _ in range(n)]

queue = deque([[0],[1],[2],[-1]]) 
ptns = [] 
 
while queue: 
    tmp = queue.popleft() 
    if len(tmp) == n: 
        ptns.append(tmp)
    elif len(tmp) < n: 
        w = tmp + [0] 
        x = tmp + [1] 
        y = tmp + [2] 
        z = tmp + [-1]
        queue += [w, x, y, z]  



ans = 10**9
for i in range(len(ptns)):
    if 0 not in ptns[i] or 1 not in ptns[i] or 2 not in ptns[i]:
        continue
    abc = [0, 0, 0, -30]
    for j in range(n):
        tmp = ptns[i][j]
        if tmp >= 0:
            abc[tmp] += l[j]
            abc[3] += 10
    mp = abc[3]
    mp += abs(abc[0] - a)
    mp += abs(abc[1] - b)
    mp += abs(abc[2] - c)
    ans = min(ans, mp)

print(ans)

'''


from collections import deque

n, a, b, c = map(int, input().split())
l = [int(input()) for _ in range(n)]

queue = deque([[0],[1],[2],[-1]])

ans = 10**9
while queue:
    tmp = queue.popleft()
    if len(tmp) == n:
        if 0 not in tmp or 1 not in tmp or 2 not in tmp:
            continue
        abc = [0, 0, 0, -30]
        for j in range(n):
            if tmp[j] >= 0:
                abc[tmp[j]] += l[j]
                abc[3] += 10
        mp = abc[3]
        mp += abs(abc[0] - a)
        mp += abs(abc[1] - b)
        mp += abs(abc[2] - c)
        ans = min(ans, mp)

    elif len(tmp) < n:
        w = tmp + [0]
        x = tmp + [1]
        y = tmp + [2]
        z = tmp + [-1]
        queue += [w, x, y, z]

print(ans)

'''

Solution (Python):

'''
from collections import deque

n, a, b, c = map(int, input().split())
l = [int(input()) for _ in range(n)]

queue = deque([[0],[1],[2],[-1]]) 
ptns = [] 
 
while queue: 
    tmp = queue.pop() 
    if len(tmp) == n: 
        ptns.append(tmp)
    elif len(tmp) < n: 
        w = tmp + [0] 
        x = tmp + [1] 
        y = tmp + [2] 
        z = tmp + [-1]
        queue += [w, x, y, z]  



ans = 10**9
for i in range(len(ptns)):
    if 0 not in ptns[i] or 1 not in ptns[i] or 2 not in ptns[i]:
        continue
    abc = [0, 0, 0, -30]
    for j in range(n):
        tmp = ptns[i][j]
        if tmp >= 0:
            abc[tmp] += l[j]
            abc[3] += 10
    mp = abc[3]
    mp += abs(abc[0] - a)
    mp += abs(abc[1] - b)
    mp += abs(abc[2] - c)
    ans = min(ans, mp)

print(ans)

'''


from collections import deque

n, a, b, c = map(int, input().split())
l = [int(input()) for _ in range(n)]

queue = deque([[0],[1],[2],[-1]])

ans = 10**9
while queue:
    tmp = queue.pop()
    if len(tmp) == n:
        if 0 not in tmp or 1 not in tmp or 2 not in tmp:
            continue
        abc = [0, 0, 0, -30]
        for j in range(n):
            if tmp[j] >= 0:
                abc[tmp[j]] += l[j]
                abc[3] += 10
        mp = abc[3]
        mp += abs(abc[0] - a)
        mp += abs(abc[1] - b)
        mp += abs(abc[2] - c)
        ans = min(ans, mp)

    elif len(tmp) < n:
        w = tmp + [0]
        x = tmp + [1]
        y = tmp + [2]
        z = tmp + [-1]
        queue += [w, x, y, z]

print(ans)

Solution (Python):


n, a, b, c = map(int, input().split())
l = [int(input()) for _ in range(n)]

stack = [[0],[1],[2],[-1]] 
ptns = [] 
 
while stack: 
    tmp = stack.pop() 
    if len(tmp) == n: 
        ptns.append(tmp)
    elif len(tmp) < n: 
        w = tmp + [0] 
        x = tmp + [1] 
        y = tmp + [2] 
        z = tmp + [-1]
        stack += [w, x, y, z]  



ans = 10**9
for i in range(len(ptns)):
    if 0 not in ptns[i] or 1 not in ptns[i] or 2 not in ptns[i]:
        continue
    abc = [0, 0, 0, -30]
    for j in range(n):
        tmp = ptns[i][j]
        if tmp >= 0:
            abc[tmp] += l[j]
            abc[3] += 10
    mp = abc[3]
    mp += abs(abc[0] - a)
    mp += abs(abc[1] - b)
    mp += abs(abc[2] - c)
    ans = min(ans, mp)

print(ans)

'''


n, a, b, c = map(int, input().split())
l = [int(input()) for _ in range(n)]

stack = [[0],[1],[2],[-1]]

ans = 10**9
while stack:
    tmp = stack.pop()
    if len(tmp) == n:
        if 0 not in tmp or 1 not in tmp or 2 not in tmp:
            continue
        abc = [0, 0, 0, -30]
        for j in range(n):
            if tmp[j] >= 0:
                abc[tmp[j]] += l[j]
                abc[3] += 10
        mp = abc[3]
        mp += abs(abc[0] - a)
        mp += abs(abc[1] - b)
        mp += abs(abc[2] - c)
        ans = min(ans, mp)

    elif len(tmp) < n:
        w = tmp + [0]
        x = tmp + [1]
        y = tmp + [2]
        z = tmp + [-1]
        stack += [w, x, y, z]

print(ans)
'''