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



Sample input:
5 100 90 80
98
40
30
21
80


Sample output:
23

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, A: int, B: int, C: int, l: "List[int]"):
    mn = 1e9
    for i in range(1 << N):
        for j in range(1 << N):
            n = []
            a = []
            b = []
            c = []
            for k in range(N):
                if (i >> k) % 2 == 0 and (j >> k) % 2 == 0:
                    n.append(k)
                if (i >> k) % 2 == 0 and (j >> k) % 2 == 1:
                    a.append(k)
                if (i >> k) % 2 == 1 and (j >> k) % 2 == 0:
                    b.append(k)
                if (i >> k) % 2 == 1 and (j >> k) % 2 == 1:
                    c.append(k)
            if len(a) == 0 or len(b) == 0 or len(c) == 0:
                continue
            else:
                m = 10 * (len(a) + len(b) + len(c) - 3) + abs(A - sum([l[aa] for aa in a])) + abs(B - sum([l[bb] for bb in b])) + abs(C - sum([l[cc] for cc in c]))
                if mn > m:
                    mn = m
    print(mn)
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    l = [ int(next(tokens)) for _ in range(N) ]  # type: "List[int]"
    solve(N, A, B, C, l)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n,a,b,c=map(int,input().split())
x=list(int(input()) for _ in range(n))

import itertools
import numpy as np

f=[0,1,2,3]

pt=list(itertools.product(f, repeat=n))

mpl=[]

for i in range(len(pt)):
	if (1 in pt[i]) and (2 in pt[i]) and (3 in pt[i]):
		rl1=0;rc1=0
		rl2=0;rc2=0
		rl3=0;rc3=0
		mp=0
		for j in range(n):
			if pt[i][j]==1:
				rl1+=x[j]
				rc1+=1
			if pt[i][j]==2:
				rl2+=x[j]
				rc2+=1
			if pt[i][j]==3:
				rl3+=x[j]
				rc3+=1
		mp=abs(rl1-a)+abs(rl2-b)+abs(rl3-c)
		if rc1>1:
			mp+=(rc1-1)*10
		if rc2>1:
			mp+=(rc2-1)*10
		if rc3>1:
			mp+=(rc3-1)*10
		mpl.append(mp)

print(min(mpl))

Submission status: Accepted

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


def solve(X):
    if not ("1" in X and "2" in X and "3" in X):
        return 1e10

    MS = [[L[i] for i in range(N) if X[i] == j] for j in "123"]
    ret = 1e10
    A_ans = []
    B_ans = []
    C_ans = []
    for i in range(3):
        A_ans.append(solve2(MS[i], A))
        B_ans.append(solve2(MS[i], B))
        C_ans.append(solve2(MS[i], C))
    ret = min(ret, A_ans[0] + B_ans[1] + C_ans[2])
    ret = min(ret, A_ans[0] + B_ans[2] + C_ans[1])
    ret = min(ret, A_ans[1] + B_ans[0] + C_ans[2])
    ret = min(ret, A_ans[1] + B_ans[2] + C_ans[0])
    ret = min(ret, A_ans[2] + B_ans[0] + C_ans[1])
    ret = min(ret, A_ans[2] + B_ans[1] + C_ans[0])
    return ret


def solve2(M, target):
    def rec(Y, target):
        # Y: [1, 0, 0]
        if len(Y) == len(M):
            if len(set(Y)) == 1 and Y[0] == 0:
                return 1e10
            sum_M = sum([M[i] for i in range(len(M)) if Y[i] == 1])
            return abs(target - sum_M) + 10 * (Y.count(1) - 1)
        return min(rec(Y + [0], target), rec(Y + [1], target))
    ret = rec([], target)
    return ret


ans = 1e10


def rec(X):
    global ans
    if len(X) == N:
        ans = min(ans, solve(X))
        return
    rec(X + "1")
    rec(X + "2")
    rec(X + "3")


rec("")

print(ans)

Submission status: Accepted

