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:
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

# def main():
  

# # main()
# print(main())

n,a,b,c=LI()
l=[I() for _ in range(n)]
answer=inf

def f(lst,ind):
  global answer
  if ind==n:
    ac=lst.count(1)
    bc=lst.count(2)
    cc=lst.count(3)

    if ac==0 or bc==0 or cc==0:
      return min(answer,inf)

    _a=_b=_c=0
    for i,x in enumerate(lst):
      if x==1:
        _a+=l[i]
      elif x==2:
        _b+=l[i]
      elif x==3:
        _c+=l[i]
    # 合わなかった原因。短縮できることを忘れてた
    # if _a>a or _b>b or _c>c:
    #   return min(answer,inf)

    sm=0
    sm+=max(0,ac-1)*10
    sm+=max(0,bc-1)*10
    sm+=max(0,cc-1)*10
    sm+=abs(a-_a)
    sm+=abs(b-_b)
    sm+=abs(c-_c)

    return min(answer,sm)

  else:
    for i in range(4):
      lst[ind]=i
      answer=min(answer,f(lst,ind+1))

  return answer

lst=[-1]*n
print(f(lst,0))

Submission status: Accepted

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

choiceList = []
for i in range(4 ** N):
    choice = [-1 for i in range(N)]
    for j in range (N):
        choice[j] = i // (4 ** j) % 4
    choiceList.append(choice)

minCost = 10 ** 9
for choice in choiceList:
    cost = 10 ** 9
    aList = []
    bList = []
    cList = []
    for i in range(N):
        if choice[i] == 1:
            aList.append(l[i])
        elif choice[i] == 2:
            bList.append(l[i])
        elif choice[i] == 3:
            cList.append(l[i])
    if len(aList) == 0 or len(bList) == 0 or len(cList) == 0:
        cost = 10 ** 9
    else:
        aCost = (len(aList) - 1) * 10 + abs(sum(aList) - A)
        bCost = (len(bList) - 1) * 10 + abs(sum(bList) - B)
        cCost = (len(cList) - 1) * 10 + abs(sum(cList) - C)
        cost = aCost + bCost + cCost
    if minCost > cost:
        minCost = cost

print(minCost)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

N, A, B, C = MAP()

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

ans = INF
for x in product(range(4), repeat=N):
	tmp = 0
	bamboo = [0]*4 #[不使用、Aに使用、Bに使用、Cに使用]
	for i in range(N):
		if 0 < x[i] and bamboo[x[i]]:
			tmp += 10
		bamboo[x[i]] += l[i]

	if 0 in bamboo[1:]:
		continue

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

	ans = min(ans, tmp)

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N, A, B, C = map(int, input().split())
L = [int(input()) for i in range(N)]
INF = float('inf')
def dfs(i,a,b,c):
    # さいごまで到達したときの操作  
    if i == N:
        if a==0 or b==0 or c==0:
            return INF
        else:
            return abs(a-A) + abs(b-B) + abs(c-C)
    # すべての手順
    ans0 = dfs(i+1, a, b, c)
    ans1 = dfs(i+1, a+L[i], b, c) + (10 if a != 0 else 0)
    ans2 = dfs(i+1, a, b+L[i], c) + (10 if b != 0 else 0)
    ans3 = dfs(i+1, a, b, c+L[i]) + (10 if c != 0 else 0)
    
    ans = min(ans0, ans1, ans2, ans3)
    return ans

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

if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

Submission status: Accepted

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

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

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:

from itertools import product

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

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

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

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

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

    print(ans)


if __name__ == "__main__":
    main()

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

Submission status: Accepted

Solution code:
from itertools import product

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

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

Submission status: Accepted

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

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

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

    return min(ans0, ans1, ans2, ans3)

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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N,A,B,C= list(map(int,input().split()))
l=[]
Inf=float("Inf")
for i in range(N):l.append(int(input()))
def Answer(cnt,a,b,c):
   if cnt==N:
      return abs(A-a)+abs(B-b)+abs(C-c)-30 if min(a,b,c)>0 else Inf
   pt1=Answer(cnt+1,a,b,c)
   pt2=Answer(cnt+1,a+l[cnt],b,c)+10
   pt3=Answer(cnt+1,a,b+l[cnt],c)+10
   pt4=Answer(cnt+1,a,b,c+l[cnt])+10
   return(min(pt1,pt2,pt3,pt4))
print(Answer(0,0,0,0))

Submission status: Accepted

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

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

