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 ** 7)
input = sys.stdin.readline

n, a, b, c = map(int, input().split())
l = list(int(input()) for i in range(n))

ans = 0
mpa = mpb = mpc = 0
mp = [0,0,0]
INF = 10**4

groups = [[]*n for _ in range(3)]

def dfs(groups, parent=-1):
    groupa = groups[0]
    groupb = groups[1]
    groupc = groups[2]

    if parent == n-1:
        if len(groupa) > 0:mpa = 10 * (len(groupa)-1) + abs(sum(groupa)-a)
        else: mpa = INF

        if len(groupb) > 0:mpb = 10 * (len(groupb)-1) + abs(sum(groupb)-b)
        else: mpb = INF

        if len(groupc) > 0:mpc = 10 * (len(groupc)-1) + abs(sum(groupc)-c)
        else: mpc = INF

        return mpa+mpb+mpc

    else:
        parent+=1

        addl = [l[parent]]

        adda = dfs([groupa+addl ,groupb, groupc], parent)
        addb = dfs([groupa, groupb+addl, groupc], parent)
        addc = dfs([groupa, groupb, groupc+addl], parent)
        noadd = dfs([groupa,groupb,groupc],parent)

        return min(adda, addb, addc, noadd)

print(dfs(groups))

Solution (Python):
import math
import collections
from operator import mul
from functools import reduce
import bisect
import string

numbers = "0123456789"
alphabets = string.ascii_letters 
characters = numbers + alphabets
def base_cvt(value, n=2):
    try:
        tmp = int(value)
    except:
        raise ValueError('Invalid value:', value)
 
    if n < 2 or n > len(characters):
        raise ValueError('Invalid n:', value)
    result = ''
    tmp = int(value)
    while tmp >= n:
        idx = tmp%n
        result = characters[idx] + result
        tmp = int(tmp / n)
    idx = tmp%n
    result = characters[idx] + result
    return result

n,a,b,c=map(int,input().split())
l=[0]*n
for i in range(n):
    l[i]=int(input())

def zeropad(s,i):
    while len(s)<i:
        s="0"+s
    return s


mp=10000000000000000
for i in range(4**n):
    A=0
    B=0
    C=0
    ai=0
    bi=0
    ci=0
    s=base_cvt(str(i),4)
    s=zeropad(s,n)
    for j in range(n):
        if s[j]=='1':
            A+=l[j]
            ai+=1
        elif s[j]=='2':
            B+=l[j]
            bi+=1
        elif s[j]=='3':
            C+=l[j]
            ci+=1
    if ai>0 and bi>0 and ci>0:
        mp=min(mp,10*((ai-1)+(bi-1)+(ci-1))+abs(A-a)+abs(B-b)+abs(C-c))


print(mp)

Solution (Python):
n,A,B,C=map(int,input().split())
l=[]
for _ in range(n):
    l.append(int(input()))