Solution code:
def main():
    import itertools as it
    N,A,B,C = map(int,input().split())
    pre = [int(input()) for _ in range(N)]
    ss = max(pre)*N <= min(A,B,C)
    if N == 3:print(A-pre[0]+B-pre[1]+C-pre[2])
    else:
        m = [0,1,2,3,4,5,6,7]
        cpm = it.permutations(pre,N)
        ccb = list(it.combinations(m[:N], 3))
        minc = 99999999999999999
        for l in cpm:
            for d in ccb:
                cmp = (d[2] - 2) * 10
                if ss:
                    asum = (cmp+A+B+C-sum(l[:d[2]+1]))
                    minc = min(minc,asum)
                else:
                    asum = abs(A - sum(l[:d[0]+1]))
                    if cmp+asum >= minc: continue
                    bsum = abs(B - sum(l[d[0]+1:d[1]+1]))
                    if cmp+asum+bsum >= minc: continue
                    csum = abs(C - sum(l[d[1]+1:d[2]+1]))
                    tc = cmp+asum+bsum+csum
                    minc = min(minc,tc)
        print(minc)
main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# ABC 119 C

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 # A の材料にする
    ret2 = dfs(cur + 1, a, b + l[cur], c) + 10 # B の材料にする
    ret3 = dfs(cur + 1, a, b, c + l[cur]) + 10 # C の材料にする
    return min(ret0, ret1, ret2, ret3)

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

Submission status: Accepted

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

def bamboo_connect(i, a, b, c):
    if i == N:
        if all((a, b, c)):
            return abs(a-A) + abs(b-B) + abs(c-C) - 30
        else:
            return inf
    no_connect = bamboo_connect(i+1, a, b, c)
    choice_a = bamboo_connect(i+1, a+l[i], b, c) + 10
    choice_b = bamboo_connect(i+1, a, b+l[i], c) + 10
    choice_c = bamboo_connect(i+1, a, b, c+l[i]) + 10
    return min(no_connect, choice_a, choice_b, choice_c)

print(bamboo_connect(0, 0, 0, 0))

Submission status: Accepted

Solution code:
# 各たけを、A,B,C,使わないの4パターンに振り分ける
# LA = [l2,l4,l7]みたいになったら、あとは
# コストは（合成＋調整で）(len(LA)-1)*10 + abs(sum(LA)-A)
# A = 90, L! = [40,30,21] -> 20 + 1
import copy as cp
inf = 10**9
def cost(li, length):
    if len(li)==0:
        return inf
    return (len(li)-1)*10 + abs(sum(li)-length)

def search_cost(ln,assignment,length):
#     from IPython.core.debugger import Pdb; Pdb().set_trace()
    if len(ln)==0:
        costA = cost(assignment["A"], length[0])
        costB = cost(assignment["B"], length[1])
        costC = cost(assignment["C"], length[2])
        return costA + costB + costC
    val = ln[-1]
    candidate = []
    for take in assignment.keys():
        nextdic = cp.deepcopy(assignment)
        nextdic[take].append(val)
        cand = search_cost(ln[:-1],nextdic,length)
        candidate.append(cand)
    return min(candidate)
  
  
# 実行
N, A, B, C =map(int,input().split())
length = [A,B,C]
ln = []
assignment = {"A":[],"B":[],"C":[],"D":[]}

for i in range(N):
    a = int(input())
    ln.append(a)
   
print(search_cost(ln,assignment,length))

Submission status: Accepted

Solution code:
minMP = 100000


def make_patterns(nowstr, count0, count1, count2, count3, rest):
    if count0 > N - 2:
        return
    if count1 > N - 2:
        return
    if count2 > N - 2:
        return
    if count3 > N - 3:
        return
    if rest == 0:
        if 0 == count0:
            return
        if 0 == count1:
            return
        if 0 == count2:
            return
        do_calc(list(nowstr), count0, count1, count2)
        return
    make_patterns(nowstr+"0", count0+1, count1, count2, count3, rest-1)
    make_patterns(nowstr+"1", count0, count1+1, count2, count3, rest-1)
    make_patterns(nowstr+"2", count0, count1, count2+1, count3, rest-1)
    make_patterns(nowstr+"3", count0, count1, count2, count3+1, rest-1)
    return