print(min(ans))

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
# abc119_c.py
# https://atcoder.jp/contests/abc119/tasks/abc119_c

# C - Synthetic Kadomatsu /
# 実行時間制限: 2 sec / メモリ制限: 1024 MB
# 配点 : 300点

# 問題文
# あなたは N本の竹を持っています。これらの長さはそれぞれ l1,l2,...,lNです (単位: センチメートル)。
# あなたの目的は、これらの竹のうち何本か (全部でもよい) を使い、長さが A,B,Cであるような 3本の竹を得ることです。
# そのために、以下の三種類の魔法を任意の順に何度でも使うことができます。
#     延長魔法: 1MP (マジックポイント) を消費し、1 本の竹を選んでその長さを 1増やす。
#     短縮魔法: 1MP を消費し、1 本の長さ 2 以上の竹を選んでその長さを 1減らす。
#     合成魔法: 10MP を消費し、2 本の竹を選んで接続し 1 本の竹とする。この新たな竹の長さは接続した 2本の竹の長さの合計に等しい。
#     (以後、この竹に対してさらに魔法を使用することもできる。)

# 目的を達成するには、最小でいくつの MP が必要でしょうか？

# 制約
#     3≤N≤8
#     1≤C<B<A≤1000
#     1≤li≤1000
#     入力される値はすべて整数である。

# 入力
# 入力は以下の形式で標準入力から与えられる。
# N A B C
# l1
# l2
# :
# lN

# 出力
# 目的の達成に必要な MP の最小量を出力せよ。

# 入力例 1
# 5 100 90 80
# 98
# 40
# 30
# 21
# 80

# 出力例 1
# 23

# 長さ 98,40,30,21,80の 5 本の竹から長さ 100,90,80 の 3 本の竹を得ようとしています。
# 長さ 80 の竹ははじめから持っており、長さ 100,90 の竹は次のように魔法を使うと合計 23MP を消費することで得られ、これが最適です。

#     長さ 98の竹に延長魔法を 2 回使い、長さ 100 の竹を得る。(消費 MP: 2)
#     長さ 40,30の竹に合成魔法を使い、長さ 70 の竹を得る。(消費 MP: 10)
#     長さ 21の竹に短縮魔法を 1 回使い、長さ 20 の竹を得る。(消費 MP: 1)
#     手順 2. で得た長さ 70の竹と手順 3. で得た長さ 20 の竹に合成魔法を使い、長さ 90 の竹を得る。(消費 MP: 10)

# 入力例 2
# 8 100 90 80
# 100
# 100
# 90
# 90
# 90
# 80
# 80
# 80

# 出力例 2
# 0

# 欲しい長さの竹をすでにすべて持っている場合、必要な MP は 0です。このように、必ずしもすべての竹を使う必要はありません。

# 入力例 3
# 8 1000 800 100
# 300
# 333
# 400
# 444
# 500
# 555
# 600
# 666

# 出力例 3
# 243


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

    patterns = get_patterns(N)

    result = None

    # print(patterns)

    # patterns = ['01020003']
    # patterns = ['01021003', '01020003', '31320113']

    # patterns = ['32012100']

    for pattern in patterns:

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

        # print(f'mp=[{mp}]')

        if result is None:
            result = mp
        else:
            if result > mp:
                # print(f'pattern=[{pattern}], mp=[{mp}]')
                result = mp

    return [result]


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


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


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


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


# 動作モード判別
def get_mode():
    import sys
    args = sys.argv
    if len(args) == 1:
        mode = 0
    else:
        mode = int(args[1])
    return mode


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

    lines_result = calculation(lines_input)

    for line_result in lines_result:
        print(line_result)

    # if mode > 0:
    #     print(f'lines_input=[{lines_input}]')
    #     print(f'lines_export=[{lines_export}]')
    #     print(f'lines_result=[{lines_result}]')
    #     if lines_result == lines_export:
    #         print('OK')
    #     else:
    #         print('NG')
    # finished = time.time()
    # duration = finished - started
    # print(f'duration=[{duration}]')


# 起動処理
if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

Submission status: Accepted

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

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

Submission status: Accepted

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

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

    res0 = dfs(cur+1,a,b,c)
    res1 = dfs(cur+1,a+l[cur],b,c)+10
    res2 = dfs(cur+1,a,b+l[cur],c)+10
    res3 = dfs(cur+1,a,b,c+l[cur])+10
    return min(res0,res1,res2,res3)