def solve(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 float('INF')
    ret0=solve(cur+1,a,b,c)
    ret1=solve(cur+1,a+l[cur],b,c)+10
    ret2=solve(cur+1,a,b+l[cur],c)+10
    ret3=solve(cur+1,a,b,c+l[cur])+10
    return min(ret0,ret1,ret2,ret3)
print(solve(0,0,0,0))

Solution (Python):
N,A,B,C=map(int,input().split())
X=[0,A,B,C]
L=[int(input()) for i in range(N)]
d=4**N
ans=float('inf')

for i in range(d):
  F=[0 for i in range(4)]
  cnt=[0 for i in range(4)]
  for j in range(N):
    F[i%4]+=L[j]
    cnt[i%4]+=1
    i //= 4
  p=True
  for k in range(1,4):
    if F[k]==0:
      p=False
      break
  tmp=0
  if p:
    for k in range(1,4):
      tmp+=cnt[k]*10+abs(X[k]-F[k])-10
    ans=min(ans,tmp)
print(ans)

Solution (Python):
n, a, b, c = map(int, input().split())
bamboo = [0]*n
for i in range(n):
  bamboo[i] = int(input())

answer = 10**10
for i in range(4**n):
  key = [0, 0, 0, 0]
  sub = [0, 0, 0]
  for j in range(n):
    k = 0
    if (i >> (2*j))&1:
      k += 1
    if (i >> (2*j+1))&1:
      k += 2
    key[k] += 1
    if k != 3:
      sub[k] += bamboo[j]
  if not all(sub):
    continue
  ans = (sum(key[:3])-3)*10+abs(sub[0]-a)+abs(sub[1]-b)+abs(sub[2]-c)
  if ans < answer:
    answer = ans
print(answer)

Solution (Python):
N, A, B, C = map(int, input().split())
X = [0, A, B, C]
L = [int(input()) for _ in range(N)]
d = 4 ** N
magic = int(1e+9)
for i in range(d):
  F = [0 for _ in range(4)]
  cnt = [0 for _ in range(4)]
  tmp = i
  for j in range(N):
    F[i%4] += L[j]
    cnt[i%4] += 1
    i //= 4
  p = True
  for k in range(1, 4):
    if F[k] == 0:
      p = False
      break
  tmpp = 0
  if p:
    for k in range(1, 4):
      tmpp += cnt[k] * 10 + abs(X[k] - F[k]) - 10
    if tmpp < magic:
      magic = tmpp
print(magic)

Solution (Python):
n,a,b,c = map(int,input().split())
l = [int(input()) for _ in range(n)]
def dfs(cur,x,y,z):
    if cur == n:
        return abs(a-x) + abs(b-y) + abs(c-z)-30 if min(x,y,z) > 0 else 10**9
    ret1 = dfs(cur+1,x,y,z)
    ret2 = dfs(cur+1,x+l[cur],y,z) + 10
    ret3 = dfs(cur+1,x,y+l[cur],z) + 10
    ret4 = dfs(cur+1,x,y,z+l[cur]) + 10
    return min(ret1,ret2,ret3,ret4)
print(dfs(0,0,0,0))

Solution (Python):

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

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

ans=10**6

for i in range(4**N):
    bit=Base_10_to_n(i,4,N)
    group=[[] for j in range(4)]
    
    for j in range(N):
        group[int(bit[j])].append(L[j])
    
    if not(group[1]) or not(group[2]) or not(group[3]):
        continue
    
    costA = abs(A-sum(group[1])) + (len(group[1])-1)*10
    costB = abs(B-sum(group[2])) + (len(group[2])-1)*10
    costC = abs(C-sum(group[3])) + (len(group[3])-1)*10
    
    cost = costA + costB + costC
    
    ans=min(ans,cost)

print(ans)

Solution (Python):

import sys
sys.setrecursionlimit(10**9)
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
N, A, B, C = map(int, input().split())
L = []
for i in range(N):
    L.append(int(input()))

def dfs(cnt, a, b, c):
    if cnt == N:
        return abs(A - a) + abs(B - b) + abs(C - c) - 30 if min(a,b,c) > 0 else 10**9
    r0 = dfs(cnt+1, a, b, c)
    r1 = dfs(cnt+1, a+L[cnt], b, c) + 10
    r2 = dfs(cnt+1, a, b+L[cnt], c) + 10
    r3 = dfs(cnt+1, a, b, c+L[cnt]) + 10
    return min(r0, r1, r2, r3)
    
print(dfs(0,0,0,0))

Solution (Python):
import sys
sys.setrecursionlimit(1000000000)
INF=10**9
n,a,b,c=map(int,input().split())
l=[int(input()) for i in range(n)]
def dfs(i,x,y,z):
    if i==n:
        if min(x,y,z)>0:
            return abs(x-a)+abs(y-b)+abs(z-c)-30
        else:
            return INF
    ans=dfs(i+1,x,y,z)
    ant=dfs(i+1,x+l[i],y,z)+10
    anu=dfs(i+1,x,y+l[i],z)+10
    anv=dfs(i+1,x,y,z+l[i])+10
    return min(ans,ant,anu,anv)
print(dfs(0,0,0,0))

Solution (Python):

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
    
N, A, B, C = map(int, input().split())
L = [int(input()) for _ in range(N)]
ans = float("inf")
for i in range(4**N):
    bits = Base_10_to_n(i, 4).zfill(N)
    a, b, c = 0, 0, 0
    cost = 0
    for j in range(len(bits)):
        if bits[j] == "0":
            pass
        elif bits[j] == "1":
            a += L[j]
            cost += 10
        elif bits[j] == "2":
            b += L[j]
            cost += 10
        else:
            c += L[j]
            cost += 10
    if min(a, b, c) > 0:
        ans = min(ans, cost + abs(a-A)+abs(b-B)+abs(c-C) - 10*3)
print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(1000000000)
INF=10**9
n,a,b,c=map(int,input().split())
l=[int(input()) for i in range(n)]
def dfs(i,x,y,z,m):
    if i==n:
        if x>0 and y>0 and z>0:
            return abs(x-a)+abs(y-b)+abs(z-c)+m
        else:
            return INF
    ans=INF
    if x==0:
        ans=min(dfs(i+1,l[i],y,z,m),ans)
    else:
        ans=min(dfs(i+1,x+l[i],y,z,m+10),ans)
    if y==0:
        ans=min(dfs(i+1,x,l[i],z,m),ans)
    else:
        ans=min(dfs(i+1,x,y+l[i],z,m+10),ans)
    if z==0:
        ans=min(dfs(i+1,x,y,l[i],m),ans)
    else:
        ans=min(dfs(i+1,x,y,z+l[i],m+10),ans)
    return min(ans,dfs(i+1,x,y,z,m))
print(dfs(0,0,0,0,0))

Solution (Python):
import sys






import itertools





readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


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

    ans = INF

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

    for select in selects:
        mp = -30
        bamboo_length = [0] * 3
        for i, num in enumerate(select):
            if num != 3:
                bamboo_length[num] += l[i]
                mp += 10

        for length in bamboo_length:
            if length == 0:
                break
        else:
            mp += abs(a - bamboo_length[0])
            mp += abs(b - bamboo_length[1])
            mp += abs(c - bamboo_length[2])
            ans = min(mp, ans)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import sys


from collections import Counter, deque, defaultdict




import itertools
from operator import attrgetter, itemgetter





readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


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

    ans = INF

    base_idx = list(itertools.permutations(range(n), r=3))

    for bi in base_idx:
        bamboo_length = [0] * 3
        add_bamboo = list(itertools.product(range(4), repeat=(n-3)))
        rem_idx = [i for i in range(n) if i not in bi]
        for ai in add_bamboo:
            mp = 0
            bamboo_length[0] = l[bi[0]]
            bamboo_length[1] = l[bi[1]]
            bamboo_length[2] = l[bi[2]]
            for idx, num in enumerate(ai):
                if num != 3:
                    bamboo_length[num] += l[rem_idx[idx]]
                    mp += 10
            mp += abs(a - bamboo_length[0])
            mp += abs(b - bamboo_length[1])
            mp += abs(c - bamboo_length[2])
            ans = min(mp, ans)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from bisect import *
from heapq import *
from collections import *
from itertools import *
from functools import *
from math import *
from fractions import *

sys.setrecursionlimit(100000000)
input = lambda: sys.stdin.readline().rstrip()

def main():
    ans = 10 ** 9
    N, A, B, C = map(int, input().split())
    l = []
    for _ in range(N):
        l.append(int(input()))
    for i in range(4 ** N):
        group = []
        for j in range(N):
            k = i
            for _ in range(j):
                k //= 4
            group.append(k % 4)
        sm = [0] * 3
        for j in range(N):
            if group[j] < 3:
                sm[group[j]] += l[j]
        if min(sm) > 0:
            ans = min(ans, 10 * (N - group.count(3) - 3) + sum(abs(i - j) for i, j in zip(sorted(sm), [C, B, A])))
    print(ans)


main()

Solution (Python):
n, a, b, c = [int(e) for e in input().split()]
L = [int(input()) for i in range(n)]

def dfs(A, B, C, O, lst, mi):
    if len(lst) == 0:
        if len(A) == 0 or len(B) == 0 or len(C) == 0:
            return mi

        mp = 0
        mp += (len(A) - 1)*10 + abs(a - sum(A))
        mp += (len(B) - 1)*10 + abs(b - sum(B))
        mp += (len(C) - 1)*10 + abs(c - sum(C))
        return min(mp, mi)

    l = lst.pop()
    mi = dfs(A + [l], B.copy(), C.copy(), O.copy(), lst.copy(), mi)
    mi = dfs(A.copy(), B + [l], C.copy(), O.copy(), lst.copy(), mi)
    mi = dfs(A.copy(), B.copy(), C + [l], O.copy(), lst.copy(), mi)
    mi = dfs(A.copy(), B.copy(), C.copy(), O + [l], lst.copy(), mi)

    return mi

def main():
    print(dfs([], [], [], [], L.copy(), float('inf')))

if __name__ == "__main__":
    main()

Solution (Python):
import sys
input = sys.stdin.buffer.readline

def main():
    N,A,B,C = map(int,input().split())
    l = [int(input()) for _ in range(N)]
    
    def point(x,y):
        con = len(x)-1
        s = sum(x)
        return con*10+abs(y-s)
    
    ans = 10**8
    for i in range(4**N):
        num = i
        use = []
        base = 1
        bam = [[] for _ in range(4)]
        for j in range(N):
            use.append(num%4)
            num //= 4
        for k in range(N):
            bam[use[k]].append(l[k])
        if len(bam[1])*len(bam[2])*len(bam[3]) == 0:
            continue
        else:
            p = point(bam[1],A)+point(bam[2],B)+point(bam[3],C)
            ans = min(ans,p)

    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
N,A,B,C=map(int,input().split())
L=[int(input()) for i in range(N)]
INF=10**8
def dfs(n,a,b,c):
  
  
  
  
  if n==N:
    if a*b*c>0:
      ret=abs(A-a)+abs(B-b)+abs(C-c)-30
    else:
      ret=INF
  else:
    ret=dfs(n+1,a,b,c)
    reta=dfs(n+1,a+L[n],b,c)+10
    retb=dfs(n+1,a,b+L[n],c)+10
    retc=dfs(n+1,a,b,c+L[n])+10
    ret = min(ret,reta,retb,retc)
  return ret
print(dfs(0,0,0,0))

Solution (Python):
def dfs(i, a, b, c):
    if i == n:
        if min(a, b, c) > 0:
            return abs(a - A) + abs(b - B) + abs(c - C) - 30
        else:
            return f_inf

    ret0 = dfs(i + 1, a, b, c)
    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

    return min(ret0, ret1, ret2, ret3)


n, A, B, C = map(int, input().split())
l = list(int(input()) for _ in range(n))
f_inf = float("inf")
print(dfs(0, 0, 0, 0))

Solution (Python):
INF = float('inf')

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

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

print(rec(0,0,0,0))

Solution (Python):
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, A, B, C = MAP()
l = [INT() for i 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 INF
    ret0 = dfs(idx+1, a, b, c)
    ret1 = dfs(idx+1, a + l[idx], b, c) + 10
    ret2 = dfs(idx+1, a, b + l[idx], c) + 10
    ret3 = dfs(idx+1, a, b, c + l[idx]) + 10
    return min(ret0, ret1, ret2, ret3)
if __name__ == "__main__":
    print(dfs(0, 0, 0 ,0))

Solution (Python):
N,a,b,c=map(int,input().split())
L=[int(input()) for i in range(N)]
import itertools 
ans=300000
for i in itertools.product('ABCD',repeat=N):
  cst=0
  A=[]
  B=[]
  C=[]
  for j in range(N):
    if i[j]=='A':
      A.append(L[j])
    elif i[j]=='B':
      B.append(L[j]) 
    elif i[j]=='C':
      C.append(L[j])
  if len(A)>0 and len(B)>0 and len(C)>0:
    if len(A)>1:
      cst+=(len(A)-1)*10
    cst+=abs(sum(A)-a)
    if len(B)>1:
      cst+=(len(B)-1)*10
    cst+=abs(sum(B)-b)
    if len(C)>1:
      cst+=(len(C)-1)*10
    cst+=abs(sum(C)-c)
    ans=min(ans,cst)
 
print(ans)

Solution (Python):
import itertools
n = list(map(int,input().split()))
l = [int(input()) for i in range(n[0])]
ans = 10**9

la = [0,1,2,3]


for i in itertools.product(la,repeat=n[0]):
    count = 0
    
    if (1 not in i) or (2 not in i) or (3 not in i):
        continue
    
    lis = [0]*4
    for j in range(n[0]):
        if i[j] > 0 and lis[i[j]] > 0:
            count += 10
        lis[i[j]] += l[j]

    for j in range(1,4):
        count += abs(lis[j]-n[j])
    ans = min(count,ans)
print(ans)

Solution (Python):

import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect, bisect_right, bisect_left

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, A, B, C = MAP()
l = [INT() for i in range(N)]

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, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, A, B, C = MAP()
l = [INT() for i in range(N)]

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**8


def dfs(current_index, sum_a, sum_b, sum_c):
    if current_index == n:
        if min(sum_a, sum_b, sum_c) > 0:
            return sum(abs(x-y) for x, y in
                       zip([a, b, c], [sum_a, sum_b, sum_c]))-30
        else:
            return INF

    cost_none = dfs(current_index+1, sum_a, sum_b, sum_c)
    cost_a = dfs(current_index+1, sum_a+L[current_index], sum_b, sum_c)+10
    cost_b = dfs(current_index+1, sum_a, sum_b+L[current_index], sum_c)+10
    cost_c = dfs(current_index+1, sum_a, sum_b, sum_c+L[current_index])+10
    return min(cost_none, cost_a, cost_b, cost_c)

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

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


def base_n(x, n, zero_padding=8):
    retval = [[], ['0']][x == 0]
    while x > 0:
        x, r = divmod(x, n)
        retval.append(str(r))
    cnt = zero_padding - len(retval)
    pad = ['', '0'*cnt][cnt > 0]
    return pad+''.join(retval[::-1])

ans = 10**8
for i in range(4**n):
    base_4 = base_n(i, 4, n)
    n_bamboo = n - base_4.count("0")
    ctr = Counter(base_4)
    if n_bamboo < 3 or any(k not in ctr.keys() for k in "123"):
        continue

    cost = 0
    for x, y in zip([a, b, c], "123"):
        cost += abs(x - sum(L[idx]for idx, v in enumerate(base_4)
                            if v == y))+(ctr[y]-1)*10
    if ans > cost:
        ans = cost
print(ans)

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:
        if min(a,b,c)>0:
            return abs(a-A)+abs(b-B)+abs(c-C)-30
        else:
            return INF
    pat0=dfs(cur+1,a+l[cur],b,c)+10
    pat1=dfs(cur+1,a,b+l[cur],c)+10
    pat2=dfs(cur+1,a,b,c+l[cur])+10
    pat3=dfs(cur+1,a,b,c)
    return min(pat0,pat1,pat2,pat3)

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

Solution (Python):



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


def dfs(cur, a, b, c):
    INF = float("inf")
    if cur == N:
        if min(a, b, c) > 0:
            return abs(a - A) + abs(b - B) + abs(c - C) - 30
        else:
            return INF
    ret = dfs(cur + 1, a, b, c)
    ret_a = dfs(cur + 1, a + L[cur], b, c) + 10
    ret_b = dfs(cur + 1, a, b + L[cur], c) + 10
    ret_c = dfs(cur + 1, a, b, c + L[cur]) + 10
    return min(ret, ret_a, ret_b, ret_c)


def main():

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


if __name__ == "__main__":
    main()

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

ans = 10**10
for i in range(2**(2*N)) :
    As = []
    Bs = []
    Cs = []
    for j in range(N) :
        if (i >> 2*j)%4 == 0 :
            As.append(b[j])
        elif (i >> 2*j)%4 == 1 :
            Bs.append(b[j])
        elif (i >> 2*j)%4 == 2 :
            Cs.append(b[j])
        else :
            continue
    if As and Bs and Cs :
        mp = 10 * (len(As) + len(Bs) + len(Cs) - 3) \
              + abs(A - sum(As)) + abs(B - sum(Bs)) + abs(C - sum(Cs))
        ans = min(ans, mp)

print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 7)
from functools import lru_cache

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

@lru_cache(None)
def dfs(cur, a, b, c):
    if cur == N:
        return abs(a - A) + abs(b - B) + abs(c - C) 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 if a else 0)
    ret2 = dfs(cur + 1, a, b + l[cur], c) + (10 if b else 0)
    ret3 = dfs(cur + 1, a, b, c + l[cur]) + (10 if c else 0)

    return min(ret0, ret1, ret2, ret3)

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

