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):



N, A, B, C = map(int, input().split())
l = [int(input()) for i in range(N)]
INF = 10 ** 9

    
def dfs(cur, a, b, c):
    
    '''
    停止条件(終端処理)
    深さに限らず，任意の停止条件を書く
    
    深さがNだったら使用MPを評価
    1本も竹を使用していなかったら棄却→MPを無限に使うこととしている
    
    (-30って引いてるのは、最初の 1 本目は合体コストなし、
    2 本目からはコスト 10 かかるため、その1本目のコストの分
    を加えてしまっているため、それを引いている（たぶん）)
    '''
    if cur == N:
        return abs(a - A) + abs(b - B) + abs(c - C) - 30 if min(a, b, c) > 0 else INF


    '''
    cur(current) を進めながら,（末端に進みながら）分岐処理
    末端まで到達した時それぞれの分岐から値が返される
    for 文で書ける場合は for 文で実装
    
    cur番目の竹に対して
        ret0:ABCどれにも使わない
        ret1:Aに使う（合成:MP+10）
        ret2:Bに使う（合成:MP+10）
        ret3:Cに使う（合成:MP+10）
    '''
    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):
import itertools

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

ans=10**10
for i in range(N):
  for j in range(i+1,N):
    for k in range(j+1,N):
      X=[L[i],L[j],L[k]]
      Y=[]
      for l in range(N):
        if l!=i and l!=j and l!=k:
          Y.append(L[l])
      
      
      for m in range(4**len(Y)):
        tmp=0
        mm=m
        XX=[L[i],L[j],L[k]]
        for n in range(len(Y)):
          mmm=mm%4
          if mmm!=0:
            XX[mmm-1]+=Y[n]
            tmp+=10
          mm=(mm-mmm)//4
        XX.sort()
        
        tmp+=abs(XX[0]-M[0])+abs(XX[1]-M[1])+abs(XX[2]-M[2])
        ans=min(tmp,ans)
print(ans)

Solution (Python):
def MP(lA,nA,lB,nB,lC,nC):
    res=0
    res+=abs(lA-A)+abs(lB-B)+abs(lC-C)
    res+=(nA+nB+nC-3)*10
    return res

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

ans=2**31-1