print(dfs(0,0,0,0))

Submission status: Accepted

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

def rec(cur, a, b, c):
    if cur == n:
        return abs(a-A) + abs(b-B) + abs(c-C) - 30 if min(a, b, c) > 0 else INF
    ret0 = rec(cur+1, a, b, c)
    ret1 = rec(cur+1, a+L[cur], b, c) + 10
    ret2 = rec(cur+1, a, b+L[cur], c) + 10
    ret3 = rec(cur+1, a, b, c+L[cur]) + 10
    return min(ret0, ret1, ret2, ret3)

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

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
#全探索をA,B,C一度で分けた
# RE 1   ac 19

# 初期入力
import copy
from itertools import combinations
import sys
input = sys.stdin.readline  #文字列では使わない
N,A,B,C = (int(i) for i in input().split())
l =[0]*N
for i in range(N):
    l[i] = int(input())

# A,B,Cどの竹を選ぶかcombination
mp=[]
for na in range(1,N-1):
    for ja in combinations(l,na):

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

                l_c =copy.copy(l_b)
                for i3 in jb:
                    if i3 in l_c:
                        l_c.remove(i3)
                for nc in range(1,N+1):
                    for jc in combinations(l_c ,nc):
                        
                        # MPの消費量＝（求める長さー今回選んだ竹の長さ合計）+10*（合成魔法の回数)
                        AA =abs(A-sum(ja)) +10*(na-1)
                        BB =abs(B-sum(jb)) +10*(nb-1)
                        CC =abs(C-sum(jc)) +10*(nc-1)
                        mp.append(AA +BB +CC)


print(min(mp))

Submission status: Accepted

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

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

def dfs(cur, a, b, c):
    if cur == N:
        return abs(a - A) + abs(b - B) + abs(c - C) - 30 if min(a, b, c) > 0 else INF
    res = dfs(cur + 1, a, b, c)
    res = min(res, dfs(cur + 1, a + l[cur], b, c) + 10)
    res = min(res, dfs(cur + 1, a, b + l[cur], c) + 10)
    res = min(res, dfs(cur + 1, a, b, c + l[cur]) + 10)
    return res
print(dfs(0, 0, 0, 0))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
n, A, B, C =map(int,input().split())
l=[]
for i in range(n):
    l.append(int(input()))
inf=10**9
"""
解法
それぞれの竹について「Aの材料」、「Bの材料」、「Cの材料」、「使わない」の4択を決める(4**n通り)
"""
def dfs(cur, a, b, c):
    if cur==n:
        return abs(a-A)+abs(b-B)+abs(c-C)-30 if min(a,b,c)>0 else inf
    
    ret0=dfs(cur+1,a,b,c)
    ret1=dfs(cur+1,a+l[cur],b,c)+10
    ret2=dfs(cur+1,a,b+l[cur],c)+10
    ret3=dfs(cur+1,a,b,c+l[cur])+10
    return min(ret0, ret1, ret2, ret3)

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

Submission status: Accepted

Solution code:
def main():
    n, a, b, c = list(map(int, input().split()))
    L = [int(input()) for _ in range(n)]
    INF = 1000000
    def dfs(i, la, lb, lc):
        if i == n:
            return abs(la - a) + abs(lb - b) + abs(lc - c) if min(la, lb, lc) > 0 else INF
        res = []
        res.append(dfs(i + 1, la, lb, lc))
        res.append(dfs(i + 1, la + L[i], lb, lc) + 10 if la != 0 else dfs(i + 1, la + L[i], lb, lc))
        res.append(dfs(i + 1, la, lb + L[i], lc) + 10 if lb != 0 else dfs(i + 1, la, lb + L[i], lc))
        res.append(dfs(i + 1, la, lb, lc + L[i]) + 10 if lc != 0 else dfs(i + 1, la, lb, lc + L[i]))
        return min(res)
    print(dfs(0, 0, 0, 0))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys,math,collections,itertools
input = sys.stdin.readline

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

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

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

Submission status: Accepted

Solution code:
# coding: utf-8

# https://atcoder.jp/contests/abc119


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

    abc_mp = []

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

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

    return ans


print(main())

Submission status: Accepted

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

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

loop(T)
print(ans)

Submission status: Accepted

Solution code:
import sys

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

from itertools import product

# 各々の竹をAに使うか、Bに使うか、Cに使うか、使わないかで全探索

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

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

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

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

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

    if score < min_score:
        min_score = score

print(min_score)