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 itertools
N, A, B, C = map(int, input().split())
L = [int(input()) for i in range(N)]
ans = float('inf')
for bit in itertools.product(range(4), repeat=N):
    ABC = [0]*3
    cost = 0
    for i, abc in enumerate(bit):
        if abc == 3:
            continue
        ABC[abc] += L[i]
        if ABC[abc] != L[i]:
            cost += 10
    if 0 in ABC:
        continue
    cost += abs(ABC[0] - A) + abs(ABC[1] - B) + abs(ABC[2] - C)
    ans = min(ans, cost)
print(ans)

Solution (Python):
import itertools
n, a, b, c = map(int, input().split())
l = [int(input()) for _ in range(n)]
pat = list(itertools.product([0, 1, 2, 3], repeat=n))
ans = 10**10
for p in pat:
    aa, bb, cc = 0, 0, 0
    mp = -30
    for i in range(n):
        if p[i] == 0:
            pass
        elif p[i] == 1:
            aa += l[i]
            mp += 10
        elif p[i] == 2:
            bb += l[i]
            mp += 10
        else:
            cc += l[i]
            mp += 10
    if aa == 0 or bb == 0 or cc == 0:
        continue
    abc = [aa, bb, cc]
    pat2 = list(itertools.permutations([0, 1, 2]))
    for q in pat2:
        mp2 = 0
        mp2 += abs(a - abc[q[0]])
        mp2 += abs(b - abc[q[1]])
        mp2 += abs(c - abc[q[2]])
        ans = min(ans, mp + mp2)
print(ans)

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 

from decimal import *



N, A, B, C = MAP()

l = [INT() for _ in range(N)]

ans = INF
for x in product(range(4), repeat=N):
	tmp = 0
	bamboo = [0]*4 
	for i in range(N):
		if 0 < x[i] and bamboo[x[i]]:
			tmp += 10
		bamboo[x[i]] += l[i]

	if 0 in bamboo[1:]:
		continue

	tmp += abs(bamboo[1]-A) + abs(bamboo[2]-B) + abs(bamboo[3]-C)

	ans = min(ans, tmp)

print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
N, A, B, C = map(int, input().split())
L = [int(input()) for i in range(N)]
INF = float('inf')
def dfs(i,a,b,c):
    
    if i == N:
        if a==0 or b==0 or c==0:
            return INF
        else:
            return abs(a-A) + abs(b-B) + abs(c-C)
    
    ans0 = dfs(i+1, a, b, c)
    ans1 = dfs(i+1, a+L[i], b, c) + (10 if a != 0 else 0)
    ans2 = dfs(i+1, a, b+L[i], c) + (10 if b != 0 else 0)
    ans3 = dfs(i+1, a, b, c+L[i]) + (10 if c != 0 else 0)
    
    ans = min(ans0, ans1, ans2, ans3)
    return ans

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

if __name__ == '__main__':
    main()

Solution (Python):
from itertools import groupby, accumulate, product, permutations, combinations
def calc(x,X):
  n = len(x)
  if n==0:
    return 10**10
  ans = abs(sum(x)-X)+(n-1)*10
  return ans

def solve():
  ans = 10**10
  N, A, B, C = map(int, input().split())
  L = [int(input()) for _ in range(N)]
  for p in product(['A','B','C','D'],repeat=N):
    a,b,c = [],[],[]
    cnt = 0
    for i in range(N):
      if p[i]=='A':
        a.append(L[i])
      elif p[i]=='B':
        b.append(L[i])
      elif p[i]=='C':
        c.append(L[i])
    cnt += calc(a,A)+calc(b,B)+calc(c,C)
    ans = min(ans,cnt)
  return ans
print(solve())

Solution (Python):
from itertools import groupby, accumulate, product, permutations, combinations
def calc(x,X):
  n = len(x)
  ans = 10**10
  for q in product([0,1],repeat=n):
    point = 0
    cnt = 0
    for i in range(n):
      if q[i]==1:
        if cnt>0:
          point += 10
        cnt += x[i]
    if cnt>0:
      point += abs(cnt-X)
    else:
      point = 10**10
    ans = min(point,ans)
  return ans

