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:
INF = float('inf')

def rec(i, a, b, c):
    if i==N:
        if not a or not b or not c:
            return INF
        return abs(a-A) + abs(b-B) + abs(c-C)

    res = rec(i+1, a, b, c)

    res = min(res, rec(i+1, a+L[i], b, c) + (10 if a else 0))
    res = min(res, rec(i+1, a, b+L[i], c) + (10 if b else 0))
    res = min(res, rec(i+1, a, b, c+L[i]) + (10 if c else 0))

    return res

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

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

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

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

def dfs(idx, a, b, c):
    if idx == N:
        return abs(a - A) + abs(b - B) + abs(c - C) - 30 if min(a, b, c) > 0 else INF
    ret0 = dfs(idx+1, a, b, c)
    ret1 = dfs(idx+1, a + l[idx], b, c) + 10
    ret2 = dfs(idx+1, a, b + l[idx], c) + 10
    ret3 = dfs(idx+1, a, b, c + l[idx]) + 10
    return min(ret0, ret1, ret2, ret3)
if __name__ == "__main__":
    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)]
import itertools 
ans=300000
for i in itertools.product('ABCD',repeat=N):
  cst=0
  A=[]
  B=[]
  C=[]
  for j in range(N):
    if i[j]=='A':
      A.append(L[j])
    elif i[j]=='B':
      B.append(L[j]) 
    elif i[j]=='C':
      C.append(L[j])
  if len(A)>0 and len(B)>0 and len(C)>0:
    if len(A)>1:
      cst+=(len(A)-1)*10
    cst+=abs(sum(A)-a)
    if len(B)>1:
      cst+=(len(B)-1)*10
    cst+=abs(sum(B)-b)
    if len(C)>1:
      cst+=(len(C)-1)*10
    cst+=abs(sum(C)-c)
    ans=min(ans,cst)
 
print(ans)

Submission status: Accepted

Solution code:
import itertools
n = list(map(int,input().split()))
l = [int(input()) for i in range(n[0])]
ans = 10**9

la = [0,1,2,3]


for i in itertools.product(la,repeat=n[0]):
    count = 0
    
    if (1 not in i) or (2 not in i) or (3 not in i):
        continue
    
    lis = [0]*4
    for j in range(n[0]):
        if i[j] > 0 and lis[i[j]] > 0:
            count += 10
        lis[i[j]] += l[j]

    for j in range(1,4):
        count += abs(lis[j]-n[j])
    ans = min(count,ans)
print(ans)

Submission status: Accepted

Solution code:
# なぜかうまくいかない
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect, bisect_right, bisect_left

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, A, B, C = MAP()
l = [INT() 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 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, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, A, B, C = MAP()
l = [INT() 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 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)]
INF = 10**8


def dfs(current_index, sum_a, sum_b, sum_c):
    if current_index == n:
        if min(sum_a, sum_b, sum_c) > 0:
            return sum(abs(x-y) for x, y in
                       zip([a, b, c], [sum_a, sum_b, sum_c]))-30
        else:
            return INF

    cost_none = dfs(current_index+1, sum_a, sum_b, sum_c)
    cost_a = dfs(current_index+1, sum_a+L[current_index], sum_b, sum_c)+10
    cost_b = dfs(current_index+1, sum_a, sum_b+L[current_index], sum_c)+10
    cost_c = dfs(current_index+1, sum_a, sum_b, sum_c+L[current_index])+10
    return min(cost_none, cost_a, cost_b, cost_c)

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

Submission status: Accepted

Solution code:
from collections import Counter
n, a, b, c = map(int, input().split())
L = [int(input()) for _ in range(n)]


def base_n(x, n, zero_padding=8):
    retval = [[], ['0']][x == 0]
    while x > 0:
        x, r = divmod(x, n)
        retval.append(str(r))
    cnt = zero_padding - len(retval)
    pad = ['', '0'*cnt][cnt > 0]
    return pad+''.join(retval[::-1])