def do_calc(pattern_list, c0, c1, c2):
    global minMP
    # print(pattern_list)
    tempA = 0
    tempB = 0
    tempC = 0
    tempcost = (c0+c1+c2-3)*10
    for i in range(N):
        num = int(pattern_list[i])
        if num == 0:
            tempA += L_list[i]
        if num == 1:
            tempB += L_list[i]
        if num == 2:
            tempC += L_list[i]
    tempcost += abs(A - tempA) + abs(B - tempB) + abs(C - tempC)

    if tempcost < minMP:
        minMP = tempcost


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

L_list = [int(input()) for i in range(N)]

# print(L_list)
make_patterns("", 0, 0, 0, 0, N)

print(minMP)

Submission status: Accepted

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

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

inf = 10 ** 10

def mp(i,a,b,c):
  if i == N:
    return abs(A-a)+abs(B-b)+abs(C-c)-30 if min(a,b,c)>0 else inf
  mp0 = mp(i+1,a,b,c)
  mp1 = mp(i+1,a+l[i],b,c)+10
  mp2 = mp(i+1,a,b+l[i],c)+10
  mp3 = mp(i+1,a,b,c+l[i])+10
  return min(mp0,mp1,mp2,mp3)

print(mp(0,0,0,0))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N,A,B,C=map(int,input().split())
l=[int(input()) for i in range(N)]
odr=[4**i for i in range(N)][::-1]
minL=1145141919
for i in range(4**N):
    a=0
    b=0
    c=0
    count=0
    mod=i
    for j in range(N):
        idx,mod=divmod(mod,odr[j])
        if idx==1:
            a+=l[j]
            count+=10
        elif idx==2:
            b+=l[j]
            count+=10
        elif idx==3:
            c+=l[j]
            count+=10
    sumL = abs(a-A)+abs(b-B)+abs(c-C)+count-30
    minL = sumL if sumL<minL and min(a,b,c)>0 else minL
print(minL)

Submission status: Accepted

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

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

Submission status: Accepted

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

assign = [0]*N

cost_min = 10000

while assign.count(3)<N:
    NL = [0]*4
    XL = [0]*4
    for i in range(N):
        NL[assign[i]] += 1
        XL[assign[i]] += L[i]

    if min(NL[:3])>=1:
        cost = (sum(NL[:3])-3)*10 + abs(A-XL[0]) + abs(B-XL[1]) + abs(C-XL[2])
        cost_min = min(cost_min, cost)

    for i in range(N):
        if assign[i]<3:
            assign[i] += 1
            for j in range(i):
                assign[j] = 0
            break

print(cost_min)

Submission status: Accepted

Solution code:
from collections import deque

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

stack = deque()
init_data = (0, [])
stack.append(init_data)

mp_results = []


def dfs():
    depth, curr_path = stack.pop()
    if depth == N:
        filter_a = 'A' not in curr_path
        filter_b = 'B' not in curr_path
        filter_c = 'C' not in curr_path
        if filter_a or filter_b or filter_c:
            return
        a_combi = []
        b_combi = []
        c_combi = []
        for idx, history in enumerate(curr_path):
            if history == 'A':
                a_combi.append(lll[idx])
            elif history == 'B':
                b_combi.append(lll[idx])
            elif history == 'C':
                c_combi.append(lll[idx])
        n_concat = len(a_combi)-1 + len(b_combi)-1 + len(c_combi)-1
        mp_used_for_concat = n_concat * 10
        mp_used_for_ext_shr = \
            abs(A-sum(a_combi)) + abs(B-sum(b_combi)) + abs(C-sum(c_combi))

        mp_results.append(mp_used_for_concat + mp_used_for_ext_shr)
    else:
        depth += 1
        stack.append((depth, curr_path + ['A']))
        stack.append((depth, curr_path + ['B']))
        stack.append((depth, curr_path + ['C']))
        stack.append((depth, curr_path + ['O']))


