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, re
from collections import deque, defaultdict, Counter
from math import sqrt, hypot, factorial, pi, sin, cos, radians, log10
if sys.version_info.minor >= 5: from math import gcd
else: from fractions import gcd 
from heapq import heappop, heappush, heapify, heappushpop
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul, xor
from copy import copy, deepcopy
from functools import reduce, partial
from fractions import Fraction
from string import ascii_lowercase, ascii_uppercase, digits
from datetime import date

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def round(x): return int((x*2+1) // 2)
def fermat(x, y, MOD): return x * pow(y, MOD-2, MOD) % MOD
def lcm(x, y): return (x * y) // gcd(x, y)
def lcm_list(nums): return reduce(lcm, nums, 1)
def gcd_list(nums): return reduce(gcd, nums, nums[0])
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

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

ABCs=[[] for i in range(3)]
for i, x in enumerate(ABC):
    
    for j in range(1<<N):
        if j==0:
            ABCs[i].append((INF, j))
            continue
        sm=cnt=0
        for k in range(N):
            if j>>k&1:
                sm+=L[k]
                cnt+=1
        mp=(cnt-1)*10
        mp+=abs(x-sm)
        ABCs[i].append((mp, j))
    ABCs[i].sort()

mn=INF

for perm in permutations([0,1,2]):
    msk=sm=0
    for i in perm:
        for j in range(len(ABCs[i])):
            mp,k=ABCs[i][j]
            
            if msk|k==msk^k:
                sm+=mp
                msk+=k
                break
    mn=min(mn, sm)
print(mn)

Solution (Python):
ri = lambda: int(input())
rl = lambda: list(map(int,input().split()))

N,A,B,C=rl()
l=[0]*N
for i in range(N):
    l[i] = ri()
ans = float('inf')
for n in range(4**N):
    a,b,c=0,0,0
    ans_ = 0
    for i in range(N):
        sn = format(n>>(2*i),'0{}b'.format(N))[-2:]
        if sn=='01':
            a+=l[i]
            ans_ += 10
        elif sn=='10':
            b+=l[i]
            ans_ += 10
        elif sn=='11':
            c+=l[i]
            ans_ += 10
    if a!=0 and b!=0 and c!=0:
        ans_ += abs(A-a)+abs(B-b)+abs(C-c) -30
        if ans > ans_:
            ans = ans_

print(ans)

Solution (Python):
def ttt (x,y,z,i,m,p,q,r):
  if i==n and (p==0 or q==0 or r==0):
    return 10000000
  if i==n:
    m+=abs(x-a)+abs(y-b)+abs(z-c)
    return m
  else:
    return min(ttt(x,y,z,i+1,m,p,q,r), ttt(x+l[i],y,z,i+1,m+10,p+1,q,r), 
               ttt(x,y+l[i],z,i+1,m+10,p,q+1,r), ttt(x,y,z+l[i],i+1,m+10,p,q,r+1))
n,a,b,c=map(int, input().split())
l=[int(input()) for i in range(n)]
print(ttt(0,0,0,0,0,0,0,0)-30)

Solution (Python):
def dfs(index, A, B, C, X ):
    global n, ans, a, b, c
    
    mp = 0
    if A and B and C:
        mp += (max(len(A) - 1, 0) + max(len(B) - 1, 0) + max(len(C) - 1, 0) ) * 10
        mp += abs(sum(A) - a) +abs(sum(B) - b) +abs(sum(C) - c) 
        ans = min(ans, mp)
    if index == n:
        return
    dfs(index+1, A + [l[index]], B, C, X)
    dfs(index+1, A, B + [l[index]], C, X)
    dfs(index+1, A, B, C + [l[index]], X)
    dfs(index+1, A, B, C, X + [l[index]])

n, a, b, c = map(int, input().split())
l = [ int(input()) for _ in range(n) ]
ans = float("inf")
dfs(0, [], [], [], [])
print(ans)

Solution (Python):
def dfs(i, d):
    if i == N:
        if any(v == [] and k != 'X' for k, v in d.items()):
            return
        join_mp = (len(d['A']) - 1) * 10 + (len(d['B']) - 1) * 10 + (len(d['C']) - 1) * 10
        sinshoku_mp = abs(A - sum(d['A'])) + abs(B - sum(d['B'])) + abs(C - sum(d['C']))
        mp = join_mp + sinshoku_mp
        cand.append(mp)
        return
    d['A'].append(l[i])
    dfs(i+1, d)
    del d['A'][-1]
    d['B'].append(l[i])
    dfs(i+1, d)
    del d['B'][-1]
    d['C'].append(l[i])
    dfs(i+1, d)
    del d['C'][-1]
    d['X'].append(l[i])
    dfs(i+1, d)
    del d['X'][-1]

if __name__ == '__main__':
    cand = []
    N, A, B, C = map(int, input().split())
    l = []
    for _ in range(N):
        l.append(int(input()))

    a = {'A': [], 'B': [], 'C': [], 'X': []}
    dfs(0, a)
    print(min(cand))

Solution (Python):


from itertools import combinations


def solver(array, a_set, b_set, c_set):
    if not a_set or not b_set or not c_set:
        return float("inf")
    res_a = sum(array[x] for x in a_set)
    res_b = sum(array[x] for x in b_set)
    res_c = sum(array[x] for x in c_set)

    join_cost = sum([10 * (len(x)-1) for x in [a_set, b_set, c_set] if len(x) > 1])
    res = abs(res_a - a) + abs(res_b - b) + abs(res_c - c) + join_cost
    return res


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

a_comb, b_comb, c_comb = [], [], []
a_index, b_index, c_index = [False for x in range(n)], [False for x in range(n)], [False for x in range(n)]

index_array = [x for x in range(1, n + 1)]
for j in range(0, n + 1):
    a_comb += [set(x) for x in combinations(index_array, j)]
    b_comb += [set(x) for x in combinations(index_array, j)]
    c_comb += [set(x) for x in combinations(index_array, j)]

res = float("inf")
tmp = 0
for a_set in a_comb:
    for b_set in b_comb:
        if a_set & b_set:
            continue
        for c_set in c_comb:
            if a_set & c_set or b_set & c_set:
                continue
            tmp += 1
            res = min(res, solver(array, a_set, b_set, c_set))

print(res)

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


import itertools
INF = 1e10

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

ans = INF
for prod in itertools.product('NABC', repeat=N):
    if not ('A' in prod and 'B' in prod and 'C' in prod):
        continue

    D = {'A': [], 'B': [], 'C': [], 'N': []}
    for i in range(N):
        D[prod[i]].append(L[i])

    tmp = (len(D['A']) - 1) * 10 + abs(sum(D['A']) - A)
    tmp += (len(D['B']) - 1) * 10 + abs(sum(D['B']) - B)
    tmp += (len(D['C']) - 1) * 10 + abs(sum(D['C']) - C)
    ans = min(ans, tmp)

print(ans)

Solution (Python):
N, A, B, C = map(int, input().split())
l = list(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=[0]*n
ch=0
ans=0

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

ans+=abs(l[0]-a)
ans+=abs(l[1]-b)
ans+=abs(l[2]-c)

    
for i in range(4**n):
    ch=0
    mp=0
    s=[0]*4
    for j in range(n):
        for k in range(3):
            if (i>>2*j) % 2**2 ==k:
                if s[k]==0:
                    0
                else:
                    mp+=10
                s[k]+=l[j]
                    
    for p in range(3):
        if s[p]==0:
            
            ch=1
    if ch==1:
        0
        
    else:
        mp+=abs(int(s[0]-a))
        mp+=abs(int(s[1]-b))
        mp+=abs(int(s[2]-c))
        if mp<ans:
            ans=mp
            s_ans=s
            j_ans=j
    
    
print(ans)

Solution (Python):
from itertools import product
a = [0, 0, 0]
N, a[0], a[1], a[2] = list(map(int,input().split()))
l = []
for i in range(N):
  l.append(int(input()))
mm = float("inf")
for p in product(range(4), repeat=N):
  c = [0]*4
  s = [0]*4
  for i in range(N):
    c[p[i]] += 1
    s[p[i]] += l[i]
  if min(c[:3])==0:
    continue
  m = 0
  for j in range(3):
    m += max(0, c[j]-1)*10
    m += abs(a[j]-s[j])
  mm = min(mm, m)
print(mm)

Solution (Python):
import itertools

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


ansans=float('inf')
ans=float('inf')

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


for j in range(len(mylist)):
    x,y,z=0,0,0
    for i in range(n):
        if mylist[j][i]==1:
            x+=l[i]
        elif mylist[j][i]==2:
            y+=l[i]
        elif mylist[j][i]==3:
            z+=l[i]
        
    if mylist[j].count(1)>0 and mylist[j].count(2)>0 and mylist[j].count(3) > 0:
        ans=0
        ans+=abs(a-x)+abs(b-y)+abs(c-z)
        compo=0
        for i in range(1,4):
            compo+=mylist[j].count(i)-1
        ans+=10*compo

    if ans < ansans:
        ansans = ans

print(ansans)

Solution (Python):






N,A,B,C = map(int,input().strip().split(' '))
l =[]
for _ in range(0,N,+1):
	banbooLength = int(input().strip())
	l.append(banbooLength)
INF = 10 ** 9

def solveAlgorithm(cursol,aBanboo,bBanboo,cBanboo):
	if cursol==N :
		nowMin = min(aBanboo,bBanboo,cBanboo)
		if nowMin > 0 :
			
			addAndminusMagic = (abs(aBanboo-A)-10)+(abs(bBanboo-B)-10)+(abs(cBanboo-C)-10)
			return addAndminusMagic
		else:
			return INF
	
	return0 = solveAlgorithm(cursol+1,aBanboo,bBanboo,cBanboo)
	
	return1 = solveAlgorithm(cursol+1,aBanboo+l[cursol],bBanboo,cBanboo)+10
	
	return2 = solveAlgorithm(cursol+1,aBanboo,bBanboo+l[cursol],cBanboo)+10
	
	return3 = solveAlgorithm(cursol+1,aBanboo,bBanboo,cBanboo+l[cursol])+10
	minReturn = min(return0,return1,return2,return3)
	return minReturn

solution = solveAlgorithm(0,0,0,0)
print("{}".format(solution))

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





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






def recur_function(a, b, c, n):
    if n == N:
        return abs(a - A) + abs(b - B) + abs(c - C) if min(a, b, c) > 0 else 10**9
    ret0 = recur_function(a + L[n], b, c, n + 1) + 10 if a > 0 else recur_function(a + L[n], b, c, n + 1)
    ret1 = recur_function(a, b + L[n], c, n + 1) + 10 if b > 0 else recur_function(a, b + L[n], c, n + 1)
    ret2 = recur_function(a, b, c + L[n], n + 1) + 10 if c > 0 else recur_function(a, b, c + L[n], n + 1)
    ret3 = recur_function(a, b, c, n + 1)
    return min(ret0, ret1, ret2, ret3)

print(recur_function(0, 0, 0, 0))

Solution (Python):
a, b, c, l_list = 0, 0, 0, []


def dfs(l_key, a_sum, b_sum, c_sum):
    if l_key == len(l_list):
        if min(a_sum, b_sum, c_sum) > 0:
            return abs(a - a_sum) + abs(b - b_sum) + abs(c - c_sum) - 30
        else:
            return 1 << 20

    l_value = l_list[l_key]
    ret0 = dfs(l_key + 1, a_sum, b_sum, c_sum)
    ret1 = dfs(l_key + 1, a_sum + l_value, b_sum, c_sum) + 10
    ret2 = dfs(l_key + 1, a_sum, b_sum + l_value, c_sum) + 10
    ret3 = dfs(l_key + 1, a_sum, b_sum, c_sum + l_value) + 10

    return min(ret0, ret1, ret2, ret3)


def main():
    global a, b, c, l_list

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

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


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):
def compute():
    from sys import stdin
    N, A, B, C = list(map(int, stdin.readline().split()))
    l = list(int(stdin.readline().split()[0]) for _ in range(N))

    dp = {}
    abclist = [A, B, C]
    def f(bamboo, remain, abc):
        if remain == 0:
            if abc >= 2:
                return 0
            
            return f(bamboo, abclist[abc+1], abc+1)

        args = (bamboo, remain, abc)
        if args in dp:
            return dp[args]
        dp[args] = 10000

        for x in range(N):
            if (bamboo & (1<<x)) == 0:
                nexbam = (bamboo | (1<<x))
                mp = abs(remain-l[x])
                dp[args] = min(dp[args], mp + f(nexbam, 0, abc))
                dp[args] = min(dp[args], 10 + f(nexbam, remain-l[x], abc))

        return dp[args]

    print(f(0, abclist[0], 0))


if __name__ == "__main__":
    compute()

Solution (Python):
from itertools import product


def main():
    tmp = [0] * 4
    N, A, B, C = map(int, input().split())
    L = [int(input()) for _ in range(N)]
    ans = float("inf")
    for i in range(N):
        for j in range(N):
            for k in range(N):
                if i == j or j == k or k == i:
                    continue
                tmp = [0, A-L[i], B-L[j], C-L[k]]
                rem = [L[x] for x in range(N) if x not in (i, j, k)]
                for p in product([0, 1, 2, 3], repeat=len(rem)):
                    tmp2 = [x for x in tmp]
                    for pi in range(len(p)):
                        tmp2[p[pi]] -= rem[pi]
                    swaps = len(list(filter(lambda x: x != 0, p)))
                    ans = min(ans, sum(map(abs, tmp2[1:])) + 10 * swaps)
                ans = min(ans, sum(map(abs, tmp[1:])))
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
z = list(map(int,input().split()))
n = z[0]
l = [int(input()) for _ in range(n)]

ans = float('inf')
loop = 0
while loop < 4**n:
    ps = [loop // (4**j) % 4 for j in range(n)]
    loop += 1
    s = [[], [], [], []]
    for cnt,p in enumerate(ps):
        s[p].append(l[cnt])
    if not all(s[1:]):
        continue
    score = [(len(s[i]) - 1) * 10 + abs(sum(s[i]) - z[i]) for i in range(4)]
    ans = min(ans, sum(score[1:]))

print(ans)

Solution (Python):
N,A,B,C = map(int, input().split())

bms = [int(input()) for _ in range(N)]

def dfs(cur,a,b,c):
    if cur == N:
        s = abs(A-a)+abs(B-b)+abs(C-c)-30 if min(a,b,c) > 0 else 10**9
        return s
    s_0 = dfs(cur+1,a,b,c)
    s_a = dfs(cur+1,a+bms[cur],b,c) + 10
    s_b = dfs(cur+1,a,b+bms[cur],c) + 10
    s_c = dfs(cur+1,a,b,c+bms[cur]) + 10
    return min(s_0,s_a,s_b,s_c)

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

Solution (Python):

import itertools



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



iterobj = itertools.product(range(4),repeat=N)

ans = 10**8

for use in iterobj:

    if 1 in use and 2 in use and 3 in use:

        synth = [0,0,0,0]

        for m, u in  zip(materials, use):
            synth[u] += m

        mp = 10 * (use.count(1) + use.count(2) + use.count(3) - 3)

        mp += abs(A-synth[1]) + abs(B-synth[2]) + abs(C-synth[3])

        ans = min(ans, mp)

print(ans)

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

def dfs(depth, a, b, c):
	if depth == N:
		if a == 0 or b == 0 or c == 0:
			return 1e9
		return abs(A - a) + abs(B - b) + abs(C - c)
	
	x = dfs(depth + 1, a, b, c)
	w = dfs(depth + 1, a, b, c + inputs[depth]) + 10 * (c != 0)
	y = dfs(depth + 1, a + inputs[depth], b, c) + 10 * (a != 0)
	z = dfs(depth + 1, a, b + inputs[depth], c) + 10 * (b != 0)
	
	return min(x, y, z, w)

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

Solution (Python):
import numpy as numpy

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

def dfs(n,a,b,c):
  if n == N:
    return INF if min(a, b, c) == 0 else abs(a - A) + abs(b - B) + abs(c - C) - 30
  res0 = dfs(n + 1, a, b, c)
  res1 = dfs(n + 1, l[n] + a, b, c) + 10
  res2 = dfs(n + 1, a, l[n] + b, c) + 10
  res3 = dfs(n + 1, a, b, l[n] + c) + 10
  return min(res0, res1, res2, res3)

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):
from itertools import product
N, A, B, C = map(int, input().split())
L = []
for i in range(N):
  L.append(int(input()))
  
hand = ['n', 'a', 'b', 'c']

ans = 1e12
for h in product(hand, repeat=N):
  if len(set(h) & set(['a', 'b', 'c'])) < 3:
    continue
  cost = 0
  work_k = {'a':0, 'b':0, 'c':0}
  
  for i in range(N):
    
    if h[i] == 'n':
      continue
    if work_k[h[i]] > 0:
      cost += 10
    work_k[h[i]] = work_k[h[i]] + L[i]
    
  cost += abs(A - work_k['a'])
  cost += abs(B - work_k['b'])
  cost += abs(C - work_k['c'])
  
  ans = min(cost, ans)

print(ans)

Solution (Python):
import numpy as np

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






def count(x,ls):
    try:
        x.index(0)
        x.index(1)
        x.index(2)        
    except:
        return False
    A = np.zeros(len(goals))
    for i,l in enumerate(ls):
        add_ind = x[i]
        if add_ind==3:
            pass
        else:
            A[add_ind] += l
    combine_MP = 0
    for i in range(3):
        combine_MP += 10*(x.count(i)-1)
    return A, combine_MP
    
    
score_min = 100000
for N in range(4**8):
    x = []
    for j in range(len(ls)):
        x.append(N % 4)
        N = N // 4 
    try:
        A, combine_MP = count(x,ls)
        score = np.abs(A-np.array(goals)).sum() + combine_MP
        if score_min >= score:
            score_min = score
    except:
        pass
print(int(score_min))

Solution (Python):
def dfs(i, A, B, C):
    global ans
    if i == n:
        if A and B and C:
            s = 0
            ABC = [A, B, C]
            for i in range(3):
                s += (len(ABC[i]) - 1) * 10 + abs(sum(ABC[i]) - abc[i])
            ans = min(ans, s)
    else:
        dfs(i + 1, A + [l[i]], B, C)
        dfs(i + 1, A, B + [l[i]], C)
        dfs(i + 1, A, B, C + [l[i]])
        dfs(i + 1, A, B, C)

n, a, b, c = map(int, input().split())
l = [int(input()) for i in range(n)]
abc = [a, b, c]
ans = float("inf")
dfs(0, [], [], [])
print(ans)

Solution (Python):
N, A, B, C = map(int, input().split())
l = []
for i in range(N):
    x = int(input())
    l.append(x)
ans = float("inf")
def dfs(depth, li):
    if depth == N:
        if len(li[0]) > 0 and len(li[1]) > 0 and len(li[2]) > 0:
            global ans
            x = abs(sum(li[0]) - A) + abs(sum(li[1]) - B) + abs(sum(li[2]) - C) + max(0, 10*(len(li[0])-1)) + max(0, 10*(len(li[1])-1)) + max(0, 10*(len(li[2])-1))
            if x < ans:
                ans = x

    else:
        dfs(depth + 1, [li[0]+[l[depth]]]+li[1:])
        dfs(depth + 1, li[:1]+[li[1]+[l[depth]]]+li[2:])
        dfs(depth + 1, li[:2]+[li[2]+[l[depth]]]+li[3:])
        dfs(depth + 1, li[:3]+[li[2]+[l[depth]]])


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

Solution (Python):
N, A, B, C = map(int, input().split())
L = [int(input()) for i 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+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
n, A, B, C = map(int, input().split())
l = [int(input()) for _ in range(n)]
ans = 10**9
for v in product([0, 1, 2, 3], repeat=n):
    a, b, c = 0, 0, 0
    cost = 0
    for i in range(n):
        if v[i] == 0:
            if a > 0:
                cost += 10
            a += l[i]
        elif v[i] == 1:
            if b > 0:
                cost += 10
            b += l[i]
        elif v[i] == 2:
            if c > 0:
                cost += 10
            c += l[i]
    if min(a, b, c) > 0:
        cost += abs(a-A) + abs(b-B) + abs(c-C)
        ans = min(ans, cost)

print(ans)

Solution (Python):
n, A, B, C = map(int, input().split())
l = [int(input()) for _ in range(n)]
inf = float("inf")
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):
want = [0,0,0]
ans = []
N,want[0],want[1],want[2] = map(int,input().split())
L = []
for _ in range(N):
    L.append(int(input()))
table = [0,1,2,-1]
import itertools as it
c = list(it.product(table, repeat=N))
for x in c:
    ABC = [0,0,0,0]
    cnt = -3
    for i in range(len(x)):
        ABC[x[i]] += L[i]
        if x[i] != -1:
            cnt += 1
    t = ABC.pop(-1)
    if 0 in ABC:
        continue
    val = sum(map(lambda x:abs(x[0]-x[1]),list(zip(ABC,want))))
    val += 10*cnt
    ans.append(val)
print(min(ans))

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

table = [0,1,2,-1]
import itertools as it
c = list(it.product(table, repeat=N))
for x in c:
    A = 0
    B = 0
    C = 0
    cnt = -3
    z = list(zip(x,L))
    for y in z:
        if y[0] == 0:
            A += y[1]
            cnt += 1
        elif y[0] == 1:
            B += y[1]
            cnt += 1
        elif y[0] == 2:
            cnt += 1
            C += y[1]
        else:
            pass
    if A*B*C == 0:
        continue
    ans.append(abs(A-want[0])+abs(B-want[1])+abs(C-want[2])+cnt*10)
print(min(ans))

Solution (Python):
N, A, B, C = map(int, input().split(" "))
l = [int(input()) for i in range(N)]
INF = 10 ** 9
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 INF
    ret1=dfs(cnt+1,a+l[cnt],b,c)+10
    ret2=dfs(cnt+1,a,b+l[cnt],c)+10
    ret3=dfs(cnt+1,a,b,c+l[cnt])+10
    ret4=dfs(cnt+1,a,b,c)
    return min(ret1,ret2,ret3,ret4)

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

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

table = [0,1,2,-1]
import itertools as it
c = list(it.product(table, repeat=N))
for x in c:
    A = 0
    B = 0
    C = 0
    cnt = -3
    z = list(zip(x,L))
    for y in z:
        if y[0] == 0:
            A += y[1]
            cnt += 1
        elif y[0] == 1:
            B += y[1]
            cnt += 1
        elif y[0] == 2:
            cnt += 1
            C += y[1]
        else:
            pass
    if A*B*C == 0:
        continue
    ans.append(abs(A-want[0])+abs(B-want[1])+abs(C-want[2])+cnt*10)
print(min(ans))

Solution (Python):
n, a, b, c = map(int, input().split())
index=0
listL = []
while index < n:
    l = int(input())
    listL.append(l)
    index+=1
stateL  = [0]*n

def calculater(listL, stateL, a, b, c):
    oneL = [0, 0, 0]  
    twowL = [0, 0, 0]
    threeL = [0, 0, 0]
    index = 0
    while index < len(stateL):
        if stateL[index] == 1:
            oneL[0] += 1
            oneL[1] += listL[index]
        elif stateL[index] == 2:
            twowL[0] += 1
            twowL[1] += listL[index]
        elif stateL[index] == 3:
            threeL[0] += 1
            threeL[1] += listL[index]
        index += 1
    oneL[2] += 10*(oneL[0]-1)+abs(a-oneL[1])
    twowL[2] += 10*(twowL[0]-1)+abs(b-twowL[1])
    threeL[2] += 10*(threeL[0]-1)+abs(c-threeL[1])
    return oneL[2]+twowL[2]+threeL[2]

def loopMaker(n, stateL, minMP):
    if n >= len(listL):
        return minMP
    else:
        index=0
        while index < 4:
            stateL[n] = index
            if n == len(stateL)-1:
                if 1 in stateL and 2 in stateL and 3 in stateL:
                    mp = calculater(listL, stateL, a, b, c)
                else:
                    mp = 10000
                if mp < minMP:
                    minMP = mp
            minMP = loopMaker(n+1, stateL, minMP)
            index+=1
        return minMP

minMP = loopMaker(0, stateL, 10000)
print(minMP)

Solution (Python):

import numpy as np

N, A, B, C = map(int, input().split(' '))
ls = []
for _ in range(N):
    ls.append(int(input()))
n = 0
INF = 10 ** 9

def dfs(n, a, b, c):
    if n == N:
        return INF if min(a, b, c) == 0 else abs(a-A) + abs(b-B) + abs(c-C) - 30
    res0 = dfs(n+1, a, b, c)
    res1 = dfs(n+1, a+ls[n], b, c) + 10
    res2 = dfs(n+1, a, b+ls[n], c) + 10
    res3 = dfs(n+1, a, b, c+ls[n]) + 10
    return min(res0, res1, res2, res3)

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

Solution (Python):
import sys
N,A,B,C = [int(n) for n in input().split()]

l = [int(input()) for _ in range(N)]


INF = 10 **18
def dfs(p,a,b,c):
    if p == N:
        return abs(a-A) + abs(b-B) + abs(c-C) - 30 if min(a,b,c) > 0  else INF
    ans0 = dfs(p+1,a,b,c)
    ans1 = dfs(p+1,a+l[p],b,c) + 10
    ans2 = dfs(p+1,a,b+l[p],c) + 10
    ans3 = dfs(p+1,a,b,c+l[p]) + 10
    return min(ans0,ans1,ans2,ans3)

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

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


label = ['a', 'b', 'c', 'd']
list_init = []
for i in label:
    for j in label:
        list_init.append([i, j])

def extend(list):
    if n == 2:
        return list
    list_new = []
    for i in list[:]:
        for j in label:
            i.append(j)
            list_new.append(i[:])
            i.pop()
    if len(list_new[0]) == n:
        return list_new
    else:
        return extend(list_new[:])

list_created = extend(list_init[:])
mp = []
INF = 10 ** 9
for i in list_created:
    s = set(i)
    try: s.remove('d')
    except KeyError: pass
    if len(s) < 3:
        mp.append(INF)
        continue

    la, lb, lc = 0, 0, 0
    na, nb, nc = 0, 0, 0
    for j in range(len(i)):
        if i[j] == 'a':
            la += l[j]
            na += 1
        elif i[j] == 'b':
            lb += l[j]
            nb += 1
        elif i[j] == 'c':
            lc += l[j]
            nc += 1
    mp.append(abs(la-a) + abs(lb-b) + abs(lc-c) + 10*(na + nb + nc - 3))

print(min(mp))

Solution (Python):
import numpy as np
n,A,B,C=list(map(int,input().split(" ")))
l_list = [0]*n
for i in range(n):
    l_list[i] = int(input())
    
flags = [0]*n

anss = []

def f(d):
    if d < n:
        for i in [0,1,2,3]:
            flags[d] = i
            f(d+1)
    else:
        if not (flags.count(1)>0 and flags.count(2)>0 and flags.count(3)>0):
            return
        tA = A
        tB = B
        tC = C
        for i in range(n):
            if flags[i] == 1:
                tA -= l_list[i]
            elif flags[i] == 2:
                tB -= l_list[i]
            elif flags[i] == 3:
                tC -= l_list[i]
        ans = 0
        ans += max(0,(flags.count(1)-1)*10)
        ans += max(0,(flags.count(2)-1)*10)
        ans += max(0,(flags.count(3)-1)*10)
        ans += abs(tA)+abs(tB)+abs(tC)
        anss.append(ans)
f(0)
print(min(anss))

Solution (Python):
N, A, B, C = map(int, input().split())
l = [int(input()) for i in range(N)]
INF = 10 ** 9
def calc(take, a, b, c):
    if take == N:
        return abs(a-A)+abs(b-B)+abs(c-C) -30 if min(a,b,c)>0 else INF
    ret0 = calc(take+1, a, b, c)
    ret1 = calc(take+1, a+l[take], b, c) + 10
    ret2 = calc(take+1, a, b+l[take], c) + 10
    ret3 = calc(take+1, a, b, c+l[take]) + 10
    return min(ret0, ret1, ret2, ret3)
    
print(calc(0,0,0,0))

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


def dfs(depth, a, b, c):
    if depth == N:
        
        return abs(A - a) + abs(B - b) + abs(C - c) - 30 if min(a, b, c) > 0 else INF
    ret0 = dfs(depth + 1, a, b, c)  
    ret1 = dfs(depth + 1, a + bamboo[depth], b, c) + 10  
    ret2 = dfs(depth + 1, a, b + bamboo[depth], c) + 10  
    ret3 = dfs(depth + 1, a, b, c + bamboo[depth]) + 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
  else:
    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))