ans = 10**8
for i in range(4**n):
    base_4 = base_n(i, 4, n)
    n_bamboo = n - base_4.count("0")
    ctr = Counter(base_4)
    if n_bamboo < 3 or any(k not in ctr.keys() for k in "123"):
        continue

    cost = 0
    for x, y in zip([a, b, c], "123"):
        cost += abs(x - sum(L[idx]for idx, v in enumerate(base_4)
                            if v == y))+(ctr[y]-1)*10
    if ans > cost:
        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:
        if min(a,b,c)>0:
            return abs(a-A)+abs(b-B)+abs(c-C)-30
        else:
            return INF
    pat0=dfs(cur+1,a+l[cur],b,c)+10
    pat1=dfs(cur+1,a,b+l[cur],c)+10
    pat2=dfs(cur+1,a,b,c+l[cur])+10
    pat3=dfs(cur+1,a,b,c)
    return min(pat0,pat1,pat2,pat3)

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

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


def dfs(cur, a, b, c):
    INF = float("inf")
    if cur == N:
        if min(a, b, c) > 0:
            return abs(a - A) + abs(b - B) + abs(c - C) - 30
        else:
            return INF
    ret = dfs(cur + 1, a, b, c)
    ret_a = dfs(cur + 1, a + L[cur], b, c) + 10
    ret_b = dfs(cur + 1, a, b + L[cur], c) + 10
    ret_c = dfs(cur + 1, a, b, c + L[cur]) + 10
    return min(ret, ret_a, ret_b, ret_c)


def main():

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


if __name__ == "__main__":
    main()

Submission status: Accepted

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

ans = 10**10
for i in range(2**(2*N)) :
    As = []
    Bs = []
    Cs = []
    for j in range(N) :
        if (i >> 2*j)%4 == 0 :
            As.append(b[j])
        elif (i >> 2*j)%4 == 1 :
            Bs.append(b[j])
        elif (i >> 2*j)%4 == 2 :
            Cs.append(b[j])
        else :
            continue
    if As and Bs and Cs :
        mp = 10 * (len(As) + len(Bs) + len(Cs) - 3) \
              + abs(A - sum(As)) + abs(B - sum(Bs)) + abs(C - sum(Cs))
        ans = min(ans, mp)

print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)
from functools import lru_cache

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

@lru_cache(None)
def dfs(cur, a, b, c):
    if cur == N:
        return abs(a - A) + abs(b - B) + abs(c - C) if min(a, b, c) > 0 else INF

    # (10 if _ else 0): 最初の1本目は合成魔法の必要がない
    ret0 = dfs(cur + 1, a, b, c)
    ret1 = dfs(cur + 1, a + l[cur], b, c) + (10 if a else 0)
    ret2 = dfs(cur + 1, a, b + l[cur], c) + (10 if b else 0)
    ret3 = dfs(cur + 1, a, b, c + l[cur]) + (10 if c else 0)

    return min(ret0, ret1, ret2, ret3)

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

Submission status: Accepted

Solution code:
# XをN進数に変換
def base_number(X:int, N:int):
    res = ""
    while True:
        q, mod = divmod(X,N)
        res += str(mod)
        X = q
        if q == 0:
            break
    return res[::-1]

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

ans = float("inf")
for i in range(4 ** N):
    state = list(base_number(i,4).rjust(N, "0"))
    if not set(["0","1","2"]) <= set(state):
        continue
    
    make = [[] for _ in range(3)]
    for j,x in enumerate(state):
        if x == "3":
            continue
        make[int(x)].append(L[j])
    
    MP = 0
    for j,m in enumerate(make):
        if len(m) == 1:
            MP += abs(B[j] - m[0]) # 延長or短縮魔法
        else:
            MP += (len(m) - 1) * 10 # 合成魔法
            MP += abs(B[j] - sum(m))
    
    ans = min(ans, MP)

print(ans)

Submission status: Accepted

Solution code:


from collections import deque