while stack:
    dfs()

print(min(mp_results))

Submission status: Accepted

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


def rec(i, x, y, z):
    if i >= n:
        return abs(a - x) + abs(b - y) + abs(c - z) if x * y * z > 0 else INF

    return min(rec(i + 1, x, y, z),
               rec(i + 1, x + l[i], y, z) + (10 if x > 0 else 0),
               rec(i + 1, x, y + l[i], z) + (10 if y > 0 else 0),
               rec(i + 1, x, y, z + l[i]) + (10 if z > 0 else 0))


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

Submission status: Accepted

Solution code:
from itertools import *

N,a,b,c = map(int,input().split())
L = [int(input()) for i in range(N)]

ans = float("inf")

products = product(range(4), repeat=N)

for prod in products :
    A = []
    B = []
    C = []
    
    for i,v in enumerate(prod) :
        if v == 1 :
            A.append(L[i])
        elif v == 2 :
            B.append(L[i])
        elif v == 3 :
            C.append(L[i])
    
    if len(A) * len(B) * len(C) == 0 :
        continue
    
    cost = 0
    
    for li in [A, B, C] :
        cost += (len(li)-1) * 10
    
    cost += abs(a-sum(A))
    cost += abs(b-sum(B))
    cost += abs(c-sum(C))
    
    ans = min(ans, cost)

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from itertools import product

N,a,b,c = map(int,input().split())

L = list(int(input()) for i in range(N))

products = product(list(range(4)), repeat=N)

ans = float("inf")

for prod in products :
    A = []
    B = []
    C = []
    
    for i in range(len(prod)) :
        if prod[i] == 1 :
            A.append(L[i])
        elif prod[i] == 2 :
            B.append(L[i])
        elif prod[i] == 3 :
            C.append(L[i])
    if len(A) * len(B) * len(C) == 0 :
        continue
    
    cost = 0
    
    for li in [A, B, C] :
        cost += (len(li)-1) * 10
    
    cost += abs(a - sum(A))
    cost += abs(b - sum(B))
    cost += abs(c - sum(C))
    
    ans = min(ans, cost)

print(ans)

Submission status: Accepted

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


def dfs(a, b, c, n):

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

    ret1 = dfs(a, b, c, n + 1)
    ret2 = dfs(a + take_list[n], b, c, n + 1) + 10
    ret3 = dfs(a, b + take_list[n], c, n + 1) + 10
    ret4 = dfs(a, b, c + take_list[n], n + 1) + 10
    return min(ret1, ret2, ret3, ret4)

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

Submission status: Accepted

Solution code:
import itertools
n,a,b,c=map(int,input().split())
l = [int(input()) for i in range(n)]
zairyo = ('A','B','C','N')
zairyo_list=[0]*(4**n)
j=0
for i in itertools.product(zairyo, repeat=len(l)):
  zairyo_list[j]=i
  j+=1
mplist=[]
for zl in zairyo_list:
  if 'A' in zl and 'B' in zl and 'C' in zl:
    mp=0
    alist = [l[i] for i, e in enumerate(zl) if e == 'A']
    blist = [l[i] for i, e in enumerate(zl) if e == 'B']
    clist = [l[i] for i, e in enumerate(zl) if e == 'C']
    mp+=(len(alist)+len(blist)+len(clist)-3)*10
    akoho=sum(alist)
    bkoho=sum(blist)
    ckoho=sum(clist)
    mp+=abs(akoho-a)+abs(bkoho-b)+abs(ckoho-c)
    mplist.append(mp)
print(min(mplist))

Submission status: Accepted