for k in range(1<<(2*N)): 
    lA=lB=lC=0 
    nA=nB=nC=0 
    for i in range(N):
        ti=(k//(4**i))%4 
        if ti==1: 
            lA+=l[i]
            nA+=1
        elif ti==2: 
            lB+=l[i]
            nB+=1
        elif ti==3: 
            lC+=l[i]
            nC+=1
    if nA>0 and nB>0 and nC>0:
        ans=min(ans,MP(lA,nA,lB,nB,lC,nC))

print(ans)

Solution (Python):
INF = pow(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 + length[cur], b, c) + 10
    ret2 = dfs(cur + 1, a, b + length[cur], c) + 10
    ret3 = dfs(cur + 1, a, b, c + length[cur]) + 10
    return min(ret0, ret1, ret2, ret3)

if __name__ == '__main__':
    N, A, B, C = map(int, input().split())
    length = [int(input()) for i in range(N)]
    print(dfs(0, 0, 0, 0))

Solution (Python):
n,a,b,c=map(int,input().split())
l=[int(input()) for i in range(n)]
data=[[[],[],[],[]] for i in range(4**n)]
inf=float("inf")
for i in range(4**n):
    k=i
    for j in range(n):
        m=k//4**(n-1-j)
        if m>0:
            data[i][m].append(j)
            k%=4**(n-1-j)
        else:
            data[i][0].append(j)
            
ans=inf
for h in data:
    if h[0] and h[1] and h[2]:
        count=0
        
        count+=(len(h[0])-1)*10
        count+=(len(h[1])-1)*10
        count+=(len(h[2])-1)*10
        
        s=0
        for i in h[0]:
            s+=l[i]
        count+=abs(s-a)
        
        s=0
        for i in h[1]:
            s+=l[i]
        count+=abs(s-b)
        
        s=0
        for i in h[2]:
            s+=l[i]
        count+=abs(s-c)
        
        ans=min(ans,count)
print(ans)

Solution (Python):
"""
できなかった

- 操作 = 四則演算 or 関数
- 交換法則などが成り立つかどうか確認する必要がある
- 再帰的(dfs)に実装する場合、何を初期値として終了条件とするかの理解が必要
  - 前提として全探索であること => 1の解に収束する必要がない
    全ての葉を訪れたときに最小・最大値・解への到達が判定できれば良い

- dfsの実装: いまどの高さにいるかを引数として渡す = 何を高さとして定義するか
  - 階層のインデックスは選択可能な配列のインデックス
  - 同階層のノードは選択肢
  - ノードが持つ値は、その選択をした時の合計の値
  - 終了条件A, B, Cを満たす

- 求める長さA, B, Cの竹 -> 選択肢

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


def dfs(index, a, b, c):
    if N == index:
        if 0 < min(a, b, c):
            return abs(a - A) + abs(b - B) + abs(c - C) - 30
        else:
            return 10 ** 9
    costs = []
    costs.append(dfs(index + 1, a, b, c))
    costs.append(dfs(index + 1, a + l[index], b, c) + 10)
    costs.append(dfs(index + 1, a, b + l[index], c) + 10)
    costs.append(dfs(index + 1, a, b, c + l[index]) + 10)
    return min(costs)


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

Solution (Python):

import sys

sys.setrecursionlimit(10 ** 9)


def dfs(cur: int, x: int, y: int, z: int) -> int:
    if cur == N:
        if min(x, y, z):
            return abs(x - A) + abs(y - B) + abs(z - C) - 30
        else:
            return 1 << 60
    patterns = []
    patterns.append(dfs(cur + 1, x, y, z))
    patterns.append(dfs(cur + 1, x + L[cur], y, z) + 10)
    patterns.append(dfs(cur + 1, x, y + L[cur], z) + 10)
    patterns.append(dfs(cur + 1, x, y, z + L[cur]) + 10)
    return min(patterns)


def main():
    global N, A, B, C, L
    N, A, B, C, *L = map(int, open(0).read().split())
    ans = dfs(0, 0, 0, 0)
    print(ans)


if __name__ == "__main__":
    main()

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

def dfs(i,x,y,z):
  if i==n:
    return abs(x-a)+abs(y-b)+abs(z-c) if x*y*z else 10**9
  r1 = dfs(i+1,x+l[i],y,z)+ (10 if x>0 else 0)
  r2 = dfs(i+1,x,y+l[i],z)+ (10 if y>0 else 0)
  r3 = dfs(i+1,x,y,z+l[i])+ (10 if z>0 else 0)
  r4 = dfs(i+1,x,y,z)
  return min(r1,r2,r3,r4)

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

Solution (Python):
n,a,b,c = map(int, input().split())
l = [int(input()) for _ in range(n)]
answer = a+b+c
def Base_10_to_n(X, n):
    if (int(X/n)):
        return Base_10_to_n(int(X/n), n)+str(X%n)
    return str(X%n)
  
for i in range(1, 4**n):
  aa = []
  bb = []
  cc = []
  four = list(str(Base_10_to_n(i,4).zfill(n)))
  
  if four.count("1")==0 or four.count("2")==0 or four.count("3") ==0:
    continue
  for index,f in enumerate(four) :
    if f == "0": 
      continue
    elif f == "1":
      aa.append(l[index])
    elif f == "2":
      bb.append(l[index])
    elif f == "3":
      cc.append(l[index])
    else:
      break
  cur = (len(aa)-1)*10+abs(a-sum(aa))+(len(bb)-1)*10+abs(b-sum(bb))+(len(cc)-1)*10+abs(c-sum(cc))
  answer = min(answer, cur)


  
print(answer)

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

def baseN(nums,base,maxketa):
    ans = ""
    for i in range(maxketa-1,-1,-1):
        ans+=str(nums//pow(base,i))
        nums=nums%pow(base,i)
        
    return(ans)



allsel=[]
for i in range(pow(4,N)):
    allsel.append(baseN(i,4,N))

mincost=3*1000
for key in allsel:
    
    a0=[]
    b1=[]
    c2=[]
    x3=[]

    for i in range(len(key)):
        if key[i] == '0':
            a0.append(l[i])
        elif key[i] == '1':
            b1.append(l[i])
        elif key[i] == '2':
            c2.append(l[i])
        else:
            x3.append(l[i])
    
    costA = abs(sum(a0)-A)+10*(len(a0)-1)
    costB = abs(sum(b1)-B)+10*(len(b1)-1)
    costC = abs(sum(c2)-C)+10*(len(c2)-1)
    if len(a0) >= 1 and len(b1) >= 1 and len(c2) >= 1 :
        
        mincost=min(mincost,costA+costB+costC)

print(mincost)

Solution (Python):
import itertools
N,A,B,C=map(int,input().split())
l = [int(input()) for _ in range(N)]
ans = 10**9
lis = itertools.product([0,1,2,3],repeat=N)
for i in lis:
    At=0; Bt=0; Ct=0
    Al=0; Bl=0; Cl=0
    cnt=0
    for j in range(N):
        if i[j]==1:
            At+=1
            Al+=l[j]
        if i[j]==2:
            Bt+=1
            Bl+=l[j]
        if i[j]==3:
            Ct+=1
            Cl+=l[j]
    if At*Bt*Ct==0:
        continue
    ans = min(ans,abs(Al-A)+abs(Bl-B)+abs(Cl-C)+(At+Bt+Ct-3)*10)
print(ans)

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

for _ in range(n):
    l.append(int(input()))
 
ind = 2**(2*n)
ans = 10000000

for i in range(ind):
    use = [[] for _ in range(4)]
    for j in range(n):
        t = (i>>(2*j))&3
        use[t].append(l[j])
        ax = sum(use[0])
        bx =sum(use[1])
        cx = sum(use[2])
        tmp = abs(a-ax) + abs(b-bx) + abs(c-cx) + 10*len(use[0]) -10 + 10*len(use[1]) - 10 + 10*len(use[2]) - 10
        if tmp<ans and len(use[0]) and len(use[1]) and len(use[2]):
            
            ans = tmp
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)


def main():
    N, A, B, C = map(int, input().split())
    l = [int(input()) for _ in range(N)]
    INF = 10 ** 9

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

        no_compound_pattern = dfs(cursor+1, a, b, c)
        compound_a_pattern = dfs(cursor+1, a+l[cursor], b, c) + 10
        compound_b_pattern = dfs(cursor+1, a, b+l[cursor], c) + 10
        compound_c_pattern = dfs(cursor+1, a, b, c+l[cursor]) + 10

        return min(no_compound_pattern, compound_a_pattern, compound_b_pattern, compound_c_pattern)

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


if __name__ == '__main__':
    main()

Solution (Python):
N,A,B,C = map(int, input().split())
l = [int(input()) for i 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):
import itertools

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


appli = ["A", "B", "C", "D"]
appli = list(itertools.product(appli, repeat=N))


def need_MP_for_one_bamboo(X, bamboo_list):
    return 10*(len(bamboo_list)-1) + abs(sum(bamboo_list)-X)


def need_MP_for_pattern(appli_pattern):
    bamboo_for_A = []
    bamboo_for_B = []
    bamboo_for_C = []
    for idx in range(len(appli_pattern)):
        if appli_pattern[idx] == "A":
            bamboo_for_A.append(l[idx])
        elif appli_pattern[idx] == "B":
            bamboo_for_B.append(l[idx])
        elif appli_pattern[idx] == "C":
            bamboo_for_C.append(l[idx])
            
    
    if not (bamboo_for_A and bamboo_for_B and bamboo_for_C):
        return float("inf")
    else:
        return need_MP_for_one_bamboo(A, bamboo_for_A) + need_MP_for_one_bamboo(B, bamboo_for_B) + need_MP_for_one_bamboo(C, bamboo_for_C)
        
            


ans = float("inf")
for appli_pattern in appli:
    ans = min(ans, need_MP_for_pattern(appli_pattern))

print(ans)

Solution (Python):

def Synthetic_Kadomatsu_dfs(l, depth, a, b, c, N, A, B, C):
    if depth == N: return abs(a - A) + abs(b - B) + abs(c - C) - 30 if min(a,b,c) > 0 else float('INF')

    ret0 = Synthetic_Kadomatsu_dfs(l, depth+1, a, b, c, N, A, B, C)
    ret1 = Synthetic_Kadomatsu_dfs(l, depth + 1, a + l[depth], b, c, N, A, B, C)+10
    ret2 = Synthetic_Kadomatsu_dfs(l, depth + 1, a, b + l[depth], c, N, A, B, C)+10
    ret3 = Synthetic_Kadomatsu_dfs(l, depth + 1, a, b, c + l[depth], N, A, B, C)+10
    return min(ret0,ret1,ret2,ret3)

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

    print(Synthetic_Kadomatsu_dfs(l, 0, 0, 0, 0, N, A, B, C))



if __name__ == "__main__":
    Synthetic_Kadomatsu()

Solution (Python):
import sys
from collections import defaultdict
from copy import copy
sys.setrecursionlimit(1000000)
N,A,B,C = map(int,input().split())
L = [int(input()) for _ in range(N)]

def dfs(x,a,b,c):
    if x == N:
        return abs(a-A)+abs(b-B)+abs(c-C) - 30 if min(a,b,c) > 0 else 1000000000
    ret0 = dfs(x+1,a,b,c)
    ret1 = dfs(x+1,a+L[x],b,c) + 10
    ret2 = dfs(x+1,a,b+L[x],c) + 10
    ret3 = dfs(x+1,a,b,c+L[x]) + 10
    return min(ret0,ret1,ret2,ret3)

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

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



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):
from collections import deque

def dfs():
  queue = deque()
  queue.append([0,[0]])
  queue.append([0,[1]])
  queue.append([0,[2]])
  queue.append([0,[3]])
  
  grps = []
  while len(queue) != 0:
    idx, Llist = queue.pop()
    if idx == N-1:
      grps.append(Llist)
    else:
      queue.append([idx+1,Llist+[0]])
      queue.append([idx+1,Llist+[1]])
      queue.append([idx+1,Llist+[2]])
      queue.append([idx+1,Llist+[3]])
  return grps

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

ans = float('inf')
for grp in grps:
  A_mem = []
  B_mem = []
  C_mem = []
  for idx, val in enumerate(grp):
    if val == 0:A_mem.append(L[idx])
    elif val == 1:B_mem.append(L[idx])
    elif val == 2:C_mem.append(L[idx])
    
  len_A_mem, len_B_mem, len_C_mem = len(A_mem), len(B_mem), len(C_mem)  
  if 0 in [len_A_mem, len_B_mem, len_C_mem]: continue
  else:
    pt = (sum([len_A_mem,len_B_mem, len_C_mem]) -3)*10
    pt += abs(sum(A_mem)-A) + abs(sum(B_mem)-B) + abs(sum(C_mem)-C)
    ans = min(ans, pt)
print(ans)

Solution (Python):
from collections import deque
import copy
n, a, b, c = map(int,input().split())
bamboos = []
for _ in range(n):
    bamboos.append(int(input()))

groups =deque()
groups.append([[bamboos[0]],[],[],[]])

for i in range(1,n):
    groups2 = deque()
    while len(groups)>0:
        group = groups.popleft()
        for j in range(4):
            group2 = copy.deepcopy(group)
            group2[j].append(bamboos[i])
            groups2.append(group2) 
    groups = groups2
def unite(g1,g2,g3,g4):
    kouho = []
    l1 = len(g1)
    l2 = len(g2)
    l3 = len(g3)
    l4 = len(g4)
    
    if len(g2)>0 and len(g3)>0 and len(g4)>0:
        unite_score = (l2 +l3 +l4-3)*10
        kouho.append([sum(g2),sum(g3),sum(g4),unite_score])
    if len(g1)>0 and len(g3)>0 and len(g4)>0:
        unite_score = (l1 +l3 +l4-3)*10
        kouho.append([sum(g1),sum(g3),sum(g4),unite_score])
    if len(g2)>0 and len(g1)>0 and len(g4)>0:
        unite_score = (l2 +l1 +l4-3)*10
        kouho.append([sum(g2),sum(g1),sum(g4),unite_score])
    if len(g2)>0 and len(g3)>0 and len(g1)>0:
        unite_score = (l2 +l3 +l1-3)*10
        kouho.append([sum(g2),sum(g3),sum(g1),unite_score])
    return kouho
        

def solve(a,b,c,groups):
    ans = float("inf")
    for comb_4 in groups:
        kouhos = unite(comb_4[0],comb_4[1],comb_4[2],comb_4[3])
        for kouho in kouhos:
            score = kouho.pop()
            bam = kouho
            bam.sort()
            x = bam[2]
            y = bam[1]
            z = bam[0]
            score += abs(a-x) +abs(b-y)+abs(c-z)
            ans = min(ans,score)
    print(ans)
solve(a,b,c,groups)

Solution (Python):
A = [0,0,0]
N,A[0],A[1],A[2] = map(int,input().split())
L = [int(input()) for _ in range(N)]


ans = 10 ** 9
for i in range(4**N):
  G = [[] for _ in range(4)]
  for j in range(N):
    G[(i//(4**j))%4].append(L[j])
  
  mp = 0
  for j in range(3):
    if len(G[j]) == 0:
      mp = 10 ** 9
      break
    mp += (len(G[j])-1)*10
    mp += abs(sum(G[j])-A[j])
  ans = min(ans,mp)
print(ans)

Solution (Python):
import sys
from bisect import *
from collections import *
from copy import deepcopy
from datetime import *
from heapq import *
from itertools import *

from operator import *
from pprint import *

sys.setrecursionlimit(10**8)

input = sys.stdin.readline

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

def dfs(idx,a,b,c):
    if idx == N:
        return abs(a-A)+abs(b-B)+abs(c-C)-30 if min(a,b,c) > 0 else float('inf')
    first = 10+dfs(idx+1,a+LS[idx],b,c)
    second = 10+dfs(idx+1,a,b+LS[idx],c)
    third = 10+dfs(idx+1,a,b,c+LS[idx])
    fourth = dfs(idx+1,a,b,c)
    return min(first,second,third,fourth)

def main():
    """ main """
    print(dfs(0,0,0,0))

if __name__ == '__main__':
    main()

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


def dfs(a, b, c, n):
    res = float("inf")
    if n == N:
        if a > 0 and b > 0 and c > 0:
            return abs(A - a) + abs(B - b) + abs(C - c) - 30
        else:
            return float("inf")
    l = l_list[n]
    res = min(res, dfs(a, b, c, n + 1))
    res = min(res, dfs(a + l, b, c, n + 1) + 10)
    res = min(res, dfs(a, b + l, c, n + 1) + 10)
    res = min(res, dfs(a, b, c + l, n + 1) + 10)
    return res


ans = dfs(0, 0, 0, 0)
print(ans)

Solution (Python):
def main():
    N, *ABCnum = (int(i) for i in input().split())
    l = [int(input()) for _ in range(N)]
    ans = 10 ** 6
    from itertools import product
    for pattar in product(range(4),repeat=N):
        ABC = [[] for i in range(3)]
        for i,g in enumerate(pattar):
            if g == 0:
                ABC[0].append(l[i])
            elif g == 1:
                ABC[1].append(l[i])
            elif g == 2:
                ABC[2].append(l[i])
        cur = 0
        if not ABC[0] or not ABC[1] or not ABC[2]:
            continue
        for i in range(3):
            cur += abs(ABCnum[i] - sum(ABC[i])) + 10*(len(ABC[i]) - 1)
        ans = min(ans,cur)
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
N,A,B,C = 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):

import sys
input = sys.stdin.readline
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7



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

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

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

    return min(ret0, ret1, ret2, ret3)

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

Solution (Python):
import sys
import queue



def aaa(ll,a,b,c):
	ret=a+b+c
	for i,v1 in enumerate(ll):
		t1=abs(a-v1)
		if ret < t1:
			continue
		for j,v2 in enumerate(ll):
			if i==j:
				continue
			t2=t1 + abs(b-v2)
			if ret < t2:
				continue
			for k,v3 in enumerate(ll):
				if i==k or j==k:
					continue
				t3 = t2 + abs(c-v3)
				ret=min(ret, t3)
	return ret		

def mk_str(ll):
	ll.sort()
	return '_'.join([str(v) for v in ll])


def main():
	n , a, b, c = map(int, input().split())
	est=lambda ll:aaa(ll,a,b,c)
	
	bb=[]
	for i in range(n):
		bb.append(int(input()))
	
	cl=set()
	ol=queue.PriorityQueue()
	
	st=bb
	ee=est(st)
	cc=0
	cl.add(mk_str(bb))
	ol.put((ee+cc, (cc, bb)))	
	while True:
		if ee == 0:
			return cc
		
		
		rr=cc+ee
		ol.put((rr, (rr, [a,b,c])))
		
		
		if len(st) > 3:
			cc+=10
			for i, v in enumerate(st):
				kk=st[:]
				m=kk.pop(i)
				for j, _ in enumerate(kk):
					kkk=kk[:]
					kkk[j]+=m
					stk=mk_str(kkk)
					if stk not in cl:
						cl.add(stk)
						ol.put((cc, (cc, kkk)))
		v,(cc, st) = ol.get()
		ee = est(st)
				
	print(ans)
	
	

isTest=False

def pa(v):
	if isTest:
		print(v)

if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
		isTest=True
	else:
		pass
		
			
	ret = main()
	if ret is not None:
		print(ret)

Solution (Python):
import sys
import queue




def aaa(ll,a,b,c):
	ret=a+b+c
	for i,v1 in enumerate(ll):
		if v1==0:
			continue
		t1=abs(a-v1)
		if ret < t1:
			continue
		for j,v2 in enumerate(ll):
			if v2==0:
				continue
			if i==j:
				continue
			t2=t1 + abs(b-v2)
			if ret < t2:
				continue
			for k,v3 in enumerate(ll):
				if v3==0:
					continue
				if i==k or j==k:
					continue
				t3 = t2 + abs(c-v3)
				ret=min(ret, t3)
	return ret		

def mk_str(ll):
	ll.sort()
	return '_'.join([str(v) for v in ll])


def main():
	n , a, b, c = map(int, input().split())
	est=lambda ll:aaa(ll,a,b,c)
	
	bb=[]
	for i in range(n):
		bb.append(int(input()))
	
	cl=set()
	ol=queue.PriorityQueue()
	

	
	st=bb
	ee=est(st)
	cc=0
	cl.add(mk_str(bb))
	ol.put((ee+cc, (cc, bb)))	
	while True:
		if ee == 0:
			return cc
		
		
		rr=cc+ee
		ol.put((rr, (rr, [a,b,c])))
		
		
		
		
		if len(st) > 3:
			cc+=10
			for i, v in enumerate(st):
				kk=st[:]
				m=kk.pop(i)
				for j, _ in enumerate(kk):
					kkk=kk[:]
					kkk[j]+=m
					stk=mk_str(kkk)
					if stk not in cl:
						cl.add(stk)
						ol.put((cc, (cc, kkk)))
		v,(cc, st) = ol.get()
		ee = est(st)
				
	print(ans)
	
	

isTest=False

def pa(v):
	if isTest:
		print(v)

if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
		isTest=True
	else:
		pass
		
			
	ret = main()
	if ret is not None:
		print(ret)

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


def dfs(cur, a, b, c):
  if cur == N:
    if min(a, b, c) > 0:
      return abs(a-A) + abs(b-B) + abs(c-C) - 30
    else:
      return 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())
l = [int(input()) for _ in range(n)]

m = []
def dfs(depth, x, y, z, count):
  if depth == n:
    if min(x, y, z) > 0:
       return abs(a-x)+abs(b-y)+abs(c-z)+10*count-30
    else:
      return float('Inf')
  ret0 = dfs(depth+1, x, y, z, count)
  ret1 = dfs(depth+1, x+l[depth], y, z, count+1)
  ret2 = dfs(depth+1, x, y+l[depth], z, count+1)
  ret3 = dfs(depth+1, x, y, z+l[depth], count+1)
  return min(ret0, ret1, ret2, ret3)

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

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

m = []
def dfs(depth, x, y, z, count):
  if depth == n:
    if min(x, y, z) > 0:
       return abs(a-x)+abs(b-y)+abs(c-z)+10*count-30
    else:
      return float('Inf')
  ret0 = dfs(depth+1, x, y, z, count)
  ret1 = dfs(depth+1, x+l[depth], y, z, count+1)
  ret2 = dfs(depth+1, x, y+l[depth], z, count+1)
  ret3 = dfs(depth+1, x, y, z+l[depth], count+1)
  return min(ret0, ret1, ret2, ret3)

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

Solution (Python):
N,A,B,C,*L=map(int,open(0).read().split())
ans=float("inf")
for i in range(2**(N*2)):
	a=b=c=0
	mp=0
	for j,x in enumerate(L):
		f=(i>>2*j)&3
		if f==0:
			if a:mp+=10
			a+=x
		elif f==1:
			if b:mp+=10
			b+=x
		elif f==2:
			if c:mp+=10
			c+=x
	if any([a==0,b==0,c==0]):
		continue
	mp+=abs(A-a)+abs(B-b)+abs(C-c)
	if ans>mp:
		ans=mp
	if ans==0:
		break
print(ans)

Solution (Python):
N,A,B,C = 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):
def getlist():
	return list(map(int, input().split()))

N, A, B, C = getlist()
L = []
for i in range(N):
	L.append(int(input()))

ans = float("inf")
for i in range(1 << 2 * len(L)):
    a = []
    b = []
    c = []
    for j in range(len(L)):
    	if ((i >> 2 * j) & 1) == 1:
    		if ((i >> 2 * j + 1) & 1) == 1:
    			a.append(L[j])
    		else:
    			b.append(L[j])
    	else:
    		if ((i >> 2 * j + 1) & 1) == 1:
    			c.append(L[j])
    	v = 0
    	if len(a) != 0 and len(b) != 0 and len(c) != 0:
    		v += 10 * (len(a) - 1)
    		v += 10 * (len(b) - 1)
    		v += 10 * (len(c) - 1)
    		v += abs(sum(a) - A) + abs(sum(b) - B) + abs(sum(c) - C)
    		ans = min(ans, v)

print(ans)

Solution (Python):
n, a, b, c = map(int, input().split())
abc = [a, b, c]
l = [int(input()) for _ in range(n)]
ans = 10**9
now = [[0, 0] for _ in range(4)]

def dfs(depth, l):
    global ans, now
    if depth == n:
        tmp = 0
        for i in range(3):
            if now[i][1] == 0:
                return
            tmp += abs(abc[i] - now[i][0]) + 10 * (now[i][1] - 1)
        ans = min(ans, tmp)
        return
    for i in range(4):
        now[i][0] += l[depth]
        now[i][1] += 1
        dfs(depth + 1, l)
        now[i][0] -= l[depth]
        now[i][1] -= 1

dfs(0, l)
print(ans)

Solution (Python):


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

for _ in range(N):
    l = int(input().split()[0])
    l_list.append(l)


def cost(no, a_len, b_len, c_len):
    if no == N:
        
        
        if min(a_len, b_len, c_len) <= 0:
            
            
            return float("inf")

        a_cost = abs(a_len - A)
        b_cost = abs(b_len - B)
        c_cost = abs(c_len - C)
        
        return sum([a_cost, b_cost, c_cost]) - 30

    l = l_list[no]
    a_cost = 10 + cost(no + 1, a_len + l, b_len, c_len)
    b_cost = 10 + cost(no + 1, a_len, b_len + l, c_len)
    c_cost = 10 + cost(no + 1, a_len, b_len, c_len + l)
    d_cost = cost(no + 1, a_len, b_len, c_len)

    
    
    return min([a_cost, b_cost, c_cost, d_cost])


ans = cost(0, 0, 0, 0)
print(ans)

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

def ten2four(x, n):
  output=str()
  for i in range(n-1, 0, -1):
    output+=str(x//(4**i))
    x=x%(4**i)
    
  output+=str(x)
  return output

p=4**N
minmp=abs(A-l[0])+abs(B-l[1])+abs(C-l[2])
for i in range(p):
  tempa=0
  tempb=0
  tempc=0
  tempmp=0
  
  pat=ten2four(i, N)
  
  x=sum([pat[j]=='1' for j in range(N)])
  y=sum([pat[j]=='2' for j in range(N)])
  z=sum([pat[j]=='3' for j in range(N)])
  
  if x>0 and y>0 and z>0:
    for j in range(N):
      if pat[j]=='1':
        tempa+=l[j]
      elif pat[j]=='2':
        tempb+=l[j]
      elif pat[j]=='3':
        tempc+=l[j]
      else:
        pass
      
    tempmp=10*(x+y+z-3)+abs(A-tempa)+abs(B-tempb)+abs(C-tempc)

    if minmp>tempmp:
      minmp=tempmp
            
print(minmp)

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

def ten2four(x, n):
  output=str()
  for i in range(n-1, 0, -1):
    output+=str(x//(4**i))
    x=x%(4**i)
    
  output+=str(x)
  return output

p=4**N
minmp=abs(A-l[0])+abs(B-l[1])+abs(C-l[2])
for i in range(p):
  tempa=0
  tempb=0
  tempc=0
  tempmp=0
  
  pat=ten2four(i, N)
  
  x=sum([pat[j]=='1' for j in range(N)])
  y=sum([pat[j]=='2' for j in range(N)])
  z=sum([pat[j]=='3' for j in range(N)])
  
  if x>0 and y>0 and z>0:
    for j in range(N):
      if pat[j]=='1':
        tempa+=l[j]
      elif pat[j]=='2':
        tempb+=l[j]
      elif pat[j]=='3':
        tempc+=l[j]
      else:
        pass
      
    tempmp=10*(x+y+z-3)+abs(A-tempa)+abs(B-tempb)+abs(C-tempc)

    if minmp>tempmp:
      minmp=tempmp
            
print(minmp)

Solution (Python):
from itertools import product


def main():
    n, *target = map(int, input().split())
    arr = [int(input()) for i in range(n)]

    tests = product(range(4), repeat=n) 
    test_arr = [[] for _ in range(3)]
    min_cost = float("inf")

    for test in tests: 
        cost = 0

        if 1 not in test or 2 not in test or 3 not in test:
            continue

        for i in range(3):
            test_arr[i] = [arr[x] for x in range(n) if test[x] == i + 1]
            cost += (len(test_arr[i]) - 1) * 10  
            cost += abs(sum(test_arr[i]) - target[i]) 

        if min_cost > cost:
            min_cost = cost

    print(min_cost)


main()

Solution (Python):
n, A, B, C = 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())
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))