Solution (Python):

def base_number(X:int, N:int):
    res = ""
    while True:
        q, mod = divmod(X,N)
        res += str(mod)
        X = q
        if q == 0:
            break
    return res[::-1]

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

ans = float("inf")
for i in range(4 ** N):
    state = list(base_number(i,4).rjust(N, "0"))
    if not set(["0","1","2"]) <= set(state):
        continue
    
    make = [[] for _ in range(3)]
    for j,x in enumerate(state):
        if x == "3":
            continue
        make[int(x)].append(L[j])
    
    MP = 0
    for j,m in enumerate(make):
        if len(m) == 1:
            MP += abs(B[j] - m[0]) 
        else:
            MP += (len(m) - 1) * 10 
            MP += abs(B[j] - sum(m))
    
    ans = min(ans, MP)

print(ans)

Solution (Python):


from collections import deque


def submit():
    n, a, b, c = map(int, input().split())
    llist = [int(input()) for _ in range(n)]

    def update(st, h):
        return st[0] + h, st[1] + 1

    def cost(st, goal):
        return (st[1] - 1) * 10 + abs(goal - st[0])

    def rec_search(ast, bst, cst, rest):
        
        if not rest:
            if ast[1] == 0 or bst[1] == 0 or cst[0] == 0:
                return float('inf')
            else:
                return cost(ast, a) + cost(bst, b) + cost(cst, c)
        else:
            head = rest[0]
            rest = rest[1:]

            
            acost = rec_search(update(ast, head), bst, cst, rest)
            
            bcost = rec_search(ast, update(bst, head), cst, rest)
            
            ccost = rec_search(ast, bst, update(cst, head), rest)
            
            ncost = rec_search(ast, bst, cst, rest)

            return min(acost, bcost, ccost, ncost)


    
    ast = (0, 0)
    bst = (0, 0)
    cst = (0, 0)
    
    cost = rec_search(ast, bst, cst, llist)
    print(cost)