def solve():
  ans = 10**10
  N, A, B, C = map(int, input().split())
  L = [int(input()) for _ in range(N)]
  for p in product(['A','B','C','D'],repeat=N):
    a,b,c = [],[],[]
    cnt = 0
    for i in range(N):
      if p[i]=='A':
        a.append(L[i])
      elif p[i]=='B':
        b.append(L[i])
      elif p[i]=='C':
        c.append(L[i])
    cnt += calc(a,A)+calc(b,B)+calc(c,C)
    ans = min(ans,cnt)
  return ans
print(solve())

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

import itertools
ans = 10**18
for p in itertools.product(range(4), repeat=n):
    C = [0]*3
    temp = [0]*3
    for i in range(n):
        if p[i] == 3:
            continue
        C[p[i]] += 1
        temp[p[i]] += L[i]
    flag = True
    for i in range(3):
        if C[i] == 0:
            flag = False
            break
    if not flag:
        continue
    mp = 0
    for i in range(3):
        mp += 10*(C[i]-1)
        mp += abs(temp[i]-T[i])
    ans = min(ans, mp)
print(ans)

Solution (Python):

from itertools import product

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

    ans = 10**9
    ite = product(range(4),repeat=n)
    ite = list(ite)
    for it in ite:
        bamboosl = [ [],[],[] ]
        cost = -30
        for i,v in enumerate(it):
            if v != 3:
                bamboosl[v].append(ll[i])
                cost += 10

        continue_f = False    
        for bamboos in bamboosl:
            if not bamboos: continue_f = True
        if continue_f: continue

        longs = []
        for bamboos in bamboosl:
            curr_l = sum(bamboos)
            longs.append(curr_l)
        longs.sort()

        for v1,v2 in zip(targetl,longs):
            cost += abs(v1-v2)
            
        ans = min(ans,cost)

    print(ans)


if __name__ == "__main__":
    main()

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

ans = float('inf')
for a in range(1<<N):
    at = []
    for i in range(N):
        if a&(1<<i):
            at.append(L[i])
    if not at: continue
    ap = 10*(len(at)-1) + abs(A - sum(at))
    for b in range(1<<N):
        if a&b: continue
        bt = []
        for i in range(N):
            if b&(1<<i):
                bt.append(L[i])
        if not bt: continue
        bp = 10*(len(bt)-1) + abs(B - sum(bt))
        for c in range(1<<N):
            if (a&c) or (b&c): continue
            ct = []
            for i in range(N):
                if c&(1<<i):
                    ct.append(L[i])
            if not ct: continue
            cp = 10*(len(ct)-1) + abs(C - sum(ct))
            ans = min(ans, ap+bp+cp)
print(ans)

Solution (Python):
from itertools import product

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

minscore=10**9
for p in product(range(-1,3),repeat=N):
  flag=0
  score = 0
  n_abc=[0,0,0]
  sumlen = [0,0,0]
  for i in range(N):
    if p[i] != -1:
      n_abc[p[i]] += 1
      sumlen[p[i]] += l[i]
  for j in range(3):
    if n_abc[j] == 0:
      flag=1
      break
    score += (n_abc[j]-1)*10 + abs(sumlen[j]-[A,B,C][j])
    
  if flag:
    continue
    
  if score < minscore:
    minscore = score
    
print(minscore)

Solution (Python):
import sys
input = sys.stdin.readline
N, A, B, C = map(int, input().split())
L = [int(input()) for i in range(N)]
INF = float('inf')

def dfs(i, a, b, c):
    if i == N:
        if a == 0 or b == 0 or c == 0:
            return INF
        else:
            return abs(a-A) + abs(b-B) + abs(c-C)
    ans0 = dfs(i+1, a, b, c)

    ans1 = dfs(i+1, a+L[i], b, c) + (10 if a != 0 else 0)
    ans2 = dfs(i+1, a, b+L[i], c) + (10 if b != 0 else 0)
    ans3 = dfs(i+1, a, b, c+L[i]) + (10 if c != 0 else 0)

    return min(ans0, ans1, ans2, ans3)

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

if __name__ == '__main__':
    main()

