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)

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

mp = [float('inf')]
def f(i, anum, alen, bnum, blen, cnum, clen):
    if i == n:
        if alen * blen * clen == 0:
            return
        mp[0] = min(mp[0], abs(anum-a)+10*(alen-1) + abs(bnum-b)+10*(blen-1) + abs(cnum-c)+10*(clen-1))
    else:
        f(i+1, anum+l[i], alen+1, bnum, blen, cnum, clen)
        f(i+1, anum, alen, bnum+l[i], blen+1, cnum, clen)
        f(i+1, anum, alen, bnum, blen, cnum+l[i], clen+1)
        f(i+1, anum, alen, bnum, blen, cnum, clen)

f(0, 0, 0, 0, 0, 0, 0)


print(mp[0])

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

def f(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 = f(cur+1,a,b,c)
    ret1 = f(cur+1,a+L[cur],b,c) + 10
    ret2 = f(cur+1,a,b+L[cur],c) + 10
    ret3 = f(cur+1,a,b,c+L[cur]) + 10
    return min(ret0,ret1,ret2,ret3)
    
print(f(0,0,0,0))

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

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

mp = [float('inf')]
def f(i, anum, alen, bnum, blen, cnum, clen):
    if i == n:
        if alen * blen * clen == 0:
            return
        mp[0] = min(mp[0], abs(anum-a)+10*(alen-1) + abs(bnum-b)+10*(blen-1) + abs(cnum-c)+10*(clen-1))
    else:
        f(i+1, anum+l[i], alen+1, bnum, blen, cnum, clen)
        f(i+1, anum, alen, bnum+l[i], blen+1, cnum, clen)
        f(i+1, anum, alen, bnum, blen, cnum+l[i], clen+1)
        f(i+1, anum, alen, bnum, blen, cnum, clen)

f(0, 0, 0, 0, 0, 0, 0)


print(mp[0])

Solution (Python):
from statistics import mean, median,variance,stdev
import numpy as np
import sys
import math
import fractions
import itertools

def j(q):
    if q==1: print("Heisei")
    else:print("TBD")
    exit(0)


def ct(x,y):
    if (x>y):print("")
    elif (x<y): print("")
    else: print("")

def ip():
    return int(input())

def swap(s,pos):
    s[pos]-=1
    s[pos+1]+=1
    print(s)
    if pos == n-2: return s
    if s[pos+2] == 0: swap(s,pos+1)
    return s





n,a,b,c= (int(i) for i in input().split())  








l = []
for i in range(n):
    l.append(ip())
if a in l and b in l and c in l:
    print(0)
    exit(0)
l.sort()
req = [a, b,c]


m  = pow(10,30)
set = [0 for i in range(n)]
set[0] = -1
while sum(set) < n*3:
    while sum(set) < n*3:
        d = 0
        set[d]+=1
        while set[d] == 4:
            set[d]=0
            d+=1
            set[d]+=1
        if 0 in set and 1 in set and 2 in set: break
    if 0 not in set or 1 not in set or 2 not in set:
        continue
    s = [0,0,0,0]
    mi = 0
    for i in range(n):
        s[set[i]]+= l[i]
    for i in range(3):
        mi += abs(s[i] - req[i]) + (set.count(i)-1) * 10
    m  = min(m,mi)
print(m)

Solution (Python):







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

def rec(cur, a, b, c):
    """
    cur: 現在のlsのindex
    a: 合成中の1本目の長さ
    b: 合成中の1本目の長さ
    c: 合成中の1本目の長さ
    """
    if cur == N:
        if min(a, b, c) > 0:
            
            return abs(A-a) + abs(B-b) + abs(C-c) - 30
        else:
            
            
            return INF
    else:
        r0 = rec(cur+1, a, b, c)    
        r1 = rec(cur+1, a+ls[cur], b, c) + 10    
        r2 = rec(cur+1, a, b+ls[cur], c) + 10    
        r3 = rec(cur+1, a, b, c+ls[cur]) + 10    
        return min(r0, r1, r2, r3)

r = rec(0, 0, 0, 0)

print(r)

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

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

mp = float('inf')
def f(i, anum, alen, bnum, blen, cnum, clen):
    global mp
    if i == n:
        if alen * blen * clen == 0:
            return
        mp = min(mp, abs(anum-a)+10*(alen-1) + abs(bnum-b)+10*(blen-1) + abs(cnum-c)+10*(clen-1))
    else:
        f(i+1, anum+l[i], alen+1, bnum, blen, cnum, clen)
        f(i+1, anum, alen, bnum+l[i], blen+1, cnum, clen)
        f(i+1, anum, alen, bnum, blen, cnum+l[i], clen+1)
        f(i+1, anum, alen, bnum, blen, cnum, clen)

f(0, 0, 0, 0, 0, 0, 0)


print(mp)

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

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

mp = float('inf')
def f(i, anum, alen, bnum, blen, cnum, clen):
    global mp
    if i == n:
        if alen * blen * clen == 0:
            return
        mp = min(mp, abs(anum-a)+10*(alen-1) + abs(bnum-b)+10*(blen-1) + abs(cnum-c)+10*(clen-1))
    else:
        f(i+1, anum+l[i], alen+1, bnum, blen, cnum, clen)
        f(i+1, anum, alen, bnum+l[i], blen+1, cnum, clen)
        f(i+1, anum, alen, bnum, blen, cnum+l[i], clen+1)
        f(i+1, anum, alen, bnum, blen, cnum, clen)

f(0, 0, 0, 0, 0, 0, 0)


print(mp)

Solution (Python):

import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(10000)


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A, B, C, L):
    ans = sys.maxsize
    
    S = (A, B, C, 0)
    for l in product([0, 1, 2, 3], repeat=len(L)):
        
        
        ta = 0
        s = [A, B, C, 0]
        for i, f in enumerate(l):
            if s[f] != S[f] and f != 3:
                ta += 10
            s[f] -= L[i]
        if any([s[i] == S[i] for i in range(3)]):
            continue
        
        ta += sum([abs(s[i]) for i in range(3)])
        ans = min(ans, ta)

    return ans