Solution code:
N, A, B, C = map(int, input().split())
l = [int(input()) for i in range(N)]
def rec(i, a, b, c, d):
    if i == N:
        if a == 0 or b == 0 or c == 0:
            return float('inf')
        return abs(a-A)+abs(b-B)+abs(c-C)+d
    return min(rec(i+1,a+l[i],b,c,d+10),rec(i+1,a,b+l[i],c,d+10),rec(i+1,a,b,c+l[i],d+10),rec(i+1,a,b,c,d))
print(rec(0,0,0,0,-30))

Submission status: Accepted

Solution code:
n, a, b, c = map(int, input().split())
l = [int(input()) for _ in range(n)]
INF = 10**9

def dfs(index, x, y, z):
    if index == n:
        return abs(a-x) + abs(b-y) + abs(c-z) - 30 if min(x, y, z) > 0 else INF

    cand1 = dfs(index+1, x+l[index], y, z) + 10
    cand2 = dfs(index+1, x, y+l[index], z) + 10
    cand3 = dfs(index+1, x, y, z+l[index]) + 10
    cand4 = dfs(index+1, x, y, z)

    return min(cand1, cand2, cand3, cand4)

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

Submission status: Accepted

Solution code:
import sys
import math
from collections import deque

sys.setrecursionlimit(4100000)


def inputs(num_of_input):
    ins = [input() for i in range(num_of_input)]
    return ins


def solve(N, A, B, C, inputs):
    bamboos = [int(i) for i in inputs]

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

        t = bamboos[cursor]
        results = []
        results.append(cost(cursor+1, a, b, c))
        results.append(cost(cursor+1, a + t, b, c) + 10)
        results.append(cost(cursor+1, a, b + t, c) + 10)
        results.append(cost(cursor+1, a, b, c + t) + 10)

        return min(results)

    return cost(0, 0, 0, 0)


def string_to_int(string):
    return list(map(lambda x: int(x), string.split()))


if __name__ == "__main__":
    [N, A, B, C] = string_to_int(input())
    ret = solve(N, A, B, C, inputs(N))
    print(ret)

Submission status: Accepted

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

def dfs(cur,x,y,z):
  if cur==n and min(x,y,z)>0:
    return abs(a-x)+abs(b-y)+abs(c-z)-30
  elif cur==n:
    return 100000000000000000000
  ret0=dfs(cur+1,x,y,z)
  ret1=dfs(cur+1,x+l[cur],y,z)+10
  ret2=dfs(cur+1,x,y+l[cur],z)+10
  ret3=dfs(cur+1,x,y,z+l[cur])+10
  return min(ret0,ret1,ret2,ret3)

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

Submission status: Accepted

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

ans = 0
initial_ans = True
for i in range(4**N):
    uses = [0] * (4)
    use_count = 0
    before_div = i
    for j in range(N):
        uses[before_div%4] += L[j]
        if before_div%4 != 0:
            use_count += 1
        before_div = before_div//4
    if uses[1] == 0 or uses[2] == 0 or uses[3] == 0:
        continue
    else:
        sum_mp = abs(A-uses[1]) + abs(B-uses[2]) + abs(C-uses[3]) + 10 * (use_count-3)
        if initial_ans:
            ans = sum_mp
            initial_ans = False
        else:
            ans = min(ans, sum_mp)
print(ans)

Submission status: Accepted

Solution code:
inf = float('inf')


def calc(mask):
    t = [0] * 3
    cnt = 0
    for j in range(n):
        idx = (mask >> (2 * j)) & 3
        if idx == 3:
            cnt += 1
            continue
        t[idx] += l[j]

    if 0 in t:
        return inf

    return sum(abs(tt - gg) for tt, gg in zip(t, goal)) + (n - cnt - 3) * 10


def dfs(cur, mask):
    # l[cur]をa,b,c,未使用のいずれかにあてがう

    # base case
    if cur == n:
        return calc(mask)

    res = inf
    for i in range(4):
        # i == 0,1,2 : a,b,cにあてがう / i == 3 : 未使用
        res = min(res, dfs(cur + 1, mask | i << (2 * cur)))
    return res