Solution (Python):
N,A,B,C= list(map(int,input().split()))
l=[]
Inf=float("Inf")
for i in range(N):l.append(int(input()))
def Answer(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
   pt1=Answer(cnt+1,a,b,c)
   pt2=Answer(cnt+1,a+l[cnt],b,c)+10
   pt3=Answer(cnt+1,a,b+l[cnt],c)+10
   pt4=Answer(cnt+1,a,b,c+l[cnt])+10
   return(min(pt1,pt2,pt3,pt4))
print(Answer(0,0,0,0))

Solution (Python):
from itertools import *
N,A,B,C = map(int, input().split())
L = [int(input()) for n in range(N)]
ans = []

for i in product(range(4),repeat=N):
  a = 0
  b = 0
  c = 0
  d = 0
  for j in range(N):
    if i[j]:
      d+=1
      if i[j]==1:
        a+=L[j]
      elif i[j]==2:
        b+=L[j]
      else:
        c+=L[j]
  if a*b*c:
    ans+=[abs(A-a)+abs(B-b)+abs(C-c)+10*(d-3)]

print(min(ans))

Solution (Python):
from itertools import product
p=4
n,a,b,c=map(int,input().split())
banboo=[0]*n
for i in range(n):
    banboo[i]=int(input())

Bit_4=list(product(range(p),repeat=n))
ans=10**6
for Bi in Bit_4:
    tmp=[0]*4
    magic=0
    if 1 in Bi and 2 in Bi and 3 in Bi:
        for i in range(n):
            tmp[Bi[i]]+=banboo[i]
            if tmp[Bi[i]]!=banboo[i] and Bi[i]!=0:
                magic+=10
        magic+=abs(tmp[1]-a)
        magic+=abs(tmp[2]-b)
        magic+=abs(tmp[3]-c)
        ans=min(magic,ans)
print(ans)

Solution (Python):





















































































def calculation(lines):
    
    
    N, A, B, C = list(map(int, lines[0].split()))
    
    values = list()
    for i in range(N):
        values.append(int(lines[i+1]))

    patterns = get_patterns(N)

    result = None

    

    
    

    

    for pattern in patterns:

        
        a = 0
        b = 0
        c = 0
        mp = 0
        for i, char in enumerate(pattern):
            if char == '1':
                if a > 0:
                    mp += 10
                a += values[i]
            elif char == '2':
                if b > 0:
                    mp += 10
                b += values[i]
            elif char == '3':
                if c > 0:
                    mp += 10
                c += values[i]
        mp += abs(A-a) + abs(B-b) + abs(C-c)

        

        if result is None:
            result = mp
        else:
            if result > mp:
                
                result = mp

    return [result]


def get_patterns(n):
    lst = ['0', '1', '2', '3']
    _, patterns = get_patterns_internal(n-1, lst)
    return [pattern for pattern in patterns if '1' in pattern and '2' in pattern and '3' in pattern]


def get_patterns_internal(n, lst):
    if n == 0:
        return 0, lst
    else:
        ret = list()
        for item in lst:
            ret.append(item + '0')
            ret.append(item + '1')
            ret.append(item + '2')
            ret.append(item + '3')
        return get_patterns_internal(n-1, ret)



def get_input_lines():
    line = input()
    N, A, B, C = list(map(int, line.split()))
    lines = list()
    lines.append(line)
    for _ in range(N):
        lines.append(input())
    return lines



def get_testdata(pattern):
    if pattern == 1:
        lines_input = ['5 100 90 80', '98', '40', '30', '21', '80']
        lines_export = [23]
    if pattern == 2:
        lines_input = ['8 100 90 80', '100', '100', '90', '90', '90', '80', '80', '80']
        lines_export = [0]
    if pattern == 3:
        lines_input = ['8 1000 800 100', '300', '333', '400', '444', '500', '555', '600', '666']
        lines_export = [243]
    return lines_input, lines_export



def get_mode():
    import sys
    args = sys.argv
    if len(args) == 1:
        mode = 0
    else:
        mode = int(args[1])
    return mode



def main():
    import time
    started = time.time()
    mode = get_mode()
    if mode == 0:
        lines_input = get_input_lines()
    else:
        lines_input, lines_export = get_testdata(mode)

    lines_result = calculation(lines_input)

    for line_result in lines_result:
        print(line_result)

    
    
    
    
    
    
    
    
    
    
    



if __name__ == '__main__':
    main()

Solution (Python):
from itertools import permutations
n,a,b,c=map(int,input().split())
target=[a,b,c]
lst=[int(input()) for _ in range(n)]
p=list(permutations(lst,3))
ans=float("inf")

def Base_10_to_n(X, n,keta):
    X_dumy = X
    out = ''
    while X_dumy>0:
        out = str(X_dumy%n)+out
        X_dumy = int(X_dumy/n)
    out="0"*(keta-len(out))+out
    return out
for q in range(len(p)):
    base_tri=list(p[q])
    extra=lst[:]
    for i in base_tri:
        extra.remove(i)
    tmp=0
    for i in range(3):
        tmp+=abs(base_tri[i]-target[i])
    ans=min(tmp,ans)
    for i in range(1,4**(n-3)):
        tmp=0
        tri=base_tri[:]
        yonshin=Base_10_to_n(i,4,n-3)
        for j in range(n-3):
            if yonshin[j]=="1":
                tri[0]+=extra[j]
                tmp+=10
            elif yonshin[j]=="2":
                tri[1]+=extra[j]
                tmp+=10
            elif yonshin[j]=="3":
                tri[2]+=extra[j]
                tmp+=10
        for j in range(3):
            tmp+=abs(tri[j]-target[j])
        ans=min(tmp,ans)
print(ans)

Solution (Python):
from itertools import product
n, a, b, c = map(int, input().split())
l = [int(input()) for i in range(n)]

ans = float('inf')
for choice in product([0, 1, 2, 3], repeat=n):
    items = [0] * 3
    totals = [0] * 3
    temp = 0
    if min([choice.count(i) for i in range(3)]) == 0: continue
    for i, ch in enumerate(choice):
        if ch == 3: continue
        totals[ch] += l[i]
        items[ch] += 1
        if items[ch] > 1:
            temp += 10
    temp+=abs(a-totals[0])
    temp+=abs(b-totals[1])
    temp+=abs(c-totals[2])
    ans = min(ans, temp)
print(ans)

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

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

    res0 = dfs(cur+1,a,b,c)
    res1 = dfs(cur+1,a+l[cur],b,c)+10
    res2 = dfs(cur+1,a,b+l[cur],c)+10
    res3 = dfs(cur+1,a,b,c+l[cur])+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 _ in range(n)]