def main():
    
    N, A, B, C = read_int_n()
    L = [read_int() for _ in range(N)]
    print(slv(N, A, B, C, L))


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from itertools import product

def main():
  input = sys.stdin.readline
  N, A, B, C = map(int, input().split())
  L = [int(input()) for _ in range(N)]
  ans = float('inf')
  for s in product(range(4), repeat=N):
    X = [0, 0, 0, 0]
    Y = [0, 0, 0, 0]
    for i in range(len(L)):
      X[s[i]] += L[i]
      Y[s[i]] += 1
    if Y[0]*Y[1]*Y[2] == 0:
      continue
    elongate = abs(X[0] - A) + abs(X[1] - B) + abs(X[2] - C)
    connect = (sum(Y[:3]) - 3) * 10
    ans = min(ans, elongate+connect)
  
  print(ans)
  

if __name__ == '__main__':
  main()

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

def dfs(cur, bs):
    if cur == N:
        return sum(abs(x - y) for x, y in zip(bs, Goals)) - 30 if min(bs) > 0 else INF
    ret = dfs(cur + 1, bs)
    for i in range(len(bs)):
        bs0 = bs.copy()
        bs0[i] += bamboos[cur]
        ret = min(ret, dfs(cur + 1, bs0) + 10)
    return ret

ans = dfs(0, [0, 0, 0])

print(ans)

Solution (Python):
import copy 

n,a,b,c=map(int,input().split())
l=[int(input()) for i in range(n)]
table=[]
for i in range(4**n):
    lis=[]
    x=copy.deepcopy(i)
    for j in range(n):
        lis.append(x%4)
        x=x//4
    table.append(lis)
ans=float('inf')
for i in table:
    check=set(i)
    w=0
    for k in check:
        w+=k
    if w!=6:
        continue
    x,y,z=0,0,0
    ans_sub=0
    cnt=-3
    for j in range(n):
        if i[j]==1:
            x+=l[j]
            cnt+=1
        elif i[j]==2:
            y+=l[j]
            cnt+=1
        elif i[j]==3:
            z+=l[j]
            cnt+=1
    ans_sub+=abs(a-x)+abs(b-y)+abs(c-z)+max(cnt,0)*10
    ans=min(ans,ans_sub)
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:
        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

