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

    """ convenient functions
    # for i, a in enumerate(iterable)
    # q, mod = divmod(a, b)
    # divmod(x, y) returns the tuple (x//y, x%y)
    # Higher-order function: reduce(operator.mul, xyz_count, 1)
    # manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
    """

    """convenient decorator
    # @functools.lru_cache():
    # to facilitate use of recursive function
        # ex:
        # from functools import lru_cache
        # import sys
        # sys.setrecursionlimit(10**9)
        # @lru_cache(maxsize=None)
        # def fib(n):
        #     if n < 2:
        #         return n
        #     return fib(n-1) + fib(n-2)
        # print(fib(1000))
    """
    
    # import numpy as np
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
    # accumulate() returns iterator! to get list: list(accumulate())
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  # prime factor
        b, e = 2, 0  # base, exponent
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        # TODO: How should I do when n - r is negative?
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict # https://docs.python.org/ja/3/library/collections.html#collections.deque
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
    from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
    import operator
    from operator import itemgetter
    # ex1: List.sort(key=itemgetter(1))
    # ex2: sorted(tuples, key=itemgetter(1,2))
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)

    # first create factorial_list
    # fac_list = mod_factorial_list(n)
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
    def modinv(a, p = MOD):
        # evaluate reciprocal using Fermat's little theorem:
        # a**(p-1) is identical to 1 (mod p) when a and p is coprime
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        # fac_list = modfactorial_list(100)
        # print(modcomb(100, 5, modfactorial_list(100)))
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    """ initialize variables and set inputs
    # initialize variables
        # to initialize list, use [0] * n
        # to initialize two dimentional array, use [[0] * N for _ in range(N)]
    # set inputs
        # open(0).read() is a convenient method:
        # ex) n, m, *x = map(int, open(0).read().split())
        #     min(x[::2]) - max(x[1::2])
        # ex2) *x, = map(int, open(0).read().split())
        #     don't forget to add comma after *x if only one variable is used
    # preprocessing
        # transpose = [x for x in zip(*data)]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        # flat = [flatten for inner in data for flatten in inner]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    # calculate and output
        # output pattern
        # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
    """

    # functions used
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    R = lambda: list(map(int, r().split()))
    Rmap = lambda: map(int, r().split())
    Rfloat = lambda: list(map(float, r().split()))
    Rtuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    # single int: int(r())
    # single string: r()
    # single float: float(r())
    # line int: R()
    # line string: r().split()
    # line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
    # lines int: [R() for _ in range(n)]
    """

    if __name__ != '__main__':
        # for test
        sys.stdin = open('sample.txt')

    # ----------------------------------
    # main

    N, A, B, C = Rmap()
    L = [r_int() for _ in range(N)]
    G = [[0,1,2,3] for _ in range(N)]
    ans = INF
    for  i in product(*G):
        group_sum = [0] * 4
        group_count = [0] * 4
        for j, k in enumerate(i):
            group_sum[k] += L[j]
            group_count[k] += 1
        if 0 in group_count[:3]:
            continue
        ans = min(ans, (abs(A - group_sum[0]) + abs(B - group_sum[1]) + abs(C - group_sum[2]) + (max(group_count[0]-1,0)+max(group_count[1]-1,0)+max(group_count[2]-1,0))*10))
    print(ans)
    
    # end of main
    # ----------------------------------

    """memo: how to use defaultdict of list
    # initialize
    Dic = defaultdict(list)
    # append / extend
    Dic[x].append(y)
    # for
    for k, v in Dic.items():
    """

if __name__ == '__main__':
    main()

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):
    t = [[],[],[],[]]
    for j in range(n):
        tmp = i//4**j
        t[tmp%4].append(l[j])
    if sum(t[0]) == 0 or sum(t[1]) == 0 or sum(t[2]) == 0:
        continue
    cost= abs(a - sum(t[0])) + abs(b - sum(t[1])) + abs(c - sum(t[2])) + 10*sum([len(t[0]),len(t[1]),len(t[2]),-3])
    ans = min(ans, cost)
print(int(ans))

Submission status: Accepted

Solution code:
n,A,B,C = map(int,input().split())
l = [int(input()) for i in range(n)]
ans = abs(l[0]-A)+abs(l[1]-B)+abs(l[2]-C)
for i in range(4**n):
    a = []
    b = []
    c = []
    for j in range(n):
        if i%4 == 0:
            a.append(l[j])
        if i%4 == 1:
            b.append(l[j])
        if i%4 == 2:
            c.append(l[j])
        i = int(i/4)
    if all([a,b,c]):
        mp = abs(sum(a)-A)+abs(sum(b)-B)+abs(sum(c)-C)+10*(len(a)+len(b)+len(c)-3)
        ans = min(ans,mp)
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)


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

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


main()

Submission status: Accepted

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

def dfs(counter,a,b,c):
    if counter==N:
        #lの中の適当な棒を持った時点から正味スタート
        if a>0 and b>0 and c>0:
            offset=10*3
            return abs(A-a)+abs(B-b)+abs(C-c)-offset
        else:
            #棒を持っていないものは候補外
            return 10**9
    #合成魔法
    #何もしなかった分も含めて、ちょっと足りない、ちょっと長すぎは
    #上のif内で調整
    ret0=dfs(counter+1,a,b,c)
    ret1=dfs(counter+1,a+l[counter],b,c)+10
    ret2=dfs(counter+1,a,b+l[counter],c)+10
    ret3=dfs(counter+1,a,b,c+l[counter])+10
    return min(ret0,ret1,ret2,ret3)

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

Submission status: Accepted

Solution code:
import math
import sys
import itertools
import queue
from fractions import gcd
 
def lcm(a, b):
    return a * b // gcd(a, b)
 

mod = 1000000007
 
if __name__ == "__main__":
    #inputfile = open("input.txt")
    N, A, B, C = map(int, sys.stdin.readline().split())
    l = [int(sys.stdin.readline()) for i in range(N)]
    INF = 10 ** 9
 
    def dfs(idx, a, b, c):
        if idx == N:
            # 初期値a,b,c = 0となっているため、一本目の竹についても合成された扱いになってしまっている
            # したがって、実際はかかっていない合成コスト30を引いている
            # a,b,cのうち少なくとも一本は必ず使われる設定になっているため、30を必ず引くような実装であっても問題はない
            return abs(A - a) + abs(B - b) + abs(C - c) - 30 if min(a, b, c) > 0 else INF
        # 一本あたりの竹について、合成しない、Aに合成、Bに合成、Cに合成の全てのパターンを以下で試行している
        no_synth = dfs(idx + 1, a, b, c)
        synth_A  = dfs(idx + 1, a + l[idx], b, c) + 10
        synth_B  = dfs(idx + 1, a, b + l[idx], c) + 10
        synth_C  = dfs(idx + 1, a, b, c + l[idx]) + 10
        return min(no_synth, synth_A, synth_B, synth_C)
 
    print(dfs(0,0,0,0))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
#ABC119 C

n,A,B,C = map(int,input().split())
l = [int(input()) for _ in range(n)]
INF = float('inf')
#使わない竹、a用、b用、c用に使う竹をあらかじめ決める(4**n通り)
#a用、b用、c用に使う竹をすべて合成する
#+1,-1で調整する

def dfs(cur,a,b,c):#cur:=現在見ている竹,a:=竹aの長さ,b:=竹bの長さ,c:=竹cの長さ
    if cur == n:#最後まで見たら
        if min(a,b,c) > 0:#合成には,a,b,cそれぞれ1本以上必要(本数0→1も合成としている)
            #abs(X-x):=目標の長さまでの差(+1,-1で調整する回数)
            #-30:=長さ0→l[cur]の部分でも10を足しているためa,b,c分引く
            return abs(A - a) + abs(B - b) + abs(C - c) - 30
        else:
            return INF
    ret0 = dfs(cur+1,a,b,c)#使わない場合
    ret1 = dfs(cur+1,a+l[cur],b,c) + 10#a用として竹(l[cur])を使う(合成する)場合
    ret2 = dfs(cur+1,a,b+l[cur],c) + 10#b用として竹(l[cur])を使う(合成する)場合
    ret3 = dfs(cur+1,a,b,c+l[cur]) + 10#c用として竹(l[cur])を使う(合成する)場合
    return min(ret0,ret1,ret2,ret3)
print(dfs(0,0,0,0))

Submission status: Accepted

Solution code:
N, A, B, C = [int(elem) for elem in input().split()]
inf = 10 ** 9

ls = []
for i in range(0, N):
  l = int(input())
  ls.append(l)

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 + ls[cur], b, c) + 10
  ret2 = dfs(cur + 1, a, b + ls[cur], c) + 10
  ret3 = dfs(cur + 1, a, b, c + ls[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)]

ret = float('inf')
for k in range(4 ** N):
    cost = 0
    stick = [0, 0, 0]

    for i in range(N):
        t = k % 4
        if t != 0:
            if stick[t - 1] > 0:
                cost += 10
            stick[t - 1] += l[i]
        k //= 4

    if stick[0] == 0 or stick[1] == 0 or stick[2] == 0:
        continue
    cost += abs(A - stick[0]) + abs(B - stick[1]) + abs(C - stick[2])

    ret = min(ret, cost)

print(ret)

Submission status: Accepted

Solution code:
import itertools
n,a,b,c=map(int,input().split())
l=[int(input()) for _ in range(n)]
li=[0,1,2,3]
it = list(itertools.product(li,repeat=n))
it = [i for i in it if 0 in i and 1 in i and 2 in i]
INF=100000007
ans=INF
for i in it:
    tmp=-30
    l_tmp=[0,0,0,0]
    for j in range(n):
        l_tmp[i[j]]+=l[j]
        if i[j]!=3:tmp+=10
    tmp=tmp+abs(l_tmp[0]-a)+abs(l_tmp[1]-b)+abs(l_tmp[2]-c)
    if tmp<ans:ans=tmp
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, ai, bi, ci):
  if cur == n:
    return abs(ai-a) + abs(bi-b) + abs(ci - c) - 30 if min(ai,bi,ci) > 0 else INF
  ret0 = dfs(cur + 1, ai, bi, ci)
  ret1 = dfs(cur + 1, ai+l[cur], bi, ci) + 10
  ret2 = dfs(cur + 1, ai, bi+l[cur], ci) + 10
  ret3 = dfs(cur + 1, ai, bi, ci+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 ** 9

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
    ret0 = dfs(cur + 1, a, b, c)
    ret1 = dfs(cur + 1, a + l[cur], b, c) + (10 if a > 0 else 0)
    ret2 = dfs(cur + 1, a, b + l[cur], c) + (10 if b > 0 else 0)
    ret3 = dfs(cur + 1, a, b, c + l[cur]) + (10 if c > 0 else 0)
    return min(ret0, ret1, ret2, ret3)

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

Submission status: Accepted

Solution code:
def c_synthetic_kadomatsu(N, A, B, C, L, INF=float('inf')):
    def dfs(cur, a, b, c):
        # cur本目まで竹を見たとき、長さA, B, Cにしたい竹のそれぞれの長さがa, b, cの状態
        if cur == N:
            # すべての竹を見終わった。長さが違う分だけ伸縮する
            # 最終的にできる3本の竹について、1本も竹を使わないことがあってはいけない
            return abs(a - A) + abs(b - B) + abs(c - C) if min(a, b, c) > 0 else INF
        # cur番目の竹をどれかの竹と合成するか、何もしない。そのときのMP
        # 第2項の条件式は、竹の長さ0のときに竹を合成することはないことを反映
        ret0 = dfs(cur + 1, a, b, c)
        ret1 = dfs(cur + 1, a + L[cur], b, c) + (10 if a > 0 else 0)
        ret2 = dfs(cur + 1, a, b + L[cur], c) + (10 if b > 0 else 0)
        ret3 = dfs(cur + 1, a, b, c + L[cur]) + (10 if c > 0 else 0)
        return min(ret0, ret1, ret2, ret3)
    return dfs(0, 0, 0, 0)  # 最初は竹に注目しておらず、どの竹も長さ0

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

Submission status: Accepted

Solution code:
n,a,b,c=map(int,input().split())
l=[int(input())for _ in range(n)]
ans=9999999999
def four(n):
  a=""
  while n:a=str(n%4)+a;n//=4
  return a
for i in range(4**n):
  s=four(i).zfill(n)
  anss=0
  aa=bb=cc=0
  coa=cob=coc=0
  for j in range(n):
    if s[j]=="1":aa+=l[j];coa+=1
    if s[j]=="2":bb+=l[j];cob+=1
    if s[j]=="3":cc+=l[j];coc+=1
  if coa==0 or cob==0 or coc==0:anss=999999999;continue
  anss+=(coa+cob+coc-3)*10
  anss+=abs(aa-a)+abs(bb-b)+abs(cc-c)
  ans=min(ans,anss)
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:
n,a,b,c=map(int,input().split())
banboo = [int(input()) for i in range(n)]

def dfs(num,A,B,C):
    if num == n:
        return abs(A-a)+abs(B-b)+abs(C-c)-30 if min(A,B,C)>0 else float("inf")
    v1 = dfs(num+1,A,B,C)
    v2 = dfs(num+1,A+banboo[num],B,C) + 10
    v3 = dfs(num+1,A,B+banboo[num],C) + 10
    v4 = dfs(num+1,A,B,C+banboo[num]) + 10
    return min(v1,v2,v3,v4)
print(dfs(0,0,0,0))

Submission status: Accepted

Solution code:
import sys 
n, A, B, C = map(int, raw_input().split())
arr = []
for i in range(n):
    arr.append(int(raw_input()))
A, B, C = sorted([A, B, C], reverse=True)
def dfs(i, a, b, c, mp):
    if i == n:
        if a > 0 and b > 0 and c > 0:
            return abs(A-a) + abs(B-b) + abs(C-c) + mp - 30
        else:
            return sys.maxint
    ret0 = dfs(i+1, a, b, c, mp)
    ret1 = dfs(i+1, a+arr[i], b, c, mp+10)
    ret2 = dfs(i+1, a, b+arr[i], c, mp+10)
    ret3 = dfs(i+1, a, b, c+arr[i], mp+10)
    return min(ret0, ret1, ret2, ret3)
print dfs(0, 0, 0, 0, 0)

Submission status: Accepted

Solution code:
"""
l1,l2,...,lN
N は max8本
A,B,Cの3本の竹にしたい