if __name__ == "__main__":
    submit()

Solution (Python):
n,a,b,c=map(int,input().split())
l=[int(input()) for i in range(n)]
ans=float('inf')
for i in range(4**n):
    abc=[[] for i in range(4)]
    for j in range(n):
        abc[i%4].append(l[j])
        i//=4
    A,B,C,x=abc
    if len(A)==0 or len(B)==0 or len(C)==0:
        continue
    ans=min(ans,abs(sum(A)-a)+abs(sum(B)-b)+abs(sum(C)-c)+(len(A)+len(B)+len(C)-3)*10)
print(ans)

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を評価
    N本の竹を使うときに必要な合成回数はN-1のため，最後に-1*10*3(?)
    1本も竹を使用していなかったら棄却→MPを無限に使うこととしている
    '''
    if cur == N:
        return abs(a - A) + abs(b - B) + abs(c - C) - 30 if min(a, b, c) > 0 else INF

    '''
    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):
from itertools import product
from sys import maxsize

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

min = maxsize
pattern = [0, 1, 2, 3]
for pt in product(pattern, repeat=n):
    mp = 0
    length = [999] + [0] * 3
    for i, k in zip(pt, l):
        if i:
            if length[i]:
                mp += 10
            length[i] += k

    if length.count(0) > 0:
        continue

    mp += abs(a - length[1]) + abs(b - length[2]) + abs(c - length[3])

    if mp < min:
        min = mp