INF = 10**9

def solve(N: int, A: int, B: int, C: int, l: "List[int]"):
    def how_much_mp(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
        costs = []
        costs.append(how_much_mp(cur+1, a, b, c))
        costs.append(how_much_mp(cur+1, a+l[cur], b, c) + 10)
        costs.append(how_much_mp(cur+1, a, b+l[cur], c) + 10)
        costs.append(how_much_mp(cur+1, a, b, c+l[cur]) + 10)
        return min(costs)
    print(how_much_mp(0, 0, 0, 0))
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    A = int(next(tokens))  
    B = int(next(tokens))  
    C = int(next(tokens))  
    l = [ int(next(tokens)) for _ in range(N) ]  
    solve(N, A, B, C, l)

if __name__ == '__main__':
    main()

Solution (Python):



def ns(X, n):
    if (int(X/n)):
        return ns(int(X/n), n)+str(X%n)
    return str(X%n)

n,a,b,c=map(int,input().split())
t=[a,b,c]
l=[]
ans=-1
for i in range(n):
    l.append(int(input()))

for i in range(4**n):
    tmp=ns(i,4)
    tmp="0"*(n-len(tmp))+tmp
    h=[0]*3
    p=0
    for j in range(n):
        if tmp[j]=="1":
            if h[0]!=0: p+=10
            h[0]+=l[j]

        elif tmp[j]=="2":
            if h[1]!=0: p+=10
            h[1]+=l[j]

        elif tmp[j]=="3":
            if h[2]!=0: p+=10
            h[2]+=l[j]

    if 0 in h:continue
    for k in range(3):
        p+=abs(h[k]-t[k])
    if ans==-1: ans=p
    else: ans=min(ans,p)
print(ans)

Solution (Python):
N, A, B, C = map(int, input().split())
t = [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+t[cur], b, c) + 10
  ret2 = dfs(cur+1, a, b+t[cur], c) + 10
  ret3 = dfs(cur+1, a, b, c+t[cur]) + 10
  return min(ret0, ret1, ret2, ret3)
print(dfs(0,0,0,0))

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

def calcMinMP(lList, ALen, BLen, CLen, mp):
    if not lList:
        return mp + abs(A-ALen) + abs(B-BLen) + abs(C-CLen) - 30 if min(ALen, BLen, CLen) > 0 else INF
    l = lList[0]
    mpList = []
    mpList.append(calcMinMP(lList[1:], ALen, BLen, CLen, mp))
    mpList.append(calcMinMP(lList[1:], ALen+l, BLen, CLen, mp+10))
    mpList.append(calcMinMP(lList[1:], ALen, BLen+l, CLen, mp+10))
    mpList.append(calcMinMP(lList[1:], ALen, BLen, CLen+l, mp+10))
    return min(mpList)

print(calcMinMP(lList, 0, 0, 0, 0))

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=list()
for i in range(N):
    l.append(int(input()))


def solve(x,ans,m):
    global N,A,B,C,l

    c=[10000,-1]
    for i in  range(0,len(l)):
        if(abs(l[i]-x)<=10 and abs(l[i]-x)<=c[0]):
            c[0]=abs(l[i]-x)
            c[1]=i
    
    if(c[1]!=-1):
        tmp=l[c[1]]
        l.pop(c[1])

        return(ans+abs(tmp-x))
    else:
        minst=1000000
        minset=[]
        for i in range(1,len(l)-m+1):
                for j in itertools.combinations(l,i):
                        if(abs(sum(j)-x)+(len(j)-1)*10<minst):
                                minst=abs(sum(j)-x)+(len(j)-1)*10
                                minset=[]
                                for z in j:
                                        minset.append(z)
        for i in minset:
                l.remove(i)
        return(abs(sum(minset)-x)+(len(minset)-1)*10)




totalAns=1000000000
import copy
L=copy.deepcopy(l)

ans=0
ans+=solve(A,0,2)
ans+=solve(B,0,1)
ans+=solve(C,0,0)
if(ans<totalAns):
    totalAns=ans

l=copy.deepcopy(L)
ans=0
ans+=solve(A,0,2)
ans+=solve(C,0,1)
ans+=solve(B,0,0)
if(ans<totalAns):
    totalAns=ans

l=copy.deepcopy(L)
ans=0
ans+=solve(B,0,2)
ans+=solve(A,0,1)
ans+=solve(C,0,0)
if(ans<totalAns):
    totalAns=ans

l=copy.deepcopy(L)
ans=0
ans+=solve(B,0,2)
ans+=solve(C,0,1)
ans+=solve(A,0,0)
if(ans<totalAns):
    totalAns=ans

l=copy.deepcopy(L)
ans=0
ans+=solve(C,0,2)
ans+=solve(A,0,1)
ans+=solve(B,0,0)
if(ans<totalAns):
    totalAns=ans

l=copy.deepcopy(L)
ans=0
ans+=solve(C,0,2)
ans+=solve(B,0,1)
ans+=solve(A,0,0)
if(ans<totalAns):
    totalAns=ans

print(totalAns)

Solution (Python):
N, *ABC = map(int, input().split())
l = [int(input()) for _ in range(N)]
def grouping(l, g, h, k):
    if all(len(x)>0 for x in [g, h, k]):
        yield g, h, k
    if len(l)>0:
        a, *l = l
        yield from grouping(l, g+[a], h, k)
        yield from grouping(l, g, h+[a], k)
        yield from grouping(l, g, h, k+[a])
        yield from grouping(l, g, h, k)
def func3(l, ABC):
    for g in grouping(l, [], [], []):
        p = sum(len(gg)-1 for gg in g)*10
        l = list(map(sum, g))
        yield sum(abs(x-y) for x,y in zip(l,ABC))+p
print(min(func3(l, ABC)))

Solution (Python):
from itertools import product

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

min_num = 10**18
for i in range(4**N):
    abcz = [[] for _ in range(4)]
    for j in range(N):
        abcz[i//(4**j)%4].append(L[j])
    if [] in abcz[:3]:
        continue
    
    m = 0
    for l, x in zip(abcz, ABC): 
        m += 10*(len(l)-1) + abs(sum(l)-x)
    
    
    min_num = min(min_num, m)

print(min_num)

Solution (Python):
import itertools as itr

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

cost = 10**9
for cr in range(1, n-1):
    for ccomb in itr.combinations(l, cr):
        ccosti = abs(c-sum(ccomb)) + (cr-1)*10
        cl = l[:]
        for icomb in ccomb:
            cl.remove(icomb)
        for br in range(1, n-cr):
            for bcomb in itr.combinations(cl, br):
                bcosti = abs(b-sum(bcomb)) + (br-1)*10
                bl = cl[:]
                for icomb in bcomb:
                    bl.remove(icomb)
                for ar in range(1, n+1-cr-br):
                    for acomb in itr.combinations(bl, ar):
                        acosti = abs(a-sum(acomb)) + (ar-1)*10
                        if cost > ccosti + bcosti + acosti:
                            cost = ccosti + bcosti + acosti

print(cost)

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

INF = 10 ** 9    


def dfs(n, a, b, c):
    if n == N:
        return abs(a-A) + abs(b-B) + abs(c-C) -30 if min(a, b, c) > 0 else INF
    
    ret1 = dfs(n+1, a+l[n], b, c) + 10
    ret2 = dfs(n+1, a, b+l[n], c) + 10
    ret3 = dfs(n+1, a, b, c+l[n]) + 10
    ret4 = dfs(n+1, a, b, c)

    return min(ret1, ret2, ret3, ret4)

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

Solution (Python):
from sys import setrecursionlimit
setrecursionlimit(10 ** 9)

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

INF = 10 ** 9

def dfs(n, a, b, c):
    if n == N:
        return abs(a-A) + abs(b-B) + abs(c-C) - 30 if min(a, b, c) > 0 else INF
    res = dfs(n+1, a+L[n], b, c) + 10
    res = min(res, dfs(n+1, a, b+L[n], c) + 10)
    res = min(res, dfs(n+1, a, b, c+L[n]) + 10)
    res = min(res, dfs(n+1, a,  b, c))

    return res

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

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

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 itertools import product
def inpl(): return list(map(int, input().split()))

N, A, B, C = inpl()
L = [int(input()) for _ in range(N)]

ans = 1e9

for X in product(range(4), repeat=N):
    P = [[] for _ in range(4)]
    for i, x in enumerate(X):
        P[x].append(L[i])

    if min(map(len, P[1:])) == 0:
        continue

    tmp = 0
    for Q, D in zip(P[1:], [A, B, C]):
        tmp += 10*(len(Q)-1) + abs(D-sum(Q))
    if tmp < ans:
        ans = min(tmp, ans)

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):
        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 = []
for i in range(N):
    a = int(input())
    l.append(a)

infty = 1000000

def DFS(i,uselist0,uselista,uselistb,uselistc):
    if i == N:
        return calc_mp(uselista,uselistb,uselistc)
    mplist = []
    u0 = uselist0 + [l[i]]
    ua = uselista + [l[i]]
    ub = uselistb + [l[i]]
    uc = uselistc + [l[i]]
    mplist.append(DFS(i+1, u0,uselista,uselistb,uselistc))
    mplist.append(DFS(i+1, uselist0,ua,uselistb,uselistc))
    mplist.append(DFS(i+1, uselist0,uselista,ub,uselistc))
    mplist.append(DFS(i+1, uselist0,uselista,uselistb,uc))
    return min(mplist)


def calc_mp(uselista,uselistb,uselistc):
    mp = 0
    
    mp += (max(len(uselista) - 1, 0)) * 10
    mp += (max(len(uselistb) - 1, 0)) * 10
    mp += (max(len(uselistc) - 1, 0)) * 10

    
    mp += abs(A - sum(uselista))
    mp += abs(B - sum(uselistb))
    mp += abs(C - sum(uselistc))

    if len(uselista)==0:
        mp += infty
    if len(uselistb)==0:
        mp += infty
    if len(uselistc)==0:
        mp += infty
    return mp

print(DFS(0,[],[],[],[]))

Solution (Python):

from itertools import product
def inpl(): return list(map(int, input().split()))

N, A, B, C = inpl()
L = [int(input()) for _ in range(N)]

ans = 1e9

def calc(Q, D):
    S = sum(Q)
    res = 10*(len(Q)-1) + abs(D-S)
    return res


for X in product(range(4), repeat=N):
    P = [[] for _ in range(4)]
    for i, x in enumerate(X):
        P[x].append(L[i])
    if min(map(len, P[1:])) == 0:
        continue
    tmp = 0
    for Q, D in zip(P[1:], [A, B, C]):
        tmp += calc(Q, D)
    if tmp < ans:
        ans = min(tmp, ans)

print(ans)

Solution (Python):

import itertools

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

l = []

for n in range(N):
    l.append(int(input()))

result = 10000000

'''
upper_A = min([abs(A - length) for length in l])
upper_B = min([abs(B - length) for length in l])
upper_C = min([abs(C - length) for length in l])
'''


def get_min(A,target):
    if len(A)==1:
        MP = min([abs(target-l[a]) for a in A])
    else:
        MP = 1000000
        for n in range(1,len(A)+1):
            for c in itertools.combinations(A, n):
                MP = min(MP, abs(target - sum([l[i] for i in c])) + 10 * (n-1))
    return MP


for i in range(3**N):
    shugo = {}
    for n in range(N):
        shugo[n] = int(i / 3**(n)) % 3

    index_A = [k for k,s in shugo.items() if s==0]
    if len(index_A)==0:
        continue
    index_B = [k for k,s in shugo.items() if s==1]
    if len(index_B)==0:
        continue
    index_C = [k for k,s in shugo.items() if s==2]
    if len(index_C)==0:
        continue

    result = min(result,get_min(index_A,A)+get_min(index_B,B)+get_min(index_C,C))

print(result)

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


ans = 10**16


def dfs(a, b, c, i):
    global ans
    if i == N:
        if len(a) == 0 or len(b) == 0 or len(c) == 0:
            return
        ans = min(ans, abs(A-sum(a))+10*(len(a)-1) + abs(B-sum(b)) +
                  10*(len(b)-1) + abs(C-sum(c))+10*(len(c)-1))
        return
    dfs(a+[L[i]], b, c, i+1)
    dfs(a, b+[L[i]], c, i+1)
    dfs(a, b, c+[L[i]], i+1)
    dfs(a, b, c, i+1)

dfs([], [], [], 0)
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):
        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 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 copy