def submit():
    n, a, b, c = map(int, input().split())
    llist = [int(input()) for _ in range(n)]

    def update(st, h):
        return st[0] + h, st[1] + 1

    def cost(st, goal):
        return (st[1] - 1) * 10 + abs(goal - st[0])

    def rec_search(ast, bst, cst, rest):
        # 処理し終わった
        if not rest:
            if ast[1] == 0 or bst[1] == 0 or cst[0] == 0:
                return float('inf')
            else:
                return cost(ast, a) + cost(bst, b) + cost(cst, c)
        else:
            head = rest[0]
            rest = rest[1:]

            # headをAに使う
            acost = rec_search(update(ast, head), bst, cst, rest)
            # headをBに使う
            bcost = rec_search(ast, update(bst, head), cst, rest)
            # headをCに使う
            ccost = rec_search(ast, bst, update(cst, head), rest)
            # headを使わない
            ncost = rec_search(ast, bst, cst, rest)

            return min(acost, bcost, ccost, ncost)


    # それぞれl合計、個数を保存
    ast = (0, 0)
    bst = (0, 0)
    cst = (0, 0)
    
    cost = rec_search(ast, bst, cst, llist)
    print(cost)


if __name__ == "__main__":
    submit()

Submission status: Accepted

Solution code:
n,a,b,c=map(int,input().split())
l=[int(input()) for i in range(n)]
ans=float('inf')
for i in range(4**n):
    abc=[[] for i in range(4)]
    for j in range(n):
        abc[i%4].append(l[j])
        i//=4
    A,B,C,x=abc
    if len(A)==0 or len(B)==0 or len(C)==0:
        continue
    ans=min(ans,abs(sum(A)-a)+abs(sum(B)-b)+abs(sum(C)-c)+(len(A)+len(B)+len(C)-3)*10)
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):
    '''
    深さがNだったら使用MPを評価
    N本の竹を使うときに必要な合成回数はN-1のため，最後に-1*10*3(?)
    1本も竹を使用していなかったら棄却→MPを無限に使うこととしている
    '''
    if cur == N:
        return abs(a - A) + abs(b - B) + abs(c - C) - 30 if min(a, b, c) > 0 else INF

    '''
    cur番目の竹に対して
        ret0:ABCどれにも使わない
        ret1:Aに使う（合成:MP+10）
        ret2:Bに使う（合成:MP+10）
        ret3:Cに使う（合成:MP+10）
    '''
    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
from sys import maxsize

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

min = maxsize
pattern = [0, 1, 2, 3]
for pt in product(pattern, repeat=n):
    mp = 0
    length = [999] + [0] * 3
    for i, k in zip(pt, l):
        if i:
            if length[i]:
                mp += 10
            length[i] += k

    if length.count(0) > 0:
        continue

    mp += abs(a - length[1]) + abs(b - length[2]) + abs(c - length[3])

    if mp < min:
        min = mp

print(min)

Submission status: Accepted

Solution code:
from itertools import product

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

ALL = list(product(['A', 'B', 'C', 'N'], repeat = N))

ans = 10 ** 9 + 7
for node in ALL:
  if len(set([ no for no in node if no != 'N'])) == 3:
    a, b, c = 0, 0, 0
    cost = N - 3 - len([ no for no in node if no == 'N'])
    for i, n in enumerate(node):
      if n == 'A':
        a += L[i]
      elif n == 'B':
        b += L[i]
      elif n == 'C':
        c += L[i]
      else:
        continue
    ans = min(abs(a-A) + abs(b-B) + abs(c-C) + 10 * cost, ans)
    
print(ans)

Submission status: Accepted

Solution code:
# Nが小さいので全探索の構え -> なにをどうする？
# A,B,Cしかないので「li本目をA,B,Cどれの材料にするか」でやれそう -> 振り分けてから和をとって（+=10）それぞれの差を計算(+=1)
n, a, b, c = map(int, input().split())
arr = []
for _ in range(n):
    arr.append(int(input()))