INF = 10**9

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

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

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

ans = 10**9
from itertools import product
for comb in product([0, 1, 2, 3], repeat=n):
    if len(set(comb)) in [1, 2]:
        continue
    
    ls = [[], [], []]
    for i, c in enumerate(comb):
        if c == 3:
            continue
        ls[c].append(L[i])

    mps = 0
    for idx, ll in enumerate(ls):
        if len(ll) == 0:
            break
        tmp = (len(ll)-1)*10
        mps += tmp
        mps += abs(targets[idx] - sum(ll))
    else:
        ans = min(ans, mps)
    
print(ans)

Solution (Python):




import copy
from itertools import combinations
import sys
input = sys.stdin.readline  
N,A,B,C = (int(i) for i in input().split())
l =[0]*N
for i in range(N):
    l[i] = int(input())


mp=[]
for na in range(1,N-1):
    for ja in combinations(l,na):

        l_b =copy.copy(l)
        for i2 in ja:
            if i2 in l_b:
                l_b.remove(i2)
        for nb in range(1,N):
            for jb in combinations(l_b ,nb):

                l_c =copy.copy(l_b)
                for i3 in jb:
                    if i3 in l_c:
                        l_c.remove(i3)
                for nc in range(1,N+1):
                    for jc in combinations(l_c ,nc):
                        
                        
                        AA =abs(A-sum(ja)) +10*(na-1)
                        BB =abs(B-sum(jb)) +10*(nb-1)
                        CC =abs(C-sum(jc)) +10*(nc-1)
                        mp.append(AA +BB +CC)


print(min(mp))

Solution (Python):
import sys
import itertools

import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines



N, A, B, C = map(int, input().split())
l = [int(input()) for _ 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
    res = dfs(cur + 1, a, b, c)
    res = min(res, dfs(cur + 1, a + l[cur], b, c) + 10)
    res = min(res, dfs(cur + 1, a, b + l[cur], c) + 10)
    res = min(res, dfs(cur + 1, a, b, c + l[cur]) + 10)
    return res
print(dfs(0, 0, 0, 0))

Solution (Python):
N,A,B,C = map(int, input().split())
l = list(int(input()) for _ in range(N))
inf = 10 ** 9
def dfs(cur,a,b,c):
    if cur == N:
        return abs(a-A) + abs(b-B) + abs(c-C) -30 if min(a,b,c) > 0 else inf
    re0 = dfs(cur+1, a, b, c)
    re1 = dfs(cur+1, a+l[cur], b, c)+10
    re2 = dfs(cur+1, a, b+l[cur], c) + 10
    re3 = dfs(cur+1, a, b, c+l[cur]) + 10
    return min (re0, re1, re2, re3)
print(dfs(0,0,0,0))

Solution (Python):
import sys
sys.setrecursionlimit(10**6)
n, A, B, C =map(int,input().split())
l=[]
for i in range(n):
    l.append(int(input()))
inf=10**9
"""
解法
それぞれの竹について「Aの材料」、「Bの材料」、「Cの材料」、「使わない」の4択を決める(4**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):
def main():
    n, a, b, c = list(map(int, input().split()))
    L = [int(input()) for _ in range(n)]
    INF = 1000000
    def dfs(i, la, lb, lc):
        if i == n:
            return abs(la - a) + abs(lb - b) + abs(lc - c) if min(la, lb, lc) > 0 else INF
        res = []
        res.append(dfs(i + 1, la, lb, lc))
        res.append(dfs(i + 1, la + L[i], lb, lc) + 10 if la != 0 else dfs(i + 1, la + L[i], lb, lc))
        res.append(dfs(i + 1, la, lb + L[i], lc) + 10 if lb != 0 else dfs(i + 1, la, lb + L[i], lc))
        res.append(dfs(i + 1, la, lb, lc + L[i]) + 10 if lc != 0 else dfs(i + 1, la, lb, lc + L[i]))
        return min(res)
    print(dfs(0, 0, 0, 0))

if __name__ == '__main__':
    main()

Solution (Python):
import sys,math,collections,itertools
input = sys.stdin.readline

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

use_list = list(itertools.product(range(4),repeat = N))
point = float('inf')

for i in range(len(use_list)):
    ABC = [0]*3
    count = [0]*3
    if (0 not in use_list[i]) or(1 not in use_list[i]) or (2 not in use_list[i]):
        continue
    for j in range(len(use_list[i])):
        if use_list[i][j] != 3:
            ABC[use_list[i][j]] += l[j]
            count[use_list[i][j]] += 1
    p = (sum(count)-len(count))*10+abs(ABC[0]-A)+abs(ABC[1]-B)+abs(ABC[2]-C)
    point = min(point,p)   
print(point)

Solution (Python):





def main():
    N, A, B, C = map(int, input().split())
    ls = [None] * N
    for i in range(N):
        ls[i] = int(input())

    abc_mp = []

    def rec(i, a, b, c, mp, ls):
        if i == len(ls):
            if a > 0 and b > 0 and c > 0:
                abc_mp.append([a, b, c, mp-30])
        else:
            rec(i+1, a+ls[i], b, c, mp+10, ls)
            rec(i+1, a, b+ls[i], c, mp+10, ls)
            rec(i+1, a, b, c+ls[i], mp+10, ls)
            rec(i+1, a, b, c, mp, ls)

    rec(0, 0, 0, 0, 0, ls)
    a0, b0, c0, mp0 = abc_mp[0]
    ans = mp0 + abs(A-a0) + abs(B-b0) + abs(C-c0)
    for a, b, c, mp in abc_mp:
        cand = mp + abs(A-a) + abs(B-b) + abs(C-c)
        if cand < ans:
            ans = cand

    return ans


print(main())

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

ans = float("inf")
def loop(K):
    global ans
    abs_A = []
    abs_B = []
    abs_C = []
    for i in range(len(K)):
        abs_A.append(abs(A - K[i]))
        abs_B.append(abs(B - K[i]))
        abs_C.append(abs(C - K[i]))
    for i in range(len(K)):
        for j in range(len(K)):
            for k in range(len(K)):
                if i != j and j != k and k != i:
                    ans = min(ans, 10*(N-len(K)) + abs_A[i] + abs_B[j] + abs_C[k])
    if len(K) > 3:
        Next = []
        for i in range(len(K)):
            for j in range(i+1, len(K)):
                for p in range(len(K)):
                    if p != i and p != j:
                        Next.append(K[p])
                Next.append(K[i] + K[j])
                loop(Next)
                Next = []

loop(T)
print(ans)

Solution (Python):
import sys

N,A,B,C = map(int,sys.stdin.readline().rstrip().split())
l = [int(sys.stdin.readline().rstrip()) for _ in range(N)]

from itertools import product



ans = 10**18
for a in list(product([1,2,3,4],repeat=N)):
    X,Y,Z = [],[],[]
    for i in range(N):
        if a[i] == 1:
            X.append(l[i])
        elif a[i] == 2:
            Y.append(l[i])
        elif a[i] == 3:
            Z.append(l[i])
    if len(X) == 0 or len(Y) == 0 or len(Z) == 0:
        continue
    else:
        a = 0
        a += 10*(len(X)+len(Y)+len(Z)-3)
        a += abs(A-sum(X)) + abs(B-sum(Y)) + abs(C-sum(Z))
        if a < ans:
            ans = a

print(ans)

Solution (Python):
import bisect
INF=10**18
n,*a=map(int,input().split())
l=[int(input()) for _ in range(n)]
ans=INF
for i in range(4**n):
  x=[[] for _ in range(3)]
  for j in range(n):
    if (i>>2*j)&1 and not (i>>2*j+1)&1:x[0].append(l[j])
    if not (i>>2*j)&1 and (i>>2*j+1)&1:x[1].append(l[j])
    if (i>>2*j)&1 and (i>>2*j+1)&1:x[2].append(l[j])
  cnt=0
  for j in range(3):
    if len(x[j])==0:cnt=INF
    cnt+=(len(x[j])-1)*10+abs(sum(x[j])-a[j])
  ans=min(ans,cnt)
print(ans)

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

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

def calc_score(group, target):
    score = 0
    if len(group) > 1:
        score += 10 * (len(group) - 1)
    length = sum(group)
    score += abs(length - target)
    return score

min_score = 10**12
for i in range(4**n):
    num = Base_10_to_n(i, 4).zfill(n)
    score = 0
    group_A = []
    group_B = []
    group_C = []
    for j in range(n):
        if num[j] == '1':
            group_A.append(bamboos[j])
        elif num[j] == '2':
            group_B.append(bamboos[j])
        elif num[j] == '3':
            group_C.append(bamboos[j])
    if len(group_A) == 0 or len(group_B) == 0 or len(group_C) == 0:
        continue
    else:
        score += calc_score(group_A, a)
        score += calc_score(group_B, b)
        score += calc_score(group_C, c)

    if score < min_score:
        min_score = score

print(min_score)

Solution (Python):
def B10N(X,B):
    if X//B!=0: return B10N(X//B,B)+str(X%B)
    return str(X%B)

N,A,B,C = (int(X) for X in input().split())
Li = [int(input()) for X in range(0,N)]
CostM = pow(10,9)
for T in range(0,pow(4,N)):
    Cho = list(B10N(T,4).zfill(N))
    if Cho.count('1')>0 and Cho.count('2')>0 and Cho.count('3')>0:
        Cost = 0
        ALi = [Li[X] for X,Y in enumerate(Cho) if Y=='1']
        BLi = [Li[X] for X,Y in enumerate(Cho) if Y=='2']
        CLi = [Li[X] for X,Y in enumerate(Cho) if Y=='3']
        SyC = (len(ALi)+len(BLi)+len(CLi)-3)*10
        LeC = abs(sum(ALi)-A)+abs(sum(BLi)-B)+abs(sum(CLi)-C)
        if SyC+LeC<CostM: CostM = SyC+LeC
print(CostM)

Solution (Python):
from functools import lru_cache
N, A, B, C, *L = map(int, open(0).read().split())


@lru_cache(None)
def popcnt(n):
    return bin(n).count('1')


@lru_cache(None)
def synth(bit):
    length = 0
    for i in range(N):
        if bit >> i & 1:
            length += L[i]
    return length


ans = 1 << 60
for bit1 in range(1, 1 << N):
    if popcnt(bit1) >= N-1:
        continue
    length1 = synth(bit1)

    for bit2 in range(1, 1 << N):
        if bit1 & bit2:
            continue
        if popcnt(bit1 | bit2) == N:
            continue
        length2 = synth(bit2)

        for bit3 in range(1, 1 << N):
            if bit1 & bit3 or bit2 & bit3:
                continue

            length3 = synth(bit3)
            c, b, a = sorted([length1, length2, length3])

            cost = 10*(popcnt(bit1 | bit2 | bit3)-3) + abs(C-c) + abs(B-b) + abs(A-a)
            if cost < ans:
                ans = cost

print(ans)

Solution (Python):
n,a,b,c=map(int,input().split())
l=[int(input())for _ in range(n)]
def dfs(i,x,y,z):
 if i==n:return abs(a-x)+abs(b-y)+abs(c-z)-30if min(x,y,z)>0else 10**9
 return min(dfs(i+1,x,y,z),dfs(i+1,x+l[i],y,z)+10,dfs(i+1,x,y+l[i],z)+10,dfs(i+1,x,y,z+l[i])+10)
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 groups in product(range(4), repeat=N):
    length_a = 0
    length_b = 0
    length_c = 0
    cost_a = -10
    cost_b = -10
    cost_c = -10

    for group, length in zip(groups, L):
        if group == 1:
            length_a += length
            cost_a += 10
        elif group == 2:
            length_b += length
            cost_b += 10
        elif group == 3:
            length_c += length
            cost_c += 10

    if 0 in {length_a, length_b, length_c}:
        continue

    ans = min(ans, sum([
        abs(A - length_a),
        abs(B - length_b),
        abs(C - length_c),
        cost_a,
        cost_b,
        cost_c,
    ]))

print(ans)

Solution (Python):
from itertools import product, permutations

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

ans = 10 ** 9
for groups in product(range(4), repeat=N):
    items = []
    group_a = []
    group_b = []
    group_c = []

    for group, length in zip(groups, L):
        if group == 0:
            items.append((length, 0))
        elif group == 1:
            group_a.append(length)
        elif group == 2:
            group_b.append(length)
        elif group == 3:
            group_c.append(length)

    if group_a:
        items.append((sum(group_a), (len(group_a) - 1) * 10))
    if group_b:
        items.append((sum(group_b), (len(group_b) - 1) * 10))
    if group_c:
        items.append((sum(group_c), (len(group_c) - 1) * 10))

    if len(items) < 3:
        continue

    for one, two, three in permutations((A, B, C), r=3):
        cost = 0
        _items = list(items)

        _items = sorted(_items, key=lambda x: (abs(x[0] - one), x[1]))
        cost += abs(_items[0][0] - one) + _items[0][1]
        _items.pop(0)

        _items = sorted(_items, key=lambda x: (abs(x[0] - two), x[1]))
        cost += abs(_items[0][0] - two) + _items[0][1]
        _items.pop(0)

        _items = sorted(_items, key=lambda x: (abs(x[0] - three), x[1]))
        cost += abs(_items[0][0] - three) + _items[0][1]

        ans = min(ans, cost)

print(ans)

Solution (Python):
N,A,B,C=map(int,input().split())
L=[int(input()) for i in range(N)]
def f(X):
  global N,A,B,C,L
  if len(X)==N:
    a,b,c=0,0,0
    for i in range(N):
      a+=X[i][0]
      b+=X[i][1]
      c+=X[i][2]
    if min(a,b,c)==0:
      return 10**16
    else:
      return abs(A-a)+abs(B-b)+abs(C-c)
  return min(f(X+[[0,0,0]]),f(X+[[L[len(X)],0,0]])+10,f(X+[[0,L[len(X)],0]])+10,f(X+[[0,0,L[len(X)]]])+10)

print(f([])-30)

Solution (Python):
import itertools
from collections import Counter

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

bb = list(itertools.product(le, repeat=n))
new = []
ans = 1145141919810

for ll in bb:
    aa = 0
    con = [0]*4
    amo = [0]*4
    for i in range(n):
        con[ll[i]] += l[i]
        amo[ll[i]] += 1
        
    if con[1] > 0 and con[2] > 0 and con[3] > 0:
        for j in range(1,4):
            aa += (amo[j] - 1) * 10
        aa += abs(con[1] - a)
        aa += abs(con[2] - b)
        aa += abs(con[3] - c)
        
        ans = min(ans,aa)
        
    else:
        continue
        
print(ans)

Solution (Python):
from itertools import product

INF = 10 ** 9

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


def estimate(lst):
    if any(not p for p in lst):
        return INF

    ret = 0
    for p, g in zip(lst, A):
        ret += abs(g - sum(p)) + (len(p) - 1) * 10
    return ret


ans = INF
for prd in product(range(4), repeat=N):
    pieces = [[] for _ in range(3)]
    for bamboo_ind, target_kadomatsu in enumerate(prd):
        if target_kadomatsu == 3: continue
        pieces[target_kadomatsu].append(L[bamboo_ind])
    if ans > (res := estimate(pieces)):
        ans = res
print(ans)