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:
def p_c():
    n, A, B, C = map(int, input().split())
    li = [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
        ret1 = dfs(cur + 1, a, b, c)
        ret2 = dfs(cur + 1, a + li[cur], b, c) + 10
        ret3 = dfs(cur + 1, a, b + li[cur], c) + 10
        ret4 = dfs(cur + 1, a, b, c + li[cur]) + 10
        return min(ret1, ret2, ret3, ret4)

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

Submission status: Accepted

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

bit = 1<<n
ans = 10**10

def chs(L,x):
    L2 = []
    for i in range(len(L)):
        if not 1&(x>>i):###not
            L2.append(L[i])
    return L2

def calc(L,x,ai):
    res = 0
    la = 0
    for i in range(len(L)):
        if 1&(x>>i):
            la+=L[i]
            res += 10
    if x:
        res -= 10
    res += abs(la-ai)
    return res

for ind in range(1,bit):##1から
    cost = 0
    cost += calc(l,ind,a)
    l2 = chs(l,ind)

    bit2 = 1<<len(l2)
    

    for ind2 in range(1,bit2):
        cost2 = cost
        cost2 += calc(l2,ind2,b)
        l3 = chs(l2,ind2)
        
        bit3 = 1<<len(l3)
       
        
        for ind3 in range(1,bit3):
            cost3 = cost2
            cost3 += calc(l3,ind3,c)
            if ans>cost3:
                #print(l2,l3,ind3)
                ans = cost3

print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
N,A,B,C=map(int,input().split())

def zet(l,m,n):
    return abs(A-l)+abs(B-m)+abs(C-n)

def saiki(x,y,z,n,count,ans):
    if n==N:
        if x==0 or y==0 or z==0:
            return 10**18
        else:
            return min(zet(x,y,z),zet(x,z,y),zet(y,x,z),zet(y,z,x),zet(z,x,y),zet(z,y,x))+count*10
    else:
        ans=min(saiki(x+l[n],y,z,n+1,count+1 if x!=0 else count,ans),ans)
        ans=min(saiki(x,y+l[n],z,n+1,count+1 if y!=0 else count,ans),ans)
        ans=min(saiki(x,y,z+l[n],n+1,count+1 if z!=0 else count,ans),ans)
        ans=min(saiki(x,y,z,n+1,count,ans),ans)
    return ans

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

print(saiki(0,0,0,0,0,10**18))

Submission status: Accepted

Solution code:
import numpy as np
N, A, B, C = (int(i) for i in input().split())  
l = [int(input()) for i in range(N)] 

def dfs(cur, a, b, c):
  if cur == N:
    return abs(a-A) + abs(b-B) + abs(c-C) - 30 if min(a, b, c) > 0 else np.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:
def examC():
    N, A, B, C = LI()
    L = [I() for _ in range(N)]
    loop = 4**N; ans = 10**9
    for i in range(loop):
        cur = 0
        curA = 0; curB = 0; curC = 0
        for j in range(N):
            judge = (i//(4**j))%4
            if judge==1:
                if curA>0:
                    cur +=10
                curA += L[j]
            elif judge==2:
                if curB>0:
                    cur +=10
                curB += L[j]
            elif judge==3:
                if curC>0:
                    cur +=10
                curC += L[j]
        if curA==0 or curB==0 or curC==0:
            continue
        cur += abs(curA-A)
        cur += abs(curB-B)
        cur += abs(curC-C)
        ans = min(cur,ans)
    print(ans)

import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
mod = 10**9 + 7
inf = float('inf')

if __name__ == '__main__':
    examC()

Submission status: Accepted

Solution code:

from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations
import sys
import bisect
import string
import math
import time
from fractions import gcd
#import random


def I(): return int(input())


def MI(): return map(int, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


YN = ['Yes', 'No']
MOD = 10**9+7
inf = float('inf')
IINF = 10**19
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)


show_flg = False
# show_flg = True

A = 0
B = 0
C = 0
N = 0


def dfs(cur, L, a, b, c):
    # print(A, B, C)
    if cur == N:
        return abs(A - a) + abs(B - b) + abs(C - c) if min(a, b, c) > 0 else IINF

    ret0 = dfs(cur + 1, L, a, b, c)
    ret1 = dfs(cur + 1, L, a + L[cur], b, c) + (0 if a == 0 else 10)
    ret2 = dfs(cur + 1, L, a, b + L[cur], c) + (0 if b == 0 else 10)
    ret3 = dfs(cur + 1, L, a, b, c + L[cur]) + (0 if c == 0 else 10)

    return min(ret0, ret1, ret2, ret3)


def main():
    global A
    global B
    global C
    global N
    N, A, B, C = MI()
    L = [0] * N

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

    # itertools.combinations(L, 2)
    print(dfs(0, L, 0, 0, 0))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools

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

a_list = list(itertools.product(class_list, repeat=N))
# print(a_list)

A_sum = 0
B_sum = 0
C_sum = 0
A_count = 0
B_count = 0
C_count = 0

min_score = 10**9
for a in a_list:
    for idx, b in enumerate(a):
        # print(b)
        if b == "A":
            A_sum += L[idx]
            A_count += 1
        elif b == "B":
            B_sum += L[idx]
            B_count += 1
        elif b == "C":
            C_sum += L[idx]
            C_count += 1
    if A_count > 0 and B_count > 0 and C_count > 0:
        score = (A_count-1+B_count-1+C_count-1) * 10 + abs(A-A_sum) + abs(B-B_sum) + abs(C-C_sum)
        # print(A_sum, B_sum, C_sum, score)
        min_score = min(min_score, score)
    A_sum = 0
    B_sum = 0
    C_sum = 0
    A_count = 0
    B_count = 0
    C_count = 0

print(min_score)

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 _ in range(n)]

def doit(index, fora, forb, forc):
    if index == len(l):
        if min(fora, forb, forc) > 0:
            return abs(fora - a) + abs(forb - b) + abs(forc - c)
        else:
            return 10000
    return min(doit(index + 1, fora, forb, forc),
               doit(index + 1, fora + l[index], forb, forc) + 10,
               doit(index + 1, fora, forb + l[index], forc) + 10,
               doit(index + 1, fora, forb, forc + l[index]) + 10)

print(doit(0, 0, 0, 0) - 30)

Submission status: Accepted

Solution code:
import itertools

N,A,B,C=map(int,input().split())
l=[int(input()) for i in range(N)]
PRD=list(itertools.product([0,1,2,3], repeat=N))

P=10**5
for i in range(len(PRD)):
    a,b,c=0,0,0
    for j in range(N):
        if PRD[i][j]==1:
            a+=l[j]
        elif PRD[i][j]==2:
            b+=l[j]
        elif PRD[i][j]==3:
            c+=l[j]
    if 0 in [a,b,c]:
        continue
    L=PRD[i]
    Q=abs(A-a)+abs(B-b)+abs(C-c)+(L.count(1)+L.count(2)+L.count(3)-3)*10
    if P>=Q:
        P=Q

print(P)

Submission status: Accepted

Solution code:
def dt(a):
    for x in range(1,9):
        if 4**x > a:
            y = x-1
            break
    n = ''
    for i in range(y+1):
        t = a // 4 ** (y-i)
        n += str(t)
        a -= t * 4 ** (y-i)
    return n

def MP(a,b):
    return (len(a)-1)*10 + abs(sum(a)-b)

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

for i in range(4**N):
    jj = dt(i)
    j = jj.zfill(N)
    for (k,x) in enumerate(j):
        if x == '0':
            continue
        elif x == '1':
            ls[0].append(H[k])
        elif x == '2':
            ls[1].append(H[k])
        elif x == '3':
            ls[2].append(H[k])
    else:
        if ls[0] and ls[1] and ls[2]:
            ans = min(ans, MP(ls[0],A)+MP(ls[1],B)+MP(ls[2],C))
        ls = [[],[],[]]

print(ans)

Submission status: Accepted

Solution code:
from itertools import permutations
from sys import setrecursionlimit
setrecursionlimit(1000000)

def doit(a, b, c, idx):
    if (a, b, c, idx) in memo:
        return memo[a, b, c, idx]
    if idx == len(unused):
        return abs(a - needA) + abs(b - needB) + abs(c - needC)
    memo[a, b, c, idx] = min(
        doit(a, b, c, idx + 1),
        doit(a + unused[idx], b, c, idx + 1) + 10,
        doit(a, b + unused[idx], c, idx + 1) + 10,
        doit(a, b, c + unused[idx], idx + 1) + 10
    )
    return memo[a, b, c, idx]

n, needA, needB, needC = map(int, input().split())
a = [int(input()) for _ in range(n)]
ret = float('inf')
for mask in range(1 << n):
    if bin(mask).count('1') != 3:
        continue
    abc = [a[i] for i in range(n) if (mask >> i) & 1]
    unused = [a[i] for i in range(n) if not (mask >> i) & 1]
    for p in permutations(abc):
        memo = {}
        ret = min(ret, doit(p[0], p[1], p[2], 0))
print(ret)

Submission status: Accepted

Solution code:
from sys import setrecursionlimit
setrecursionlimit(1000000)

def permute(a, idx):
    if idx == len(a):
        permutations.append(a[::])
    for i in range(idx, len(a)):
        a[i], a[idx] = a[idx], a[i]
        permute(a, idx + 1)
        a[i], a[idx] = a[idx], a[i]

def doit(a, b, c, idx):
    if (a, b, c, idx) in memo:
        return memo[a, b, c, idx]
    if idx == len(unused):
        return abs(a - needA) + abs(b - needB) + abs(c - needC)
    memo[a, b, c, idx] = min(
        doit(a, b, c, idx + 1),
        doit(a + unused[idx], b, c, idx + 1) + 10,
        doit(a, b + unused[idx], c, idx + 1) + 10,
        doit(a, b, c + unused[idx], idx + 1) + 10
    )
    return memo[a, b, c, idx]

n, needA, needB, needC = map(int, input().split())
a = [int(input()) for _ in range(n)]
ret = float('inf')
for mask in range(1 << n):
    if bin(mask).count('1') != 3:
        continue
    abc = [a[i] for i in range(n) if (mask >> i) & 1]
    unused = [a[i] for i in range(n) if not (mask >> i) & 1]
    permutations = []
    permute(abc, 0)
    for p in permutations:
        memo = {}
        ret = min(ret, doit(p[0], p[1], p[2], 0))
print(ret)

Submission status: Accepted

Solution code:
import sys
import math
n, a, b, c = [int(i) for i in sys.stdin.readline().split()]
l_ls = []
INF = 10 ** 18
def get_4_sinsu(x):
    if x == 0:
        return "0"
    res = ""
    for i in range(math.floor(math.log(x, 4)), -1, -1):
        res += str(x // (4 ** i))
        x %= 4 ** i
    return res

for i in range(n):
    l = int(input())
    l_ls.append(l)
best = INF
for i in range(4 ** n):
    dic = {0 : [], 1 : [], 2 : []}
    _i = get_4_sinsu(i).zfill(n)
    cost = 0
    for k, j in enumerate(_i):
        if j == "3":
            continue
        if j == "0":
            dic[0].append(l_ls[k])
        elif j == "1":
            dic[1].append(l_ls[k])
        else:
            dic[2].append(l_ls[k])
    if any([len(j) == 0 for j in dic.values()]):
        continue
    res = abs(sum(dic[0]) - a) + abs(sum(dic[1]) - b) + abs(sum(dic[2]) - c) + max(0, len(dic[0]) - 1) * 10 + \
                                                                                max(0, len(dic[1]) - 1) * 10 + \
                                                                                 max(0, len(dic[2]) - 1) * 10
    best = min(best, res)
print(best)

Submission status: Accepted

Solution code:
INF = 1e+9
import sys
sys.setrecursionlimit(int(INF))

N, A, B, C = map(int, input().split())
l = list()
for n in range(N):
  l.append(int(input()))
  
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
    branch1 = dfs(depth+1, a+l[depth], b, c) + 10
    branch2 = dfs(depth+1, a, b+l[depth], c) + 10
    branch3 = dfs(depth+1, a, b, c+l[depth]) + 10
    branch4 = dfs(depth+1, a, b, c)
    return min(branch1, branch2, branch3, branch4)
print(dfs(0,0,0,0))

Submission status: Accepted

Solution code:
def MAP(): return list(map(int,input().split()))

n,A,B,C = MAP()
l = [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
    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:
import sys
input = sys.stdin.readline

N,A,B,C = [int(x) for x in input().split()]
ln = tuple([int(input()) for _ in range(N)])

def dp(A, B, C, a, b, c, n):
    global ln
    if n == N:
        if len(a) == 0 or len(b) == 0 or len(c) == 0:
            return float('INF')
        cost = (len(a) + len(b) + len(c) - 3) * 10
        return cost + abs(A - sum(a)) + abs(B - sum(b)) + abs(C - sum(c))
    ans = float('INF')
    ans = min(ans, dp(A, B, C, a[:], b[:], c[:], n+1))
    ans = min(ans, dp(A, B, C, a[:]+[ln[n]], b[:], c[:], n+1))
    ans = min(ans, dp(A, B, C, a[:], b[:]+[ln[n]], c[:], n+1))
    ans = min(ans, dp(A, B, C, a[:], b[:], c[:]+[ln[n]], n+1))
    return ans
print(dp(A, B, C, [], [], [], 0))

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
import sys
import bisect
import math
import itertools
import string
import queue
import copy
# import numpy as np
# import scipy
from itertools import permutations, combinations
from heapq import heappop, heappush
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7

def inp(): # n=1
    return int(input())
def inpm(): # x=1,y=2
    return map(int,input().split())
def inpl(): # a=[1,2,3,4,5,...,n]
    return list(map(int, input().split()))
def inpls(): # a=['1','2','3',...,'n']
    return list(input().split())
def inplm(n): # x=[] 複数行
    return list(int(input()) for _ in range(n))
def inpll(n): # [[1,1,1,1],[2,2,2,2],[3,3,3,3]]
    return sorted([list(map(int, input().split())) for _ in range(n)])

    
def main():
    ans=10**10
    n,a,b,c=inpm()
    l=inplm(n)
    for an in range(1,n-1):
        for use_a in combinations(range(n),an):
            tank = []
            for j in range(n):
                if j not in use_a:
                    tank.append(j)
            for bn in range(1,n-an):
                for use_b in combinations(tank,bn):
                    tank1=[]
                    for j in tank:
                        if j not in use_b:
                            tank1.append(j)
                    for cn in range(1,n-an-bn+1):
                        for use_c in combinations(tank1,cn):
                            a_pre=0
                            b_pre=0
                            c_pre=0
                            for i in use_a:
                                a_pre+=l[i]
                            for i in use_b:
                                b_pre+=l[i]
                            for i in use_c:
                                c_pre+=l[i]
                            cnt=0
                            cnt+= (len(use_a)+len(use_b)+len(use_c)-3)*10 + abs(a_pre-a)+abs(c_pre-c)+abs(b_pre-b)
                            if ans>cnt:
                                ans=cnt
                            
    print(ans) 

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from itertools import product
N,A,B,C = map(int,input().split())
L = [int(input()) for _ in range(N)]
cntmin = abs(A-L[0])+abs(B-L[1])+abs(C-L[2])
for x in product(range(4),repeat=N):
    cnt = 0
    a = x.count(1)
    b = x.count(2)
    c = x.count(3)
    if a*b*c==0:continue
    A1 = []
    B1 = []
    C1 = []
    for i in range(N):
        if x[i]==1:
            A1.append(L[i])
        elif x[i]==2:
            B1.append(L[i])
        elif x[i]==3:
            C1.append(L[i])
    cntA = 10*(len(A1)-1)
    La = 0
    for l in A1:
        La += l
    cntA += abs(A-La)
    cntB = 10*(len(B1)-1)
    Lb = 0
    for l in B1:
        Lb += l
    cntB += abs(B-Lb)
    cntC = 10*(len(C1)-1)
    Lc = 0
    for l in C1:
        Lc += l
    cntC += abs(C-Lc)
    cntmin = min(cntmin,cntA+cntB+cntC)
        
print(cntmin)

Submission status: Accepted

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

def f(x,y,z,arr,cnt):
    global a
    global b
    global c
    global ans
    if arr:
        f(x + arr[0], y, z, arr[1:],cnt+1)
        f(x, y + arr[0], z, arr[1:],cnt+1)
        f(x, y, z + arr[0], arr[1:],cnt+1)
        f(x, y, z, arr[1:],cnt)
    else:
        if x > 0 and y > 0 and z > 0:
            ans.append(abs(a-x) + abs(b-y) + abs(c-z) + 10 * (cnt - 3))
f(0,0,0,l,0)
print(min(ans))

Submission status: Accepted

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

def f(x,y,z,arr,ca,cb,cc):
    global a
    global b
    global c
    global ans
    if arr:
        f(x + arr[0], y, z, arr[1:],ca+1,cb,cc)
        f(x, y + arr[0], z, arr[1:],ca,cb+1,cc)
        f(x, y, z + arr[0], arr[1:],ca,cb,cc+1)
        f(x, y, z, arr[1:],ca,cb,cc)
    else:
        if x > 0 and y > 0 and z > 0:
            ans.append(abs(a-x) + abs(b-y) + abs(c-z) + 10 * (ca + cb + cc - 3))
f(0,0,0,l,0,0,0)
print(min(ans))

Submission status: Accepted

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

def search(t,a,b,c):
    if t == n:
        return abs(A-a)+abs(B-b)+abs(C-c) -30 if min(a,b,c) > 0 else 10**9
        #-30について。少なくともa,b,c各一本の竹はコストを払わずに使用することができ、また必ず使用するため、
        #予め30引くことでそのままprintできる。(printの方で-30したほうが分かりやすいとは思うが)
    ret0 = search(t+1,a,b,c)
    ret1 = search(t+1,a+list1[t],b,c) +10
    ret2 = search(t+1,a,b+list1[t],c) +10
    ret3 = search(t+1,a,b,c+list1[t]) +10
    return min(ret0,ret1,ret2,ret3)

print(search(0,0,0,0))

Submission status: Accepted

Solution code:
import itertools


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

for pattern in itertools.product(range(4), repeat=N):
    if not {1, 2, 3} <= set(pattern):
        continue

    trees = [0] * 3
    synthesis_cost = -30
    for num, length in zip(pattern, L):
        if num == 0:
            continue
        trees[num-1] += length
        synthesis_cost += 10

    fix_cost = 0
    for tree_length, target_length in zip(trees, [A, B, C]):
        fix_cost += abs(target_length - tree_length)

    total_cost = synthesis_cost + fix_cost
    ans = min(ans, total_cost)

print(ans)

Submission status: Accepted

Solution code:

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

big=10**9

def dp(cur,a,b,c):
  if cur==n:
    if a==0 or b==0 or c==0:
      return big
    else:
      return abs(A-a)+abs(B-b)+abs(C-c)-30
  else:
    ret0 = dp(cur+1,a,b,c)
    ret1 = dp(cur+1,a+l[cur],b,c)+10
    ret2 = dp(cur+1,a,b+l[cur],c)+10
    ret3 = dp(cur+1,a,b,c+l[cur])+10
    return min([ret0, ret1, ret2, ret3])

ret=dp(0,0,0,0)
print(ret)

Submission status: Accepted

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


def ketame(n, i):
  return n // (4 ** i) % 4


mps = []
import itertools
for pro in itertools.product([0, 'a', 'b', 'c'], repeat=n):
  if pro.count('a') == 0 or pro.count('b') == 0 or pro.count('c') == 0:
    continue
  merge = {'a': 0, 'b': 0, 'c': 0}
  for i in range(n):
    if pro[i] != 0:
      merge[pro[i]] += l[i]
  mp = (max(pro.count('a') - 1, 0) + max(pro.count('b') - 1, 0) +
        max(pro.count('c') - 1, 0)) * 10
  mp += abs(merge['a'] - a)
  mp += abs(merge['b'] - b)
  mp += abs(merge['c'] - c)
  mps.append(mp)

print(min(mps))

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(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:
def base_change(numbers,base,keta):
    s=""
    while numbers>0:
        a,b=divmod(numbers,base)
        if b==0:
            s+="0"
            numbers=a
        elif b!=0:
            s+=str(b)
            numbers=a
    if len(s)<keta:
        s+="0"*(keta-len(s))
    elif len(s)>keta:
        print("桁がどうやら足りないようです。桁をもう少し数が収まるように大きく取ってください　。")
    s=s[::-1]
    return s
#C - Synthetic Kadomatsu
n,A,B,C=map(int,input().split())
lists=[int(input()) for i in range(n)]   
mini=10**9
for i in range(4**(n)):
    alist=[0,0,0,0]
    counterlist=[0,0,0,0]
    S=base_change(i,4,n)
    for i in range(n):
        for j in range(3):
            if S[i]==str(j):
                alist[j]+=lists[i]
                counterlist[j]+=1
    if all(counterlist[j]>0 for j in range(3)):
        mini=min(mini,10*(sum(counterlist[:3])-3)+abs(alist[0]-A)+abs(alist[1]-B)+abs(alist[2]-C))
print(mini)

Submission status: Accepted

Solution code:
def find_index(l,x,default=-1):
    return l.index(x) if x in l else default

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


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

    ans = 10**9
    for i in range(4**n):
        a = 0
        b = 0
        c = 0
        no_use = 0
        temp = 0
        status = base_10_to_n(i,4)
        status = status.zfill(n)
        status = list(map(int,list(status)))
        for j in range(n):
            if status[j] == 0:
                a += l[j]
                temp += 10
            if status[j] == 1:
                b += l[j]
                temp += 10
            if status[j] == 2:
                c += l[j]
                temp += 10
            if status[j] == 3:
                no_use += l[j]
        if a==0 or b==0 or c==0:
            continue
        temp += abs(A-a)+abs(B-b)+abs(C-c)-30
        ans = min(ans,temp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import numpy as np
N, A, B, C = map(int, input().split())
l = [int(input()) for _ in range(N)]
INF = 10 ** 9


def dfs(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
    Sa = dfs(i+1, a+l[i], b, c) + 10
    Sb = dfs(i+1, a, b+l[i], c) + 10
    Sc = dfs(i+1, a, b, c+l[i]) + 10
    Sx = dfs(i+1, a, b, c) 

    return min(Sa, Sb, Sc, Sx)

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

Submission status: Accepted

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


# 先に全ての合成を終えてから延長/縮小をすると考える
# それぞれの竹は、[Aに使う, Bに使う, Cに使う, どれにも使わない]の4通り
# 4 ** 8 = 65536 なので全通り試しても間に合う
def dfs(cur, len_a, len_b, len_c):
    if cur == N:
        if min(len_a, len_b, len_c) > 0:
            # 1本目は合成していないので、10ずつ引いて調整する
            return abs(len_a - A) + abs(len_b - B) + abs(len_c - C) - 30
        else:
            # 竹を1本も使わなかったケースを除外する
            return INF
    # どれにも使わない
    not_use = dfs(cur + 1, len_a, len_b, len_c)
    # Aに使う（Aを使うために合成する）
    use_for_a = dfs(cur + 1, len_a + L[cur], len_b, len_c) + 10
    # Bに使う（Bを使うために合成する）
    use_for_b = dfs(cur + 1, len_a, len_b + L[cur], len_c) + 10
    # Cに使う（Cを使うために合成する）
    use_for_c = dfs(cur + 1, len_a, len_b, len_c + L[cur]) + 10

    return min(not_use, use_for_a, use_for_b, use_for_c)


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

Submission status: Accepted

Solution code:
n,a,b,c=map(int,input().split())
l=[]
for i in range(n):
  l.append(int(input()))
bit=[]
for i in range(1,4**n):
  bl=[]
  num=i
  while num!=0:
    bl.append(num%4)
    num=num//4
  while len(bl)<n:
    bl.append(0)
  bit.append(bl)
min=10**10
for i in bit:
  bit1=i
  l1=0
  l2=0
  l3=0
  c1,c2,c3=0,0,0
  for j in range(n):
    if bit1[j]==0:
      l1+=l[j]
      c1+=1
    elif bit1[j]==1:
      l2+=l[j]
      c2+=1
    elif bit1[j]==2: 
      l3+=l[j]
      c3+=1
  if l1==0 or l2==0 or l3==0:
    pass
  else:
    ans=0
    ans+=(c1+c2+c3-3)*10
    ans+=abs(a-l1)+abs(b-l2)+abs(c-l3)
    if min>ans:
      min=ans
print(min)

Submission status: Accepted

Solution code:
def TtoF(a):
  r = ''
  while a >= 1:
    r += str(a%4)
    a = a // 4
  return r[::-1]
n,a,b,c = map(int,input().split())
l = [int(input()) for i in range(n)]
m = float('INF')
for i in range(1,4**n):
  cur = TtoF(i)
  cur = '0'*(n-len(cur)) + cur
  abc = [[] for i in range(3)]
  for j in range(n):
    if cur[j] != '3':
      abc[int(cur[j])].append(l[j])
  if [] in abc:
    continue
  else:
    m = min(m,10*(len(abc[0])-1)+abs(sum(abc[0])-a)+10*(len(abc[1])-1)+abs(sum(abc[1])-b)+10*(len(abc[2])-1)+abs(sum(abc[2])-c))
print(m)

Submission status: Accepted

Solution code:
N, A, B, C = map(int, input().split())
li = [int(input()) for i in range(N)]
INF = 10**9
def dfs(cur, a, b, c):
  if cur == N:
    if min(a, b, c) > 0:
      return abs(a-A) + abs(b-B) + abs(c-C) - 30
    else:
      return INF
  else:
    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))

Submission status: Accepted

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

def dfs(i,a,b,c):
  #竹を全部巡ったら
  ##1つ上の関数の働きを考えながらベース式で何をするかを定める
  if i == N:
    #a,b,cは合成によって得られた竹の長さ
    if min(a,b,c) > 0:
      #差の絶対値が延長・短縮に必要なMP
      #a,b,c = 0 から竹の長さに値を与えるために1本ずつ竹を使っているため
      #10 * 3の分だけ余分に合成魔法のMPが使われているから、引く
      return abs(a - A) + abs(b - B) + abs (c - C) - 30
    #竹を1本も材料としなかった場合 = 却下のケース
    ##=無の竹に延長短縮魔法は使えない
    #i = N - 1で却下するためにINFを返す
    else:
      return INF
  
  else:
    #竹の長さをa,b,cに足してゆき、消費MP10を値に足す
    #使わない場合は竹の長さもMPも足さない
    ret0 = dfs(i + 1,a,b,c)
    ret1 = dfs(i + 1,a + bamboo[i],b,c) + 10
    ret2 = dfs(i + 1,a,b + bamboo[i],c) + 10
    ret3 = dfs(i + 1,a,b,c + bamboo[i]) + 10
    
    #次の再帰呼び出しの中で最小のものを選び値を返す
    #i = 4の関数で abs ~ -30を受け取る
    return min(ret0,ret1,ret2,ret3)
  
print(dfs(0,0,0,0))

Submission status: Accepted

Solution code:
import itertools
n,a,b,c = map(int,input().split())

ll = []
for _ in range(n):
    l = int(input())
    ll.append(l)
    

assign = [0, 1, 2, 3]

ans = float('inf')
for assignl in itertools.product(assign, repeat=n):
    mp = -30
    abc = [0,0,0]
    for idx, i in enumerate(assignl):
        if i > 0:
            mp += 10
            abc[i-1] += ll[idx]
    if 0 in abc:
        continue
    else:
        mp += abs(abc[0] - a)
        mp += abs(abc[1] - b)
        mp += abs(abc[2] - c)
    if mp < ans:
        ans = mp
        
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:
n, a, b, c = map(int, input().split())
L = [0] * n
for i in range(n):
  L[i] = int(input())

iter = [[]]
for i in range(n):
  temp = []
  for num in range(0, 4):
    for lis in iter:
      temp.append(lis + [num])
  else:
    iter = temp

min_cost = 1000000000000000
for lis in iter:
  length = [0, 0, 0, 0]
  cost = -30
  if 1 in lis and 2 in lis and 3 in lis:
    for i in range(n):
      length[lis[i]] += L[i]
      if lis[i] != 0: 
        cost += 10
    cost += abs(length[1] - a)
    cost += abs(length[2] - b)
    cost += abs(length[3] - c)
    min_cost = min(min_cost, cost)
  else:
    continue
print(min_cost)