def rec(i, ai, bi, ci):
    if i == n:
        if ai == 0 or bi == 0 or ci == 0:
            # 各最低でも1本以上必要だよね
            return 10 ** 10
        return abs(a - ai) + abs(b - bi) + abs(c - ci)
    else:
        ret = 10 ** 10
        # いま注目してるやつをa,b,cどれに属することにするか選ぶ
        if ai == 0:
            ret = min(ret, rec(i + 1, arr[i], bi, ci))
        elif ai > 0:
            ret = min(ret, rec(i + 1, ai + arr[i], bi, ci) + 10)
        if bi == 0:
            ret = min(ret, rec(i + 1, ai, arr[i], ci))
        elif bi > 0:
            ret = min(ret, rec(i + 1, ai, bi + arr[i], ci) + 10)
        if ci == 0:
            ret = min(ret, rec(i + 1, ai, bi, arr[i]))
        elif ci > 0:
            ret = min(ret, rec(i + 1, ai, bi, ci + arr[i]) + 10)
        # 今回は選ばない場合もある
        ret = min(ret, rec(i + 1, ai, bi, ci))
        return ret


print(rec(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=10**9
for bit in range(4**n):
    v=[0]*n
    A,B,C=0,0,0
    cnt=0
    for i in range(n):
        v[i]=(bit>>2*i)&3 #
        if v[i]==1:
            if A!=0:
                cnt+=10
            A+=l[i]
        elif v[i]==2:
            if B!=0:
                cnt+=10
            B+=l[i]
        elif v[i]==3:
            if C!=0:
                cnt+=10
            C+=l[i]
    if A==0 or B==0 or C==0: #
        continue
    ans=min(ans,abs(a-A)+abs(b-B)+abs(c-C)+cnt)
print(ans)

Submission status: Accepted

Solution code:
N, A, B, C = map(int, input().split())
li = [int(input()) for _ 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+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:
#abc 114 c
INF=100100100
n,A,B,C=map(int,input().split())
L=[]
for i in range(n):
    l=int(input())
    L.append(l)
def dfs(i,a,b,c):
    #print(i,a,b,c)
    if i==len(L):
        return abs(a-A)+abs(b-B)+abs(c-C)-30 if min(a,b,c)>0 else INF#a,b,cは1MP消費で長さ-1するのでマイナスになる可能性ある
        #0以上でないと３本あることにならない
        #1本目のa,b,cを選ぶときにdfs内ではMP10消費しているので-30
    ret0=dfs(i+1,a,b,c)
    ret1=dfs(i+1,a+L[i],b,c)+10
    ret2=dfs(i+1,a,b+L[i],c)+10
    ret3=dfs(i+1,a,b,c+L[i])+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)]
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_10_to_n(x,n):
  tmp=x
  out=''
  while tmp>0:
    out=str(tmp%n)+out
    tmp=int(tmp/n)
  return out
n,a,b,c=map(int,input().split())
l=[int(input()) for i in range(n)]
ans=10**18
for i in range(4**n):
  cost=0
  d=[[] for j in range(4)]
  s=Base_10_to_n(i,4).zfill(n)
  for j in range(n):
    k=int(s[j])
    d[k].append(l[j])
  if len(d[1])*len(d[2])*len(d[3])==0:
    continue
  for j in range(1,4):
    cost+=(len(d[j])-1)*10
  d1=sum(d[1])
  d2=sum(d[2])
  d3=sum(d[3])
  L=[abs(d1-a)+abs(d2-b)+abs(d3-c),abs(d1-a)+abs(d2-c)+abs(d3-b),abs(d1-b)+abs(d2-a)+abs(d3-c),abs(d1-b)+abs(d2-c)+abs(d3-a),abs(d1-c)+abs(d2-a)+abs(d3-b),abs(d1-c)+abs(d2-b)+abs(d3-a)]
  cost+=min(L)
  ans=min(ans,cost)
print(ans)

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 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 float('inf')
    mx = dfs(i+1, a, b, c)
    ma = dfs(i+1, a+l[i], b, c) + 10
    mb = dfs(i+1, a, b+l[i], c) + 10
    mc = dfs(i+1, a, b, c+l[i]) + 10
    return min(mx, ma, mb, mc)


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

Submission status: Accepted

Solution code:
def change_base(n, base):
    q = n // base
    r = n % base
    if q == 0:
        return str(r)
    return change_base(q, base) + str(r)


N, A, B, C = map(int, input().split())
target = [A, B, C]
l = [int(input()) for _ in range(N)]
ans = float('inf')
for n in range(4**N):
    bit = change_base(n, 4)
    bit = '0'*(N-len(bit)) + bit
    start = [0] * 3
    mp = 0
    for i in range(N):
        for j in range(3):
            if bit[i] == str(j):
                if start[j] > 0:
                    mp += 10
                start[j] += l[i]
    if any(s == 0 for s in start):
        continue
    for j in range(3):
        mp += abs(target[j]-start[j])
    ans = min(ans, mp)
print(ans)

Submission status: Accepted

Solution code:
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) - 30 if min(
            x, y, z) > 0 else float('inf')
    res0 = dfs(i + 1, x, y, z)
    res1 = dfs(i + 1, x + l[i], y, z) + 10
    res2 = dfs(i + 1, x, y + l[i], z) + 10
    res3 = dfs(i + 1, x, y, z + l[i]) + 10
    return min(res0, res1, res2, res3)


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