print(min)

Solution (Python):
from itertools import product

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

ALL = list(product(['A', 'B', 'C', 'N'], repeat = N))

ans = 10 ** 9 + 7
for node in ALL:
  if len(set([ no for no in node if no != 'N'])) == 3:
    a, b, c = 0, 0, 0
    cost = N - 3 - len([ no for no in node if no == 'N'])
    for i, n in enumerate(node):
      if n == 'A':
        a += L[i]
      elif n == 'B':
        b += L[i]
      elif n == 'C':
        c += L[i]
      else:
        continue
    ans = min(abs(a-A) + abs(b-B) + abs(c-C) + 10 * cost, ans)
    
print(ans)

Solution (Python):
N,A,B,C=map(int,input().split())
L=[int(input()) for i in range(N)]
INF=10**8
def dfs(n,a,b,c):
  
  
  
  
  if n==N:
    if a*b*c>0:
      ret=abs(A-a)+abs(B-b)+abs(C-c)-30
    else:
      ret=INF
  else:
    ret=dfs(n+1,a,b,c)
    reta=dfs(n+1,a+L[n],b,c)+10
    retb=dfs(n+1,a,b+L[n],c)+10
    retc=dfs(n+1,a,b,c+L[n])+10
    ret = min(ret,reta,retb,retc)
  return ret