def solve(t, l, c):
    
    min_cost = 100000
    cand = []

    ptn = 1 << len(l)
    
    
    for i in range(1, ptn):
        answers = []
        for j in range(0, len(l)):
            if (i >> j) & 1:
                answers.append(l[j])
        temp_cost = abs(t - sum(answers)) + (10 * (len(answers) - 1) if len(answers) > 1 else 0)
        if temp_cost < min_cost:
            min_cost = temp_cost
            cand = answers

    
    for d in cand:
        del l[l.index(d)]
    return min_cost, l

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

    answer = 1000000
    for targets in [[A, B, C], [A, C, B],[B, A, C],[B, C, A], [C,B,A],[C,A,B]]:
        is_done = [False] * 3
        L2 = copy.copy(L)
        total_cost = 0
        for i in range(len(targets)):
            if targets[i] in L2:
                del L2[L2.index(targets[i])]
                is_done[i] = True

        for i in range(3):
            if is_done[i]:
                continue

            
            
            cost, L2 = solve(targets[i], L2, 0)
            
            total_cost += cost

        answer = min(answer, total_cost)

    print(answer)


if __name__ == '__main__':
    main()

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

tar = []
for x in C, B, A:
    if x in l:
        l.remove(x)
    else:
        tar.append(x)

if not tar:
    print(0)
    exit()