n, *goal = map(int, input().split())
l = [int(input()) for _ in range(n)]

print(dfs(0, 0))

Submission status: Accepted

Solution code:
inf = float('inf')


def calc(mask):
    cost = -30
    t = [0] * 3
    for j in range(n):
        idx = (mask >> (2 * j)) & 3
        if idx == 3: continue
        t[idx] += l[j]
        cost += 10

    if 0 in t[:3]:
        return inf

    cost += sum(abs(tt - gg) for tt, gg in zip(t, goal))
    return cost


def dfs(cur, mask):
    # l[cur]をa,b,c,未使用のいずれかにあてがう

    # base case
    if cur == n:
        return calc(mask)

    res = inf
    for i in range(4):
        # i == 0,1,2 : a,b,cにあてがう / i == 3 : 未使用
        res = min(res, dfs(cur + 1, mask | i << (2 * cur)))
    return res


n, *goal = map(int, input().split())
l = [int(input()) for _ in range(n)]

print(dfs(0, 0))

Submission status: Accepted

Solution code:
inf = float('inf')

n, *goal = map(int, input().split())
l = [int(input()) for _ in range(n)]

ans = inf
for q in range(4 ** n):
    cost = -30
    t = [0] * 3
    for j in range(n):
        idx = (q // (4 ** j)) % 4
        if idx == 3: continue
        t[idx] += l[j]
        cost += 10

    if any(tt == 0 for tt in t):
        continue

    for idx in range(3):
        cost += abs(t[idx] - goal[idx])

    ans = min(ans, cost)

print(ans)

Submission status: Accepted

Solution code:
inf = float('inf')

n, *goal = map(int, input().split())
l = [int(input()) for _ in range(n)]

ans = inf
for q in range(4 ** n):
    m = [[] for _ in range(4)]
    lm = 0
    for j in range(n):
        idx = (q // (4 ** j)) % 4
        m[idx].append(l[j])
    if any(len(m[idx]) == 0 for idx in range(3)):
        continue

    cost = 0
    for idx in range(3):
        merge_time = len(m[idx]) - 1
        cost += merge_time * 10
        cost += abs(sum(m[idx]) - goal[idx])

    ans = min(ans, cost)

print(ans)

Submission status: Accepted

Solution code:
def smaller(x, y):
	if x < y:
		return x
	return y

N, A, B, C = map(int, input().split())
L = []
for i in range(0, N):
	L.append(int(input()))
min = 5000000000000000
for i in range(0, 4**N):
	m = i
	groups = [[], [], []]
	for j in range(0, N):
		if m % 4 != 3:
			groups[m%4].append(j)
		m //= 4
	if [] not in groups:
		mp = 10 * (len(groups[0])+len(groups[1])+len(groups[2])-3)
		sum1 = 0
		sum2 = 0
		sum3 = 0
		for j in range(0, len(groups[0])):
			sum1 += L[groups[0][j]]
		for j in range(0, len(groups[1])):
			sum2 += L[groups[1][j]]
		for j in range(0, len(groups[2])):
			sum3 += L[groups[2][j]]
		mp += abs(A-sum1)+abs(B-sum2)+abs(C-sum3)
		min = smaller(min, mp)
print(min)

Submission status: Accepted

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

def rec(i,a,b,c):
    if i == N:
        if min(a,b,c) > 0:
            return abs(a-A) + abs(b-B) + abs(c-C) - 30
        else:
            return 10**10
    # 今の竹を使わない場合
    ret0 = rec(i+1,a,b,c)
    # 今の竹をAの竹に使う
    ret1 = rec(i+1,a+L[i],b,c) + 10
    # 今の竹をBの竹に使う
    ret2 = rec(i+1,a,b+L[i],c) + 10
    #　今の竹をCの竹に使う
    ret3 = rec(i+1,a,b,c+L[i]) + 10
    return min(ret0,ret1,ret2,ret3)

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