延長 : 1MP  +1
短縮 : 1MP  -1
合成 : 10MP li + lj
A, B, Cを達成するための最小MP
"""


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

import sys
sys.setrecursionlimit(100000)
"""
Gを作りながら探索するパターン
"""

minMP = 10**9 + 7
def dfs(i,MP,a,b,c):
    global minMP
    # 探索打ち切り条件->計算してしまう
    if i+1  >= N:
        if a>0 and b>0 and c>0:
            cnt = MP + abs(A-a)+abs(B-b)+abs(C-c) - 30 
            minMP = min(cnt,minMP)
        return 0
    l = ls[i+1]
    # 再帰的に探索
    dfs(i+1,MP,a,b,c)   # なんもしない
    dfs(i+1,MP+10,a+l,b,c) # aに
    dfs(i+1,MP+10,a,b+l,c) # bに
    dfs(i+1,MP+10,a,b,c+l) # cに

dfs(-1,0,0,0,0)
print(minMP)

Submission status: Accepted

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

ans = 3000
for bits in range(4**n):
    xa = xb = xc = 0
    tmp_ans = 0
    for i in range(n):
        f = (bits//(4**i)) % 4
        if f == 1:
            if xa != 0:
                tmp_ans += 10
            xa += l[i]
        elif f == 2:
            if xb != 0:
                tmp_ans += 10
            xb += l[i]
        elif f == 3:
            if xc != 0:
                tmp_ans += 10
            xc += l[i]

    if xa == 0 or xb == 0 or xc == 0:
        continue
    
    tmp_ans += abs(a - xa) + abs(b - xb) + abs(c - xc)
    ans = min(ans, tmp_ans)

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_tmp, b_tmp, c_tmp):
    if cur == n:
        return abs(a_tmp-a)+abs(b_tmp-b)+abs(c_tmp-c)-30 if min(a_tmp,b_tmp,c_tmp) > 0 else INF
    ret0 = dfs(cur+1, a_tmp, b_tmp, c_tmp)
    ret1 = dfs(cur+1, a_tmp+l[cur], b_tmp, c_tmp)+10
    ret2 = dfs(cur+1, a_tmp, b_tmp+l[cur], c_tmp)+10
    ret3 = dfs(cur+1, a_tmp, b_tmp, c_tmp+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)]


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

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:
    # -30で各Lの一回目の使用のコストを調整する。abs(a-A)で何度+-1の処理が必要かを計算する。
    return abs(a - A) + abs(b - B) + abs(c - C) - 30 if min(a, b, c) > 0 else INF
  # 各Lを使うか使わないか決める
  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 _ in range(N)]
INF = 10 ** 9


def dfs(cur, a, b, c):
  if cur == N:
    # -30で各Lの一回目の使用のコストを調整する。abs(a-A)で何度+-1の処理が必要かを計算する。
    return abs(a - A) + abs(b - B) + abs(c - C) - 30 if min(a, b, c) > 0 else INF
  # 各Lを使うか使わないか決める
  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:
import itertools

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

state = ['A', 'B', 'C', 'D']
loop = list(itertools.product(state, repeat=N))

m = 10**8

for i in range(4**N):
    takeA = 0
    takeB = 0
    takeC = 0
    syn = -3
    for j in range(N):
        if loop[i][j] == 'A':
            takeA += l[j]
            syn += 1
        elif loop[i][j] == 'B':
            takeB += l[j]
            syn += 1
        elif loop[i][j] == 'C':
            takeC += l[j]
            syn += 1
    if takeA!=0 and takeB!=0 and takeC!=0:
        m = min(m, abs(takeA-A)+abs(takeB-B)+abs(takeC-C)+10*syn)
        
print(m)

Submission status: Accepted

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

for i in range(4**n):
    abc=[[],[],[],[]]
    for j in range(n):
            abc[i // (4**(n-1-j))].append(j)
            i = i % (4**(n-1-j))
    if len(abc[0]) == 0 or len(abc[1]) == 0 or len(abc[2]) == 0:
            continue
    a_mp = abs(sum(l[i] for i in abc[0])-a) + (len(abc[0])-1)*10
    b_mp = abs(sum(l[i] for i in abc[1])-b) + (len(abc[1])-1)*10
    c_mp = abs(sum(l[i] for i in abc[2])-c) + (len(abc[2])-1)*10
    mp_min = min(mp_min, a_mp+b_mp+c_mp)
print(mp_min)

Submission status: Accepted

Solution code:
# editorialを参考に、再帰を使わず実装
N, len_A, len_B, len_C = map(int, input().split())
l = [int(input()) for i in range(N)]

ans = 10 ** 9
pattern = 4 ** N
A = [0] * pattern
B = [0] * pattern
C = [0] * pattern
cost = [0] * pattern
for ite in range(pattern):
    ite_2 = 0
    ite_2 += ite
    A[ite], B[ite], C[ite] = [], [], []
    for j in range(N):
        if ite_2 % 4 == 0:
            A[ite].append(l[j])
        elif ite_2 % 4 == 1:
            B[ite].append(l[j])
        elif ite_2 % 4 == 2:
            C[ite].append(l[j])
        ite_2 = ite_2 // 4
    if len(A[ite]) == 0 or len(B[ite]) == 0 or len(C[ite]) == 0:
        continue
    len_A_magic, len_B_magic, len_C_magic = 0, 0, 0
    for p in A[ite]:
        len_A_magic += p
    for q in B[ite]:
        len_B_magic += q
    for r in C[ite]:
        len_C_magic += r
    cost[ite] += (len(A[ite]) - 1) * 10+abs(len_A-len_A_magic)
    cost[ite] += (len(B[ite]) - 1) * 10+abs(len_B-len_B_magic)
    cost[ite] += (len(C[ite]) - 1) * 10+abs(len_C-len_C_magic)
    if ans > cost[ite]:
        ans = cost[ite]

print(ans)

Submission status: Accepted

Solution code:
"""
# 標準入力取得
## 文字列
 = sys.stdin.readline().rstrip()
 = list(sys.stdin.readline().rstrip())