ans = float('inf')
for j in range((len(tar) + 1) ** len(l)):
    vvv = [[] for _ in range(len(tar) + 1)]
    for i in sorted(range(len(l)), reverse=True):
        idx, j = divmod(j, (len(tar) + 1) ** i)
        vvv[idx].append(l[i])
    if any(len(vvvv) == 0 for vvvv in vvv[:-1]):
        continue
    else:
        bbb = 0
        
        for k in range(len(tar)):
            bbb += 10 * (len(vvv[k]) - 1)
            bbb += abs(sum(vvv[k]) - tar[k])
        ans = min(ans, bbb)

print(ans)

Solution (Python):


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

def dfs(n, a):
    if n==0:
        if ("A" not in a) | ("B" not in a) | ("C" not in a):
            return 999999999999
        mp=-30
        At=Bt=Ct=0
        for i, ai in enumerate(a):
            if ai=="A":
                At+=l[i]
                mp+=10
            elif ai=="B":
                Bt+=l[i]
                mp+=10
            elif ai=="C":
                Ct+=l[i]
                mp+=10
        mp+=abs(At-A)
        mp+=abs(Bt-B)
        mp+=abs(Ct-C)
        return mp
    
    return min(dfs(n-1, a+"A"), dfs(n-1, a+"B"), dfs(n-1, a+"C"), dfs(n-1, a+"N"))