minmp = 10**18

for i in range(4**N):
    mp = 0
    a = []
    b = []
    c = []
    d = []
    
    for j in range(N):
        if i>>(2*j) & 1:
            if i>>(2*j+1) & 1:
                a.append(j)
            else:
                b.append(j)
        else:
            if i>>(2*j+1) & 1:
                c.append(j)
            else:
                d.append(j)
                
    if not a or not b or not c:
        continue
        
    mp += (len(a)-1)*10
    mp += abs(A-sum([L[j] for j in a]))
    mp += (len(b)-1)*10
    mp += abs(B-sum([L[j] for j in b]))
    mp += (len(c)-1)*10
    mp += abs(C-sum([L[j] for j in c]))
    minmp = min(mp,minmp)

print(minmp)

Submission status: Accepted

Solution code:
n,a,b,c = map(int,input().split())
l = [int(input()) for _ in range(n)]
ans = 10000
for i in range(2 ** (2*n)):
  v = [0,0,0,0]
  assign = [(i>>(2*j)) & 3 for j in range(n)]
  cost = 0
  for j in range(n):
    if assign[j] > 0 and v[assign[j]] > 0:
      cost += 10
    v[assign[j]] += l[j]
  if v[1] == 0 or v[2] == 0 or v[3] == 0:
    continue
  ans = min(ans, cost + abs(v[1]-a) + abs(v[2]-b) + abs(v[3]-c))
print(ans)

Submission status: Accepted

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


def recur(n, i, a, b, c):
    if i == n:
        if a < 1 or b < 1 or c < 1:
            return 10 ** 18
        return abs(A-a) + abs(B-b) + abs(C-c)
    return min([
        recur(n, i + 1, a, b, c),
        recur(n, i + 1, a + l[i], b, c) + (10 if a > 0 else 0),
        recur(n, i + 1, a, b + l[i], c) + (10 if b > 0 else 0),
        recur(n, i + 1, a, b, c + l[i]) + (10 if c > 0 else 0)
    ])