print(dfs(0,0,0,0))

Solution (Python):


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


def rec(i, ai, bi, ci):
    if i == n:
        if ai == 0 or bi == 0 or ci == 0:
            
            return 10 ** 10
        return abs(a - ai) + abs(b - bi) + abs(c - ci)
    else:
        ret = 10 ** 10
        
        if ai == 0:
            ret = min(ret, rec(i + 1, arr[i], bi, ci))
        elif ai > 0:
            ret = min(ret, rec(i + 1, ai + arr[i], bi, ci) + 10)
        if bi == 0:
            ret = min(ret, rec(i + 1, ai, arr[i], ci))
        elif bi > 0:
            ret = min(ret, rec(i + 1, ai, bi + arr[i], ci) + 10)
        if ci == 0:
            ret = min(ret, rec(i + 1, ai, bi, arr[i]))
        elif ci > 0:
            ret = min(ret, rec(i + 1, ai, bi, ci + arr[i]) + 10)
        
        ret = min(ret, rec(i + 1, ai, bi, ci))
        return ret


print(rec(0, 0, 0, 0))

Solution (Python):
n,a,b,c=map(int,input().split())
l=[int(input()) for i in range(n)]
ans=10**9
for bit in range(4**n):
    v=[0]*n
    A,B,C=0,0,0
    cnt=0
    for i in range(n):
        v[i]=(bit>>2*i)&3 
        if v[i]==1:
            if A!=0:
                cnt+=10
            A+=l[i]
        elif v[i]==2:
            if B!=0:
                cnt+=10
            B+=l[i]
        elif v[i]==3:
            if C!=0:
                cnt+=10
            C+=l[i]
    if A==0 or B==0 or C==0: 
        continue
    ans=min(ans,abs(a-A)+abs(b-B)+abs(c-C)+cnt)
print(ans)

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


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 float('inf')
    ret0 = dfs(cur+1, a, b, c)
    ret1 = dfs(cur+1, a+li[cur], b, c) + 10
    ret2 = dfs(cur+1, a, b+li[cur], c) + 10
    ret3 = dfs(cur+1, a, b, c+li[cur]) + 10
    return min(ret0, ret1, ret2, ret3)


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

Solution (Python):

INF=100100100
n,A,B,C=map(int,input().split())
L=[]
for i in range(n):
    l=int(input())
    L.append(l)
def dfs(i,a,b,c):
    
    if i==len(L):
        return abs(a-A)+abs(b-B)+abs(c-C)-30 if min(a,b,c)>0 else INF
        
        
    ret0=dfs(i+1,a,b,c)
    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

    return min(ret0,ret1,ret2,ret3)

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