print(dfs(N, ""))

Solution (Python):
import math
import numpy as np
import itertools

N, A, B, C = list(map(int, input().split(" ")))
l_list = np.asarray(sorted([int(input()) for _ in range(N)]))

def calc_mp(X, in_list):
    n_elm = len(in_list)
    mps = []
    ans = np.min(np.abs(in_list - X))
    if n_elm >= 2:
        ans2 = min([abs(in_list[i] + in_list[j] - X) for i in range(n_elm) for j in range(i+1, n_elm)]) + 10
        
        ans = min(ans, ans2)
    if n_elm >= 3:
        ans3 = min([abs(in_list[i0] + in_list[i1] + in_list[i2] - X) for i0 in range(n_elm) for i1 in range(i0+1, n_elm) for i2 in range(i1+1, n_elm)]) + 10 + 10
        
        ans = min(ans, ans3)
    if n_elm >= 4:
        ans3 = min([abs(in_list[i0] + in_list[i1] + in_list[i2] + in_list[i3] - X) for i0 in range(n_elm) for i1 in range(i0+1, n_elm) for i2 in range(i1+1, n_elm) for i3 in range(i2+1, n_elm)]) + 10 + 10 + 10
        
        ans = min(ans, ans3)
    if n_elm >= 5:
        ans3 = min([abs(in_list[i0] + in_list[i1] + in_list[i2] + in_list[i3] + in_list[i4] - X) for i0 in range(n_elm) for i1 in range(i0+1, n_elm) for i2 in range(i1+1, n_elm) for i3 in range(i2+1, n_elm) for i4 in range(i3+1, n_elm)]) + 10*4
        
        ans = min(ans, ans3)
    if n_elm >= 6:
        ans3 = min([abs(in_list[i0] + in_list[i1] + in_list[i2] + in_list[i3] + in_list[i4] + in_list[i5] - X) for i0 in range(n_elm) for i1 in range(i0+1, n_elm) for i2 in range(i1+1, n_elm) for i3 in range(i2+1, n_elm) for i4 in range(i3+1, n_elm) for i5 in range(i4+1, n_elm)]) + 10*5
        
        ans = min(ans, ans3)
    if n_elm >= 7:
        ans3 = min([abs(in_list[i0] + in_list[i1] + in_list[i2] + in_list[i3] + in_list[i4] + in_list[i5] + in_list[i6] - X) for i0 in range(n_elm) for i1 in range(i0+1, n_elm) for i2 in range(i1+1, n_elm) for i3 in range(i2+1, n_elm) for i4 in range(i3+1, n_elm) for i5 in range(i4+1, n_elm) for i6 in range(i5+1, n_elm)]) + 10*6
        
        ans = min(ans, ans3)
    if n_elm >= 8:
        ans3 = min([abs(in_list[i0] + in_list[i1] + in_list[i2] + in_list[i3] + in_list[i4] + in_list[i5] + in_list[i6] - in_list[i7] - X) for i0 in range(n_elm) for i1 in range(i0+1, n_elm) for i2 in range(i1+1, n_elm) for i3 in range(i2+1, n_elm) for i4 in range(i3+1, n_elm) for i5 in range(i4+1, n_elm) for i6 in range(i5+1, n_elm) for i7 in range(i6+1, n_elm)]) + 10*7
        
        ans = min(ans, ans3)





    return ans