print(recur(n, 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 dfs(i, a, b, c):
    if i == N:
        if min(a, b, c) != 0:  # いずれかが0だと竹を1本も使っていないことになる
            return abs(A - a) + abs(B - b) + abs(C - c)
        else:
            return float('inf')
        
    res1 = dfs(i+1, a, b, c)
    
    # 竹をつなぎ合わせる時は10MP消費する
    mp2 = 10 if a > 0 else 0
    mp3 = 10 if b > 0 else 0
    mp4 = 10 if c > 0 else 0
    
    res2 = dfs(i+1, a+L[i], b, c) + mp2
    res3 = dfs(i+1, a, b+L[i], c) + mp3
    res4 = dfs(i+1, a, b, c+L[i]) + mp4
    
    return min(res1, res2, res3, res4)

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

Submission status: Accepted

Solution code:
import itertools
n,a,b,c=map(int,input().split())
x=[a,b,c]
l=[int(input()) for i in range(n)]
ans=1000000
loop='012'
for i in range(2**n):
    use=[]
    for j in range(n):
        if((i>>j)&1):
            use.append(l[j])
    if(len(use)>=3):
        for j in (itertools.product(loop,repeat=len(use))):
            A=[[] for i in range(3)]
            for k in range(len(use)):
                A[int(j[k])].append(use[k])
                
            if(len(A[0])!=0 and len(A[1])!=0 and len(A[2])!=0):
                res=0
                for i in range(3):
                    res+=abs(sum(A[i])-x[i])+(len(A[i])-1)*10
                ans=min(res,ans)
print(ans)

Submission status: Accepted

Solution code:
import itertools
import time
start=time.time()
n,a,b,c=map(int,input().split())
l=[int(input()) for i in range(n)]
ans=1000000007
for i in range(2**n):
    use=[]
    for j in range(n):
        if((i>>j)&1):
            use.append(l[j])#使う竹の列挙
    loop='123'
    if(len(use)>=3):
        for j in (itertools.product(loop,repeat=len(use))):#グループ分けの列挙
            A=[]
            B=[]
            C=[]
            for k in range(len(use)):
                if(j[k]=='1'):
                    A.append(use[k])
                elif(j[k]=='2'):
                    B.append(use[k])
                elif(j[k]=='3'):
                    C.append(use[k])
            if(len(A)!=0 and len(B)!=0 and len(C)!=0):
                res=abs(sum(A)-a)+((len(A)-1)*10)+abs(sum(B)-b)+((len(B)-1)*10)+abs(sum(C)-c)+((len(C)-1)*10)
                ans=min(res,ans)
    else:
        continue
print(ans)

Submission status: Accepted

Solution code:
def solve(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 10 ** 9 + 7


    use_for_a = solve(cur + 1, A + l[cur], B, C) + 10
    use_for_b = solve(cur + 1, A, B + l[cur], C) + 10
    use_for_c = solve(cur + 1, A, B, C + l[cur]) + 10
    not_use = solve(cur + 1, A, B, C)

    return min(use_for_a, use_for_b, use_for_c, not_use)


n, a, b, c = map(int, input().split())
l = [int(input()) for i in range(n)]
print(solve(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

def mag(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 INF

    r0 = mag(i+1, a     , b     , c     )
    r1 = mag(i+1, a+l[i], b     , c     ) + 10
    r2 = mag(i+1, a     , b+l[i], c     ) + 10
    r3 = mag(i+1, a     , b     , c+l[i]) + 10

    return min(r0, r1, r2, r3)

print(mag(0,0,0,0))

Submission status: Accepted

Solution code:
N, A, B, C, *L = map(int, open(0).read().split())
ans = float('inf')
for i in range(4**N):
  a = 0
  b = 0
  c = 0
  m = 0
  for j in range(N):
    if i%4==0:
      if a!=0:
        m += 10
      a += L[j]
    elif i%4==1:
      if b!=0:
        m += 10
      b += L[j]
    elif i%4==2:
      if c!=0:
        m += 10
      c += L[j]
    i //= 4
  if a==0 or b==0 or c==0:
    continue
  ans = min(ans, m+abs(A-a)+abs(B-b)+abs(C-c))
print(ans)

Submission status: Accepted

Solution code:
N,A,B,C=map(int,input().split())
l_list=[]
for i in range(N):
    l_list.append(int(input()))
def f(i,a,b,c):
    if i==N:
        if a*b*c==0:
            return 10**10
        else:
            return abs(a-A)+abs(b-B)+abs(c-C)-30
    else:
        addno=f(i+1,a,b,c)
        addA=f(i+1,a+l_list[i],b,c)+10
        addB=f(i+1,a,b+l_list[i],c)+10
        addC=f(i+1,a,b,c+l_list[i])+10
        return(min(addno,addA,addB,addC))
print(f(0,0,0,0))

Submission status: Accepted

Solution code:
n,a,b,c=map(int,input().split())
tree=[a,b,c]
ls=[int(input()) for _ in range(n)]
ans=10000
for i in range(4**n):
    group=[[] for _ in range(4)]
    for j in range(n):
        k,i=i%4,i//4
        group[k].append(ls[j])
    buf=0
    for l in range(3):
        group_len=len(group[l])
        if group_len==0:
            buf=10000
            break
        buf+=(group_len-1)*10+abs(sum(group[l])-tree[l])
    ans=min(ans,buf)
print(ans)

Submission status: Accepted

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

def dfs(x,a,b,c):
    if x==N:
        return abs(a-A)+abs(b-B)+abs(c-C)-30 if min(a,b,c)>0 else INF
    res0=dfs(x+1,a,b,c)
    res1=dfs(x+1,a+l[x],b,c)+10
    res2=dfs(x+1,a,b+l[x],c)+10
    res3=dfs(x+1,a,b,c+l[x])+10
    return min(res0,res1,res2,res3)
    
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 recur(i, a, b, c):
    if n == i:
        if a < 1 or b < 1 or c < 1:
            return 10 ** 18
        return abs(A-a) + abs(B-b) + abs(C-c)
    return min([
        recur(i + 1, a, b, c),
        recur(i + 1, a + l[i], b, c) + (10 if a > 0 else 0),
        recur(i + 1, a, b + l[i], c) + (10 if b > 0 else 0),
        recur(i + 1, a, b, c + l[i]) + (10 if c > 0 else 0)
    ])


print(recur(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**10

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

# ある竹を,Aに使う、Bに使う、Cに使う、どれにも使わない　の4パターンで全探索
# A,B,C	それぞれに対して2つ目以降は10Pかかる

stack=[]
# Aの長さ、Bの長さ、Cの長さ、処理した竹の本数、消費MP
stack.append([0,0,0,0,0])
ans=1000*10
while stack:
  a,b,c,num,mp=stack.pop()
  if num==N:
    if a==0 or b==0 or c==0:
      continue
    mp+=abs(A-a)+abs(B-b)+abs(C-c)
    if mp<ans:
      ans=mp
    continue
  stack.append([a+L[num],b,c,num+1,mp+(a!=0)*10])
  stack.append([a,b+L[num],c,num+1,mp+(b!=0)*10])
  stack.append([a,b,c+L[num],num+1,mp+(c!=0)*10])
  stack.append([a,b,c,num+1,mp])
print(ans)

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

# ある竹を,Aに使う、Bに使う、Cに使う、どれにも使わない　の4パターンで全探索
# A,B,C	それぞれに対して2つ目以降は10Pかかる

stack=[]
# Aの長さ、Bの長さ、Cの長さ、処理した竹の本数、消費MP
stack.append([0,0,0,0,0])
ans=1000*10
while stack:
  a,b,c,num,mp=stack.pop()
  if num==N:
    if a==0 or b==0 or c==0:
      continue
    mp+=abs(A-a)+abs(B-b)+abs(C-c)
    if mp<ans:
      ans=mp
    continue
  for i in range(4):
    if i==0:
      stack.append([a+L[num],b,c,num+1,mp+(a!=0)*10])
    if i==1:
      stack.append([a,b+L[num],c,num+1,mp+(b!=0)*10])
    if i==2:
      stack.append([a,b,c+L[num],num+1,mp+(c!=0)*10])
    if i==3:
      stack.append([a,b,c,num+1,mp])
print(ans)