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:
# ABC119 Synthetic Kadomatsu

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

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

print(kadomatsu(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:
import sys
sys.setrecursionlimit(100000)
input=sys.stdin.readline
def intinput():return map(int,input().split())

import itertools
n,a,b,c=intinput()
abc=[a,b,c]
l=[0]*n
for i in range(n):
    l[i]=int(input())
k=list(itertools.product((0,1,2,3),repeat=n))
ans=float("inf")
for i in k:
    if 0 not in i or 1 not in i or 2 not in i:
        continue
    tmp=abc[:]
    cnt=[-1,-1,-1]
    for j in range(n):
        if i[j]==3:
            continue
        tmp[i[j]]-=l[j]
        cnt[i[j]]+=1
    cost=0
    for j in range(3):
        cost+=abs(tmp[j])+10*cnt[j]
    ans=min(ans,cost)
print(ans)

Submission status: Accepted

Solution code:
import itertools as it
import time

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


for i in range(N):
	l.append(int(input()))
	
allocate = (list(it.product("0123", repeat = N)))
least_score = 99999999999999999999999
for lst in allocate:
	if lst.count("0") * lst.count("1") * lst.count("2") >= 1:
		abc = [[], [], [], []]
		for i in range(len(lst)):
			abc[int(lst[i])].append(l[i])
		# print(abc)
		score = (len(abc[0]) - 1 + len(abc[1]) - 1 + len(abc[2]) - 1) * 10 + abs(sum(abc[0]) - A) + abs(sum(abc[1]) - B) + abs(sum(abc[2]) - C)
		if score < least_score:
			least_score = score
			
print(least_score)

Submission status: Accepted

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

def search(now, a, b, c):
  if now == N:
    return abs(A-a) + abs(B-b) + abs(C-c) if min(a, b, c) > 0 else INF
  MP0 = search(now+1, a, b, c)
  MP1 = search(now+1, a+l[now], b, c) + 10
  MP2 = search(now+1, a, b+l[now], c) + 10
  MP3 = search(now+1, a, b, c+l[now]) + 10
  return min(MP0, MP1, MP2, MP3)

print(search(0,0,0,0)-30)

Submission status: Accepted

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

def dfs(cur, ta, tb, tc):
  if cur==n:
    if ta<=0 or tb<=0 or tc<=0:
      return 1e9
    else:
      return abs(a-ta)+abs(b-tb)+abs(c-tc)-30

  t1 = dfs(cur+1, ta, tb, tc)
  t2 = dfs(cur+1, ta+l[cur], tb, tc)+10
  t3 = dfs(cur+1, ta, tb+l[cur], tc)+10
  t4 = dfs(cur+1, ta, tb, tc+l[cur])+10
  return min(t1, t2, t3, t4)

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

Submission status: Accepted

Solution code:
from functools import reduce
from fractions import gcd

l = input().split()
N = int(l[0])
ABC =[int(x) for x in l[1:]]
L = []
for i in range(N):
    L.append(int(input()))

# print(N, ABC, L)

def calc_score(a, b, L):
    c = 0
    r = 0
    u = 0
    while b > 0:
        if b & 1 != 0:
            r += L[c]
            u += 1
        c += 1
        b >>= 1
    score = (u - 1) * 10 + abs(a - r)
    return score

ans = 10**9
max_range = 1 << len(L)
for a in range(1, max_range):
    score_a = calc_score(ABC[0], a, L)
    for b in range(1, max_range):
        if a & b != 0:
            continue
        score_b = score_a + calc_score(ABC[1], b, L)
        for c in range(1, max_range):
            if a & c != 0 or b & c != 0:
                continue
            score_c = score_b + calc_score(ABC[2], c, L)
            ans = min(ans, score_c)

print(ans)

Submission status: Accepted

Solution code:

N,A,B,C = map(int,input().split(" "))
l = []
none = 10**6
for i in range(N):
    l.append(int(input()))


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

    ret0 = dfs(cur+1,a,b,c)
    ret1 = dfs(cur+1,a+l[cur],b,c) + 10
    ret2 = dfs(cur+1,a,b+l[cur],c) + 10
    ret3 = dfs(cur+1,a,b,c+l[cur]) + 10

    return min(ret0,ret1,ret2,ret3)

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

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
import itertools
import os
import sys

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")

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

L = np.array(L)

# 全部試す
choosing = np.array(list(itertools.product([0, 1, 2, 3], repeat=N)))
# 0: 選ばない
# 1: 竹 A にする
# 2: 竹 B にする
# 3: 竹 C にする
a = choosing == 1
b = choosing == 2
c = choosing == 3
acnt = a.sum(axis=1)
bcnt = b.sum(axis=1)
ccnt = c.sum(axis=1)
ans = abs(np.dot(a, L) - A) + (acnt - 1) * 10
ans += abs(np.dot(b, L) - B) + (bcnt - 1) * 10
ans += abs(np.dot(c, L) - C) + (ccnt - 1) * 10
print(ans[(acnt > 0) & (bcnt > 0) & (ccnt > 0)].min())

Submission status: Accepted

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

def f(num, x, y, z):
    if num == n:
        if min(x, y, z) > 0:
            return abs(a - x) + abs(b - y) + abs(c - z) - 30
        else:
            return 1000 * 10
    mp_0 = f(num + 1, x, y, z)
    mp_a = f(num + 1, x + l[num], y, z) + 10
    mp_b = f(num + 1, x, y + l[num], z) + 10
    mp_c = f(num + 1, x, y, z + l[num]) + 10
    return min(mp_0, mp_a, mp_b, mp_c)
print(f(0, 0, 0, 0))

Submission status: Accepted

Solution code:
def base_10to(n,m):
    if (n//m):
        return base_10to(n//m, m) + str(n%m)
    return str(n%m)

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):
    d = base_10to(i,4).zfill(n)
    x = 0
    y = 0
    z = 0
    e = 0
    for j in range(n):
        if d[j]=='0':
            x+=l[j]
            e+=1
        elif d[j]=='1':
            y+=l[j]
            e+=1
        elif d[j]=='2':
            z+=l[j]
            e+=1
    if x==0 or y==0 or z==0:
        continue
    ans = min(abs(x-a)+abs(y-b)+abs(z-c)+(e-3)*10,ans)
print(ans)

Submission status: Accepted

Solution code:
# 竹1, 2, 3, 使わない の4種類
# 4 ** 8 = 65536

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

INF = 10 ** 18
answer = INF
for pattern in itertools.product(range(4), repeat = N):
  x = [0] * 4
  MP = 0
  for take, length in zip(pattern, L):
    if take == 3:
      continue
    if x[take] != 0:
      MP += 10
    x[take] += length
  if x[0] == 0 or x[1] == 0 or x[2] == 0:
    continue
  MP += abs(A-x[0])
  MP += abs(B-x[1])
  MP += abs(C-x[2])
  if answer > MP:
    answer = MP
print(answer)

Submission status: Accepted

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

ans = 10**9
for i in range(2**(2*len(l))):
    a = 0
    b = 0
    c = 0
    cnt = 0
    for j in range(len(l)):
        if (i>>j*2)&1 and (i>>j*2+1)&1:
            if a!=0:
                cnt +=10
            a += l[j]
        elif (i>>j*2)&1 and ~(i>>j*2+1)|0:
            if b!=0:
                cnt +=10
            b += l[j]
        elif ~(i>>j*2)|0 and (i>>j*2+1)&1:
            if c!=0:
                cnt +=10
            c += l[j]
        else:
            pass
    if all(x>0 for x in [a,b,c]):
        ans = min(ans,cnt+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=[int(input()) for i in range(N)]
INF=10**9

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

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

Submission status: Accepted

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


def bamboo(i, a, b, c):
    if i == N:
        if a * b * c == 0:
            return 10 ** 12
        return abs(A - a) + abs(B - b) + abs(C - c)
    ans = bamboo(i + 1, a, b, c)
    ans = min(ans, bamboo(i + 1, a + l[i], b, c) + (10 if a else 0))
    ans = min(ans, bamboo(i + 1, a, b + l[i], c) + (10 if b else 0))
    ans = min(ans, bamboo(i + 1, a, b, c + l[i]) + (10 if c else 0))
    return ans


print(bamboo(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 ** 12

def solve(n, cost, a, b, c):
	if n == N:
		if 0 == min(a, b, c):
			return INF
		return abs(a - A) + abs(b - B) + abs(c - C) + cost - 30
	ret1 = solve(n + 1, cost, a, b, c)
	ret2 = solve(n + 1, cost + 10, a + L[n], b, c)
	ret3 = solve(n + 1, cost + 10, a, b + L[n], c)
	ret4 = solve(n + 1, cost + 10, a, b, c + L[n])
	return min(ret1, ret2, ret3, ret4)

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

Submission status: Accepted

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

e=[0]*n
def dfs(i):
    if i==n:
        return solve()
    r=10**10
    for k in range(4):
        e[i]=k
        r=min(r,dfs(i+1))
    return r

def solve():
    ta=tb=tc=0
    ca=cb=cc=0
    for i in range(n):
        if e[i]==1:
            ta+=ll[i]
            ca+=1
        if e[i]==2:
            tb+=ll[i]
            cb+=1
        if e[i]==3:
            tc+=ll[i]
            cc+=1
    if not ca or not cb or not cc:
        return 10**10
    return (ca+cb+cc-3)*10+abs(a-ta)+abs(b-tb)+abs(c-tc)

print(dfs(0))

Submission status: Accepted

Solution code:
N,*A=list(map(int,input().split()))
baml=[int(input()) for _ in range(N)]
ans=-1
tmp=0
def makelist(num):
    madelist=[[],[],[],[]]
    for i in range(N):
        madelist[num%4].append(i)
        num=int(bin(num>>2),0)
    return madelist

def mpcheck(n,comb):
    return abs(sum([baml[x] for x in comb])-A[n])+(len(comb)-1)*10

for i in range(4**N):
    mk=makelist(i)
    tmp=0
    flag=0
    if min([len(x) for x in mk[:3]])==0:
        continue
    for j in range(3):
        tmp+=mpcheck(j,mk[j])
    ans=(min(ans,tmp),tmp)[ans==-1]
print(ans)

Submission status: Accepted

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

length = [0] * N

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

inf = 10 ** 9

def dfs(pos, a, b, c):
    if pos == N:
        if min(a, b, c) > 0:
            #a = 0, b = 0, c = 0だったら題意が成立しない
            return abs(a - A) + abs(b - B) + abs(c - C) - 30
        else:
            return inf
    
    ret1 = dfs(pos + 1, a, b, c)
    ret2 = dfs(pos + 1, a + length[pos], b, c) + 10
    ret3 = dfs(pos + 1, a, b + length[pos], c) + 10
    ret4 = dfs(pos + 1, a, b, c + length[pos]) + 10
    return min(ret1, ret2, ret3, ret4)
    
print(dfs(0, 0, 0, 0))

Submission status: Accepted

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

llist = []
for i in range(N):
  llist.append(int(input()))
  
blist = [0]*N
min_mp = 10000
for i in range(4**N):
  index = i
  for j in range(N):
    blist[j] = index%4
    index = index//4
  
  if 1 not in blist or 2 not in blist or 3 not in blist:
    continue
  
  #print(blist)
  mp = 0
  len_A = 0
  len_B = 0
  len_C = 0
  for j in range(N):
    if blist[j] == 1:
      if len_A != 0:
        mp += 10
      len_A += llist[j]
    if blist[j] == 2:
      if len_B != 0:
        mp += 10
      len_B += llist[j]
    if blist[j] == 3:
      if len_C != 0:
        mp += 10
      len_C += llist[j]
      
  mp += abs(A-len_A)
  mp += abs(B-len_B)
  mp += abs(C-len_C)
  
  if mp < min_mp:
    min_mp = mp
    
print(min_mp)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
'''
allinputs = iter(input().splitlines())
input = lambda : next(allinputs)
#'''
N, A, B, C = map(int, input().split())
l = [int(input()) for _ in range(N)]

m = 4 ** N - 1
group = [0] * N
flag1, flag2, flag3 = -1, -1, -1
sum1, sum2, sum3 = 0, 0, 0
min_cost = 3000

for i in range(m):
	tmp = i
	for j in range(N):
		group[j] = tmp % 4
		tmp //= 4
		if group[j] == 1:
			flag1 += 1
			sum1 += l[j]
		elif group[j] == 2:
			flag2 += 1
			sum2 += l[j]
		elif group[j] == 3:
			flag3 += 1
			sum3 += l[j]
			
	if flag1 >= 0 and flag2 >= 0 and flag3 >= 0:
		cost = 10 * (flag1 + flag2 + flag3) + abs(sum1 - A) + abs(sum2 - B) + abs(sum3 - C)
		if cost < min_cost:
			min_cost = cost
			
	flag1, flag2, flag3 = -1, -1, -1
	sum1, sum2, sum3 = 0, 0, 0
	
print(min_cost)

Submission status: Accepted

Solution code:
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)

def s(generator, splitter, mapper):
    return [ mapper(s) for s in generator().split(splitter) ]

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行区切りの入力をn行読み込んで数値リストにして返します。
def get_nums_n(n):
    return [ int(input()) for _ in range(n)]

n,a,b,c = get_nums_l()
lengths = list(map(int,sys.stdin.readlines()))

ans = 999999999999999

for x in range(4 ** n):
    lll = [0] * 4
    gattai=0
    for i in range(n):
        tmp = x >> (i*2)
        tmp %= 4
        
        if tmp != 0 and lll[tmp] > 0:
            gattai += 1
        lll[tmp] += lengths[i]

    if min(lll[1:]) == 0:
        continue

    mp = gattai*10 + abs(a-lll[1]) + abs(b-lll[2]) + abs(c-lll[3])
    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)]

min_cost = 10 ** 18

def func(n, select):
	global min_cost
	if n == 0:
		if len(set(select) - {0}) < 3:
			return
		#print(select)
		cost = 0
		a, b, c = 0, 0, 0
		for i, t in enumerate(select):
			if t == 1:
				if a != 0:
					cost += 10
				a += L[i]
			if t == 2:
				if b != 0:
					cost += 10
				b += L[i]
			if t == 3:
				if c != 0:
					cost += 10
				c += L[i]
		cost += abs(A - a)
		cost += abs(B - b)
		cost += abs(C - c)
		min_cost = min(min_cost, cost)
		return
	for i in range(4):
		func(n - 1, select + [i])

func(N, [])
print(min_cost)

Submission status: Accepted

Solution code:
def f(x):
    result=""
    while x>=1:
        result+=str(x%4)
        x=int(x/4)
    result=result[::-1]
    return(result)
    
l=[]
MP=[]
N,A,B,C=map(int,input().split())
for _ in range(N):
    l.append(int(input()))

for n in range(4**N-1):
    state=f(n).zfill(N)
    a=state.count("1")
    b=state.count("2")
    c=state.count("3")
    if a==0 or b==0 or c==0:
        pass
    else:
        p,q,r=A,B,C
        ans=(a+b+c-3)*10
        for j in range(N):
            if state[j]=="0":
                pass
            elif state[j]=="1":
                p-=l[j]
            elif state[j]=="2":
                q-=l[j]
            else:
                r-=l[j]
        ans+=abs(p)+abs(q)+abs(r)
        MP.append(ans)

print(min(MP))

Submission status: Accepted

Solution code:
import sys
import itertools

input = sys.stdin.readline
n, a, b, c = map(int, input().split())
l_list = [int(input()) for _ in range(n)]
comb_list = list(itertools.product(range(4), repeat=n))
mp = 10**9+1
for comb in comb_list:
    tmp_a, tmp_b, tmp_c = 0, 0, 0
    cnt_a, cnt_b, cnt_c = 0, 0, 0
    for i, k in enumerate(comb):
        if k > 0:
            if k == 1:
                tmp_a += l_list[i]
                cnt_a += 1
            elif k == 2:
                tmp_b += l_list[i]
                cnt_b += 1
            else:
                tmp_c += l_list[i]
                cnt_c += 1
    if cnt_a > 0 and cnt_b > 0 and cnt_c > 0:
        tmp = abs(a-tmp_a) + abs(b-tmp_b) + abs(c-tmp_c) + (cnt_a-1)*10 + (cnt_b-1)*10 + (cnt_c-1)*10
        mp = min(mp, tmp)
print(mp)

Submission status: Accepted

Solution code:
N, A, B, C = [int(x) for x in input().split()]
ABC = [A, B, C]
total = [0, 0, 0]
cnt = [0, 0, 0]
T = [int(input()) for _ in range(N)]


def calc():
    if min(cnt) <= 0: return 1e10
    return sum([abs(ABC[i] - total[i]) + (cnt[i] - 1) * 10 for i in range(3)])


def f(i):
    if i >= N: return calc()

    res = 1e10
    for j in range(3):
        total[j] += T[i]
        cnt[j] += 1
        res = min(res, f(i + 1))
        total[j] -= T[i]
        cnt[j] -= 1

    return min(f(i + 1), res)


print(f(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:
        if min(a, b, c) > 0:
            return abs(a - A) + abs(b - B) + abs(c - C) - 30  
        else:
            return INF
    ret0 = dfs(cur + 1, a, b, c) #l[cur+1]を使用しない
    ret1 = dfs(cur + 1, a + l[cur], b, c) + 10 ##l[cur+1]をAに使用
    ret2 = dfs(cur + 1, a, b + l[cur], c) + 10 ##l[cur+1]をBに使用
    ret3 = dfs(cur + 1, a, b, c + l[cur]) + 10 ##l[cur+1]を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())
cand = [A, B, C]
l = []
for i in range(N):
    l.append(int(input()))

def search(i, a, b, c):
    tmp = 0
    if i == N:
        if a > 0 and b > 0 and c > 0:
            return abs(A-a)+abs(B-b)+abs(C-c)
        else:
            return 10**9
    
    ret1 = search(i+1, a, b, c)

    tmp = a
    ret2 = search(i+1, a+l[i], b, c)
    if tmp != 0:
        ret2 += 10
    
    tmp = b
    ret3 = search(i+1, a, b+l[i], c)
    if tmp != 0:
        ret3 += 10

    tmp = c
    ret4 = search(i+1, a, b, c+l[i])
    if tmp != 0:
        ret4 += 10
    
    return min(ret1, ret2, ret3, ret4)

print(search(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(i,la,lb,lc,cost):
    if i == N:
        if la*lb*lc == 0:
            return 10**20
        else:
            return abs(A-la)+abs(B-lb)+abs(C-lc)-30+cost
    ret1 = dfs(i+1,la+L[i],lb,lc,cost+10)
    ret2 = dfs(i+1,la,lb+L[i],lc,cost+10)
    ret3 = dfs(i+1,la,lb,lc+L[i],cost+10)
    ret4 = dfs(i+1,la,lb,lc,cost)
    return min(ret1,ret2,ret3,ret4)
print(dfs(0,0,0,0,0))

Submission status: Accepted

Solution code:
#%%
import sys
INPUT = sys.stdin.readline

def SINGLE_INT(): return int(INPUT())
def MULTIPLE_INT_LIST(): return list(map(int, INPUT().split()))
def MULTIPLE_INT_MAP(): return map(int, INPUT().split())
def SINGLE_STRING(): return INPUT()
def MULTIPLE_STRING(): return INPUT().split()

#%%

N, A, B, C = MULTIPLE_INT_MAP()
materials = [int(input()) for _ in range(N)]
INF = 10 ** 9

#%%

def dfs(cursor, a, b, c):  # cursor:カーソル a,b,c:現在の竹の長さ
    if cursor == N:  # cursorが最後まで行ったら終了する。
        return abs(a - A) + abs(b - B) + abs(c - C) - 30 if min(a, b, c) != 0 else INF
    # なぜ30を減じているのかというと、
    # dfs(0,0,0,0)で始まる以上、最初に選ばれるa,b,cを決定する際にもコストが10増加してしまうからである。

    # a,b,cのいずれかに1本も竹を利用していない場合は不適であるため、三項演算子を利用してその場合のコストをINFとする。

    # 再帰(4**N)
    # カーソルの当たっている竹に対して、(A or B or Cに合成する) or (合成しない)の場合に分ける
    no_compound = dfs(cursor+1, a, b, c)
    compound_to_a = dfs(cursor+1, a + materials[cursor], b, c) + 10
    compound_to_b = dfs(cursor+1, a, b + materials[cursor], c) + 10
    compound_to_c = dfs(cursor+1, a, b, c + materials[cursor]) + 10

    return min(no_compound, compound_to_a, compound_to_b, compound_to_c)

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

Submission status: Accepted

Solution code:

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

N= int(N)
A= int(A)
B= int(B)
C= int(C)

stick =[]
leng = []
left_nums = ""
all_zero = ""


for i in range(N):

    x = int(input())
    stick.append(x)
    left_nums += "1"
    all_zero += "0"


for i in range(2 ** N):

    uses_int = format(i,'b')
    uses = uses_int.zfill(N)

    lensum = 0
    
    for j in range(N):

        if (uses[j] == "1"):
            lensum += stick[j]

    leng.append( [lensum , uses] )

#print (leng)


order = ((A,B,C),(A,C,B),(B,A,C),(B,C,A),(C,A,B),(C,B,A))


mini_last = 3001

for i in range(6): #ABC全ての順番において最小を調べる

    point = 0
    lefts = left_nums # 1がN個並んでいる文字列
    

    for j in range(3): #A,B,Cそれぞれの場合において最小を考察&出力

            
            goal = order[i][j] #近づける値

            mini_point = 1001
            mini_num = ""

            for k in leng:

                if (  abs( k[0] - goal ) + ( k[1].count('1') - 1 ) * 10 <= mini_point and abs( k[0] - goal ) + ( k[1].count('1') - 1 ) * 10 >= 0  and k[1] != all_zero ):

                    flag = True
                    for m in range(len(lefts)):

                        if (lefts[m] == "0" and k[1][m] == "1"):
                            flag = False
                            #print ("lefts:",lefts," nowk1:",k[1])

                    if (flag):
                        mini_point = abs( k[0] - goal ) + ( k[1].count('1') - 1 ) * 10
                        mini_num = k[1]


            for m in range(len(mini_num)):

                if (mini_num[m] == "1"):
                    lef_lis = list(lefts)
                    lef_lis[m] = "0"
                    lefts = "".join(lef_lis)

            point += mini_point

            #print ("mp:",mini_point ," mn:",mini_num)

    if (point < mini_last):
        mini_last = point


print (mini_last)

Submission status: Accepted

Solution code:
import itertools 
def take_solve(take):
    result=float("inf")
    for x,y,z in itertools.permutations(take):
        result=min(result,abs(x-a)+abs(y-b)+abs(z-c))
    return result

n,a,b,c=[int(x) for x in input().split()]
l=[]
for _ in range(n):
    l.append(int(input()))
from collections import defaultdict
d=defaultdict(int)
def ans(takes):
    takes=sorted(takes)
    key=str(takes)
    if key in d.keys():
        return d[key]
    m=len(takes)
    result=float("inf")
    if m==3:
        result=min(result,take_solve(takes)+10*(n-m))
    else:
        for i,j in itertools.combinations(list(range(m)),2):
            next_take=[takes[x] for x in range(m) if not x in (i,j)]
            next_take.append(takes[i]+takes[j])
            result=min(result,ans(next_take))
        for i,j,k in itertools.combinations(list(range(m)),3):
            result=min(result,take_solve((takes[i],takes[j],takes[k]))+10*(n-m))
    d[key]=result
    return result
print(ans(l))

Submission status: Accepted

Solution code:
# N本の竹、必要な3本の竹の長さはABC
N, A, B, C = map(int, input().split())
# 現在持っているそれぞれの竹の長さ（最大8本）
l = [int(input()) for i in range(N)]
INF = 10**9


def dfs(cur, a, b, c):
    # 竹の本数が全ての竹の場合だけ求める
    if cur == N:
        # min(a, b, c) > 0 は最低でも竹を作るには1本以上の竹が必要なため
        if min(a, b, c) > 0:
            # 現在（合体後）のabcそれぞれの竹の長さからABCにするの必要なコストを求める
            # 最初の再帰呼び出し時は合体をしていないので10*ABC3種分の30は引く
            return abs(a-A)+abs(b-B)+abs(c-C)-30
        else:
            return INF

    # 4のn乗の全探索をする
    ret0 = dfs(cur + 1, a, b, c)
    # 竹の追加＝合体なので+10している
    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本の竹、必要な3本の竹の長さはABC
N, A, B, C = map(int, input().split())
# 現在持っているそれぞれの竹の長さ（最大8本）
l = [int(input()) for i in range(N)]
INF = 10**9


def dfs(cur, a, b, c):
    # 全ての竹を使用している時だけ求める？
    if cur == N:
        # min(a, b, c) > 0 は最低でも竹を作るには1本以上の竹が必要なため
        if min(a, b, c) > 0:
            return abs(a-A)+abs(b-B)+abs(c-C)-30
        else:
            return INF

    ret0 = dfs(cur + 1, a, b, c)
    #print(cur + 1, a, b, c)
    ret1 = dfs(cur + 1, a + l[cur], b, c) + 10
    #print(cur + 1, a + l[cur], b, c)
    ret2 = dfs(cur + 1, a, b + l[cur], c) + 10
    #print(cur + 1, a, b + l[cur], c)
    ret3 = dfs(cur + 1, a, b, c + l[cur]) + 10
    #print(cur + 1, a, b, c + l[cur])
    return min(ret0, ret1, ret2, ret3)


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

Submission status: Accepted

Solution code:
def resolve():
    (N, A, B, C) = list(map(int, input().split(" ")))
    ls = [int(input()) for i in range(N)]
    targets = [A, B, C]

    mincost = float('inf')
    for i in range(1, 1<<N):
        for j in range(1, 1<<N):
            if i & j: continue
            for k in range(1, 1<<N):
                if i & k: continue
                if j & k: continue
                
                cost = 0
                lensum = [0, 0, 0]
                for idx, target in enumerate([i, j, k]):
                    # 状態bitに基づいて長さとcostを算出
                    for order in range(N):
                        if (target >> order) & 1:
                            cost = cost + (10 if lensum[idx] != 0 else 0) # 一本目は合成魔法を使わない
                            lensum[idx] = lensum[idx] + ls[order]
                    if lensum[idx] != targets[idx]:
                        cost = cost + abs(targets[idx] - lensum[idx])
                
                mincost = min(mincost, cost)
    print(mincost)


if '__main__' == __name__:
    resolve()

Submission status: Accepted

Solution code:
def resolve():
    (N, A, B, C) = list(map(int, input().split(" ")))
    ls = [int(input()) for i in range(N)]

    # input: i(lsのindexで、くっつけるかもしれない竹), a, b, c（作った竹の長さ）
    # output: cost
    # return: 長さa, b, cの竹を作るのに必要な最小コスト
    def get_cost(i, a, b, c):
        # 竹をくっつけたあと、微調整
        if (i == N):
            if (a == 0 or b == 0 or c == 0):
                return float('inf')
            diff = abs(A - a) + abs(B - b) + abs(C - c)
            return diff
        
        not_concat = get_cost(i+1, a, b, c) # 竹をくっつけない場合
        concat_a = get_cost(i+1, a+ls[i], b, c) + (0 if a == 0 else 10) # aに竹ls[i]をくっつける場合
        concat_b = get_cost(i+1, a, b+ls[i], c) + (0 if b == 0 else 10) # bに竹ls[i]をくっつける場合
        concat_c = get_cost(i+1, a, b, c+ls[i]) + (0 if c == 0 else 10) # cに竹ls[i]をくっつける場合

        return min([not_concat, concat_a, concat_b, concat_c])
    
    print(get_cost(0, 0, 0, 0))

if '__main__' == __name__:
    resolve()

Submission status: Accepted

Solution code:
# review
N,A,B,C = map(int,input().split())
L = [int(input()) for _ in range(N)]
 
def f(i,a,b,c):
    if i == N:
        if min(a, b, c) <= 0:
            return 10**9
        return abs(a-A)+abs(b-B)+abs(c-C)-30
    costx = f(i+1,a,b,c)
    costA = f(i+1,a+L[i],b,c)+10
    costB = f(i+1,a,b+L[i],c)+10
    costC = f(i+1,a,b,c+L[i])+10
    return min(costx,costA,costB,costC)
 
print(f(0,0,0,0))

Submission status: Accepted

Solution code:
import itertools

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

bamboo = [0,A,B,C]
bit = [0,1,2,3]
ans = int(10e10)
for seq in itertools.product(bit,repeat=N):
  data = [[] for i in range(4)]
  for j in range(N):
    data[seq[j]].append(l[j])
  else:
    for i in range(1,4):
      if len(data[i]) == 0:
        break
    else:
      tmp = 0
      for i in range(1,4):
        tmp += max(0,(len(data[i])-1))*10 + abs(sum(data[i])-bamboo[i])
      else:
        ans = min(ans,tmp)
print(ans)

Submission status: Accepted

Solution code:
n,a,b,c = map(int,input().split())
l = []
for i in range(n):
    l.append(int(input()))
ans = 10000
for i in range(4**n):
    abc = [(i%(4**(j+1)))//(4**j) for j in range(n)]
    if abc.count(1) >= 1 and abc.count(2) >= 1 and abc.count(3) >= 1:    
        d_a = a
        d_b = b
        d_c = c
        
        for j in range(n):
            if abc[j] == 1:
                d_a -= l[j]
            elif abc[j] == 2:
                d_b -= l[j]
            elif abc[j] == 3:
                d_c -= l[j]         
        ans = min(ans,abs(d_a)+abs(d_b)+abs(d_c)+10*(abc.count(1)+abc.count(2)+abc.count(3)-3))
        
print(ans)

Submission status: Accepted

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

def dfs(cur,a,b,c):
    if cur == N:
        if min(a,b,c) > 0:
            ans = abs(a-A) + abs(b-B) + abs(c-C) -30 
            #接合は各一回ずつ余分
        else:
            ans = INF
        return ans
    ret0 = dfs(cur+1,a+l[cur],b,       c)        + 10
    ret1 = dfs(cur+1,a,       b+l[cur],c)        + 10
    ret2 = dfs(cur+1,a,       b,       c+l[cur]) + 10
    ret3 = dfs(cur+1,a,       b,       c)
    #a,b,c,どこにも入れないの4通り
    #分けて接合 -> 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**6
    
def dfs(cur,a,b,c):
    if cur==N:
        if min(a,b,c)>0:
            return abs(A-a)+abs(B-b)+abs(C-c)-30
        else:
            return inf
    else:
        ret0=dfs(cur+1,a,b,c)
        ret1=dfs(cur+1,a+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))