mps = []
for belongings in itertools.product(*[range(3) for _ in range(N)]):
    bs = np.asarray(belongings)
    l_list0 = l_list[bs==0]
    l_list1 = l_list[bs==1]
    l_list2 = l_list[bs==2]
    
    if 0 in [len(l_list0), len(l_list1), len(l_list2)]:
        continue

    a_mp = calc_mp(A, l_list0)
    b_mp = calc_mp(B, l_list1)
    c_mp = calc_mp(C, l_list2)
    cur_mp = a_mp+b_mp+c_mp
    
    mps.append(cur_mp)

print(min(mps))

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

def get_best(li, goal):
    bam_mp_lis = {0: (-10, tuple())}
    li.sort()
    for i, v in enumerate(li):
        tmp = bam_mp_lis.copy()
        for bam, (mp, lis) in tmp.items():
            b0 = bam + v
            m0 = mp + 10
            l0 = lis + (i,)
            if b0 not in bam_mp_lis or m0 < bam_mp_lis[b0][0]:
                bam_mp_lis[b0] = (m0, l0)
    del bam_mp_lis[0]
    best = 10 ** 9
    for bam, (mp, lis) in bam_mp_lis.items():
        cost = mp + abs(goal - bam)
        if cost < best:
            best = cost
            beslis = lis
    return best, beslis

ans = 10 ** 9
from itertools import permutations
for junjo in permutations(goals):
    tmp = 0
    bambooo = bamboos.copy()
    for ju in junjo:
        if len(bambooo) == 0:
            tmp = 10 ** 9
            break
        be, beli = get_best(bambooo, ju)
        beli = sorted(beli, reverse=True)
        for beli0 in beli:
            del bambooo[beli0]
        tmp += be
    if tmp < ans:
        ans = tmp

print(ans)