## 数値
 = int(sys.stdin.readline())
 = map(int, sys.stdin.readline().split())
 = list(map(int, sys.stdin.readline().split()))
 = [list(map(int,list(sys.stdin.readline().split()))) for i in range(h)]  # 二次元配列入力　二次元マップみたいな入力のとき

# 0埋め, 小数点出力桁指定時のときの出力
a = 100
b = 0.987654321
print("{0:06d}-{1:6f}".format(a,b))
000100-0.987654

# 文字列をリストに格納
char_list = list("abcd") # ["a","b","c","d"]
"""

import math
import sys
import itertools
import queue
from fractions import gcd

def lcm(a, b):
    return a * b // gcd(a, b)

mod = 1000000007

if __name__ == "__main__":
    #inputfile = open("input.txt")
    N, A, B, C = map(int, sys.stdin.readline().split())
    l = [int(sys.stdin.readline()) for i in range(N)]
    INF = 10 ** 9

    def dfs(idx, a, b, c):
        if idx == N:
            # 初期値a,b,c = 0となっているため、一本目の竹についても合成された扱いになってしまっている
            # したがって、実際はかかっていない合成コスト30を引いている
            # a,b,cのうち少なくとも一本は必ず使われる設定になっているため、30を必ず引くような実装であっても問題はない
            return abs(A - a) + abs(B - b) + abs(C - c) - 30 if min(a, b, c) > 0 else INF
        # 一本あたりの竹について、合成しない、Aに合成、Bに合成、Cに合成の全てのパターンを以下で試行している
        no_synth = dfs(idx + 1, a, b, c)
        synth_A  = dfs(idx + 1, a + l[idx], b, c) + 10
        synth_B  = dfs(idx + 1, a, b + l[idx], c) + 10
        synth_C  = dfs(idx + 1, a, b, c + l[idx]) + 10
        return min(no_synth, synth_A, synth_B, synth_C)

    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:
from sys import stdin

# ABC
# N = int(stdin.readline().rstrip())


def dfs(x):
    ret = 0
    if int(x) > N:
        return ret
    if '7' in x and '5' in x and '3' in x:
        ret += 1
    for k in '753':
        ret += dfs(x + k)
    return ret


# print(dfs('0'))

# ABC119 C - Synthetic Kadomatsu
N, A, B, C = [int(x) for x in stdin.readline().rstrip().split()]
l = [int(stdin.readline().rstrip()) for _ in range(N)]


def solve(m, a, b, c):
    if m == N:
        if a == 0 or b == 0 or c == 0:
            return 10 ** 7
        else:
            return abs(a - A) + abs(b - B) + abs(c - C) - 30
    return min(solve(m + 1, a, b, c), solve(m + 1, a + l[m], b, c) + 10,
               solve(m + 1, a, b + l[m], c) + 10, solve(m + 1, a, b, c + l[m]) + 10)


print(solve(0, 0, 0, 0))

Submission status: Accepted

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

inf = 1000000
def cost(N,x,y,z):
  if N == n:
    if x*y*z == 0:
      return inf
    return abs(x-a) + abs(y-b) + abs(z-c)
  
  cost1 = cost(N+1,x,y,z)
  cost2 = cost(N+1,x+li[N],y,z) + 10
  cost3 = cost(N+1,x,y+li[N],z) + 10
  cost4 = cost(N+1,x,y,z+li[N]) + 10
  return min(cost1,cost2,cost3,cost4)

print(cost(0,0,0,0)-30)

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