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:
#!/usr/bin/env python3
import sys
INF = float('inf')

def solve(N: int, A: int, B: int, C: int, l: "List[int]"):
    target = [A, B, C]
    def calc(group):
        ret = 0
        for i in range(3):
            elms = group[i]
            if len(elms) < 1:
                return INF
            ret += (len(elms) - 1) * 10
            total = 0
            for e in elms:
                total += l[e]
            ret += abs(total - target[i])
        return ret

    def rec(idx, group):
        if idx >= N:
            return calc(group)
        ret = INF
        for i in range(4):
            group[i].append(idx)
            ret = min(ret, rec(idx + 1, group))
            group[i].remove(idx)
        return ret

    ret = rec(0, [[] for i in range(4)])
    print(ret)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    l = [ int(next(tokens)) for _ in range(N) ]  # type: "List[int]"
    solve(N, A, B, C, l)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

l=[]

for i in range(n):
    l.append(int(input()))

def base(X, n):
    X_dumy = X
    out = ''
    while X_dumy>0:
        out = str(X_dumy%n)+out
        X_dumy = int(X_dumy/n)
    return out
ans=10**9
for i in range(4**n):
    d=str(base(i,4)).rjust(n,'0')
    a=0
    b=0
    c=0
    ca=-10
    cb=-10
    cc=-10
    for j in range(n):
        if d[j]=="1":
            a+=l[j]
            ca+=10
        elif d[j]=="2":
            b+=l[j]
            cb+=10
        elif d[j]=="3":
            c+=l[j]
            cc+=10
    if ca<0:
        ca=0
    if cb<0:
        cb=0
    if cc<0:
        cc=0
    if a*b*c!=0:
        ans=min(ans,abs(A-a)+abs(B-b)+abs(C-c)+ca+cb+cc)
    
print(ans)

Submission status: Accepted

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

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

INF=3000

def mp(co,a,b,c):
    if co==N:
        return abs(a-A)+abs(b-B)+abs(c-C)-30 if min(a,b,c)>0 else INF

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

    return min(ret0,ret1,ret2,ret3)

print(mp(0,0,0,0))

Submission status: Accepted

Solution code:
def four(n):
    if (int(n/4)):
        return four(int(n/4))+str(n%4)
    return str(n%4)

def check(A,bit,l,k):
    num=-1
    sum=0
    for i in range(N):
        if bit[i]==k:
            num+=1
            sum+=l[i]
    return abs(A-sum)+num*10

N,A,B,C=map(int,input().split())
l=[]
MP=10**5
for i in range(N):
    li=int(input())
    l.append(li)
for i in range(4**N):
    bit=four(i).zfill(N)
    if not("1" in bit):
        continue
    if not("2" in bit):
        continue
    if not("3" in bit):
        continue
    mp=check(A,bit,l,"1")+check(B,bit,l,"2")+check(C,bit,l,"3")
    if mp<=MP:
        MP=mp
print(MP)

Submission status: Accepted

Solution code:
import numpy as np
N, A, B, C = list(map(int, input().split()))
l_li = []
for i in range(N):
    l_li.append(int(input()))
INF = 10 ** 9
def dfs(n, a, b, c):
  if n == N:
    if min(a, b, c) == 0:
      return INF
    else:
      return abs(a-A) + abs(b-B) + abs(c-C) -30
  res0 = dfs(n + 1, a, b, c)
  res1 = dfs(n + 1, a + l_li[n], b, c) + 10
  res2 = dfs(n + 1, a, b + l_li[n], c) + 10
  res3 = dfs(n + 1, a, b, c + l_li[n]) + 10
  return min(res0, res1, res2, res3)

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)

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



#長さmの竹を作るのに必要なMPの表を作りたいが?
#長さ10以下の竹を繋げるくらいなら長くしたほうがいい





#距離
#まず, 絶対値の比較を行いたい
#そして, 


#操作の交換法則は成立する
#


def cal_cost(L_use):
	a=0
	b=0
	c=0
	na=0
	nb=0
	nc=0
	for i in range(len(L_use)):
		if(L_use[i]==0):
			0
		if(L_use[i]==1):
			a+=L[i]
			na+=1
		if(L_use[i]==2):
			b+=L[i]
			nb+=1
		if(L_use[i]==3):
			c+=L[i]
			nc+=1
	if(na==0 or nb==0 or nc==0):
		return -1
	return abs(a-A)+abs(b-B)+abs(c-C)+10*(na+nb+nc-3)
	

L_use=[]
for i in range(4**N):
	k=i
	tmp=[]
	for j in range(N):
		tmp.append(k%4)
		k//=4
	L_use.append(tmp)
costs=[]
for u in L_use:
	c=cal_cost(u)
	if(c!=-1):
		costs.append(c)
print(min(costs))
#print(costs)
#print(L_use)	




#Aの材料or Bの材料 or Cの材料 or Dの材料





#nはそんなに大きくないので, 自由にできそう

Submission status: Accepted

Solution code:
from sys import stdin

# 無限大の定義
INF = 10 ** 9

N, A, B, C = [int(x) for x in stdin.readline().rstrip().split()]
#N, *ABC = [int(x) for x in stdin.readline().rstrip().split()]

l_list = [int(stdin.readline().rstrip()) for _ in range(N)]


# DFS（深さ優先探索で解く）
# cur: カーソル
def dfs(cur, a, b, c):
    # カーソルが丈listの最後まで来たら
    if cur == N:
        # 「長さ Aの竹の材料」「長さ B の竹の材料」「長さ C の竹の材料」がそれぞれ一本以上必要で、
        # これを満たさない竹の扱い方は棄却
        if min(a, b, c) > 0:
            # 合成してから竹を伸ばしたり縮めるコストと、竹を伸ばしたり縮めたりして合成するコストは同じ
            # （足し算は順序を交換しても結果は変わらないから）
            # -30は、a, b, cについて材料選択の1回目にも合成とみなされていることから、その分を引いている
            # abs()は差の絶対値を求める標準関数
            # abs(a - A)は、今あるaに対して目標のAに対して伸ばすor縮めるコストを表している
            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_list[cur], b, c) + 10 # Aの材料にする
    ret2 = dfs(cur+1, a, b+l_list[cur], c) + 10 # Bの材料にする
    ret3 = dfs(cur+1, a, b, c+l_list[cur]) + 10 # Cの材料にする

    return min(ret0, ret1, ret2, ret3)

# cur=0, どの竹の材料も無い状態から
print(dfs(0, 0, 0, 0))

Submission status: Accepted

Solution code:
import itertools
INF = 1000000007
n, a, b, c = map(int, input().split())
B = [a, b, c]
take = [int(input()) for i in range(n)]
sh = [i for i in itertools.product(range(4), repeat=n)]
res = INF
for C in sh:
    if 0 not in C or 1 not in C or 2 not in C:
        continue
    ex = [0] * 3
    ifres = 0
    for index, x in enumerate(C):
        if x != 3:
            if ex[x] != 0:
                ifres += 10
            ex[x] += take[index]
    for i in range(3):
        ifres += abs(B[i]-ex[i])
    if ifres < res:
        res = ifres
print(res)

Submission status: Accepted

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


def dfs(cur, a, b, c):
    if cur == N:
        # INFが返ってくるのは，A，B，Cいずれかの材料が1本も存在しない時（棄却する）
        ret = abs(a - A) + abs(b - B) + abs(c - C) if min(a, b, c) > 0 else INF
        return abs(a - A) + abs(b - B) + abs(c - C) if min(a, b, c) > 0 else INF
    # 合成するたびに10必要になる
    ret1 = dfs(cur + 1, a + length[cur], b, c) + (10 if a else 0)
    ret2 = dfs(cur + 1, a, b + length[cur], c) + (10 if b else 0)
    ret3 = dfs(cur + 1, a, b, c + length[cur]) + (10 if c else 0)
    # 使わない
    ret0 = dfs(cur + 1, a, b, c)
    return min(ret0, ret1, ret2, ret3)


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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000)
N,A,B,C = [int(x) for x in input().split()]
l = [int(input()) for _ in range(N)]

def calc(li):
    bam = [0]*4
    scr = [0]*4
    for index,i in enumerate(li):
        if(i == 0): continue
        scr[i] += 10 if bam[i]!=0 else 0
        bam[i] += l[index]
    scr[1] += abs(bam[1]-A)
    scr[2] += abs(bam[2]-B)
    scr[3] += abs(bam[3]-C)
    global ans
    ans = min(ans,sum(scr))

def dfs(num,li):
    if(num == N):
        exist = [0]*4
        mul = 1
        for i in li:
            exist[i]+=1
        for i in exist[1:]:
            mul *= i
        if(mul == 0): return 0        
        calc(li)
    else:
        for i in range(4):
            dfs(num+1,li+[i])


li1=[]
ans = 10**9
dfs(0,li1)
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()))


INF = 10 ** 5


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

    ret0 = dfs(depth+1, a, b, c)
    ret1 = dfs(depth+1, a+l[depth], b, c) + 10
    ret2 = dfs(depth+1, a, b+l[depth], c) + 10
    ret3 = dfs(depth+1, a, b, c+l[depth]) + 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())
leng=[int(input()) for i in range(N)]


def dfs(cur,a,b,c,cost):
    if cur == N:
        if min(a,b,c)>0 :
            return abs(A-a)+abs(B-b)+abs(C-c)+cost
        else: return 10**9
    
    return0=dfs(cur+1,a,b,c,cost)
    return1=dfs(cur+1,a+leng[cur],b,c,cost+10)
    return2=dfs(cur+1,a,b+leng[cur],c,cost+10)
    return3=dfs(cur+1,a,b,c+leng[cur],cost+10)
    
    return min(return0,return1,return2,return3)


print(dfs(0,0,0,0,0)-30)

Submission status: Accepted

Solution code:
import numpy as np

def main():
	n,a,b,c=map(int,input().split())
	l=[]
	for i in range(n):
		l.append(int(input()))
	
	key=[[0],[1],[2],[3]]
	key_4=key[:]
	for i in range(n-1):
		temp=[]
		for elem1 in key:
			for elem2 in key_4:
				temp.append(elem1+elem2)
		key=temp[:]

	res=10**9
	for elem in key:
		res=min(res,judge(elem,l,a,b,c))
	print(res)
	
def judge(key,l,a,b,c):
	num=[0,0,0,0]
	array=[0,0,0,0]
	for i in range(len(key)):
		array[key[i]]+=l[i]
		num[key[i]]+=1
	if(num[0]==0 or num[1]==0 or num[2]==0):
		return 10**9
	result=0
	result=abs(array[0]-a)+abs(array[1]-b)+abs(array[2]-c)
	result+=(num[0]+num[1]+num[2]-3)*10

	return result

def inputList():
	a=list(map(int,input().split()))
	return a

def multisort(li,index):
	return sorted(li,key=lambda x: x[index])

if(__name__=='__main__'):
	main()

Submission status: Accepted

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

def dfs(x, a, b, c):
  if x == N:
    if min(a, b, c) > 0:
      return abs(a-A)+abs(b-B)+abs(c-C)-30
    else:
      return float("inf")
  
  ret0 = dfs(x+1, a, b, c)
  ret1 = dfs(x+1, a+l[x], b, c)+10
  ret2 = dfs(x+1, a, b+l[x], c)+10
  ret3 = dfs(x+1, a, b, c+l[x])+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())
li = [int(input()) for _ in range(n)]

def searchans(count,a,b,c):
    if count == n:
        if not 0 in [a,b,c]:
            return abs(A-a) + abs(B-b) + abs(C-c) - 30
        else:
            return 10**100
    else:
        ret0 = searchans(count+1,a,b,c)
        ret1 = searchans(count+1,a+li[count],b,c) + 10
        ret2 = searchans(count+1,a,b+li[count],c) + 10
        ret3 = searchans(count+1,a,b,c+li[count]) + 10
        return min([ret0,ret1,ret2,ret3])

print(searchans(0,0,0,0))

Submission status: Accepted

Solution code:
try:
    from math import inf
except:
    inf = float("inf")
from collections import deque

N, A, B, C = map(int, input().split())
ls = [0]
for _ in range(N):
    ls.append(int(input()))
ls.sort()

q = deque()
q.append((0, -30, 0, 0, 0))
minmp = inf
while len(q):
    n, mp, a, b, c = q.pop()
    if n == N:
        if min(a, b, c) == 0:
            continue
        minmp = min(minmp, mp + abs(a - A) + abs(b - B) + abs(c - C))
    else:
        q.append((n + 1, mp, a, b, c))
        q.append((n + 1, mp + 10, a + ls[n + 1], b, c))
        q.append((n + 1, mp + 10, a, b + ls[n + 1], c))
        q.append((n + 1, mp + 10, a, b, c + ls[n + 1]))

print(minmp)

Submission status: Accepted

Solution code:
import itertools

N,A,B,C = map(int,input().split())
comb = [] #0:使用しない,1:竹Aの材料,2:竹Bの材料,3:竹Cの材料
L = []
for i in range(N):
  l = int(input())
  L.append(l)
  comb.append([0,1,2,3])

All_comb =  list(itertools.product(*comb))
min_MP = float('inf')
for i in range(len(All_comb)):
  tmp = All_comb[i]
  Non_material = []
  A_material = []
  B_material = []
  C_material = []
  for j in range(len(tmp)):
    if(tmp[j] == 0): Non_material.append(L[j])
    elif(tmp[j] == 1): A_material.append(L[j])
    elif(tmp[j] == 2): B_material.append(L[j])
    elif(tmp[j] == 3): C_material.append(L[j])
    a,b,c = len(A_material),len(B_material),len(C_material)
    if((a>=1)and(b>=1)and(c>=1)):
     sum_A,sum_B,sum_C = sum(A_material),sum(B_material),sum(C_material)
     MP = abs(A-sum_A)+abs(B-sum_B)+abs(C-sum_C) +10*(a+b+c-3)
     min_MP = min(MP,min_MP)

print(min_MP)

Submission status: Accepted

Solution code:
import numpy as np

N,A,B,C = map(int,input().split())
target = [A,B,C]
l = []
#ans = math.inf

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


def calc2(v):
    res = 0
    for i in range(3):
        if len(v[i])==0:
            return np.inf
        res += 10*(len(v[i])-1) + abs(sum(v[i]) - target[i])
    return res

v=[[],[],[],[]]
def dfs2(depth=0):
    #global ans
    if depth == N:
        return calc2(v)
    #else:
    ans = np.inf
    for i in range(4):
        #next_v = v.copy()
        #print(i, v, depth, l)
        v[i].append(l[depth])
        ans = min(ans,dfs2(depth+1))
        del v[i][-1]

    return ans

print(dfs2())

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!


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

take = []
INF = 10 ** 18

for _ in range(N) : 
    tmp = int(input())
    take.append(tmp)
    
def dfs(i, a, b, c) : 
    if i == N : return abs(A-a) + abs(B-b) + abs(C-c) -30 if min(a, b, c) > 0 else INF
    
    ret0 = dfs(i+1, a, b, c)
    ret1 = dfs(i+1, a + take[i], b, c) + 10
    ret2 = dfs(i+1, a, b + take[i], c) + 10
    ret3 = dfs(i+1, a, b, c + take[i]) + 10
        
    return(min(ret0, ret1, ret2, ret3))
        
print(dfs(0, 0, 0, 0))

Submission status: Accepted

Solution code:
def int_raw():
    return int(raw_input())
 
def words_raw():
    return raw_input().split()
 
def ints_raw():
    return map(int, words_raw())

N, A, B, C = ints_raw()
l = [int_raw() for _ in range(N)]

INF = 1e10
def cost(idx, a, b, c):
	if idx == N:
		if min(a,b,c)  == 0:
			return INF
		else:
			return abs(a - A) + abs(b - B) + abs(c - C) - 30
	val1 = cost(idx + 1, a, b, c)
	val2 = cost(idx + 1, a + l[idx], b, c) + 10
	val3 = cost(idx + 1, a, b + l[idx], c) + 10
	val4 = cost(idx + 1, a, b, c + l[idx]) + 10
	return min(val1, val2, val3, val4)

print cost(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+7

def dfs(count,a,b,c):
	if count == N:
		if min(a,b,c) > 0:
			return abs(a-A)+abs(b-B)+abs(c-C)-30
		else:
			return INF
	non = dfs(count+1,a,b,c)
	useA = dfs(count+1,a+l[count],b,c)+10
	useB = dfs(count+1,a,b+l[count],c)+10
	useC = dfs(count+1,a,b,c+l[count])+10
	return min(non,useA,useB,useC)

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

Submission status: Accepted

Solution code:
import itertools
N,A,B,C = map(int,input().split())
L = []
Comb = [] #0:使わない, 1:竹Aの材料 ,2:竹Bの材料 ,3:竹Cの材料

for i in range(N):
  l = int(input())
  L.append(l)
  Comb.append([0,1,2,3])
all_Comb = list(itertools.product(*Comb))

min_MP = float('inf')
for i in range(len(all_Comb)):
 tmp = list(all_Comb[i])
 Non_material = []
 A_material = []
 B_material = []
 C_material = []
 for j in range(N):
   if(tmp[j] == 0): Non_material.append(L[j])
   elif(tmp[j] == 1):  A_material.append(L[j])
   elif(tmp[j] == 2):  B_material.append(L[j])
   elif(tmp[j] == 3):  C_material.append(L[j])
   a,b,c = len(A_material),len(B_material),len(C_material)
   if((a>=1)and(b>=1)and(c>=1)):
    sum_A,sum_B,sum_C = sum(A_material),sum(B_material),sum(C_material)
    MP = abs(A-sum_A) + abs(B-sum_B) + abs(C-sum_C) + 10*(a+b+c-3)
    min_MP = min(MP,min_MP)
 
print(min_MP)

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 cost(index, a,b,c):
    if index == N:
        return (abs(a-A) + abs(b-B) + abs(c-C) - 30) if min(a,b,c) > 0 else INF
    ret0 = cost(index+1, a,b,c)
    ret1 = cost(index+1, a+l[index],b,c) + 10
    ret2 = cost(index+1, a,b+l[index],c) + 10
    ret3 = cost(index+1, a,b,c+l[index]) + 10
    return min(ret0, ret1, ret2, ret3)

print(cost(0,0,0,0))

Submission status: Accepted

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

def base10to(n, b):
    if (int(n/b)):
        return base10to(int(n/b), b) + str(n%b)
    return str(n%b)

maxL = 4 ** N - 1
maxL = base10to(maxL,4)
ans = []
for i in range(1, 4 ** N + 1):
    n = 4 ** N - i
    n = base10to(n,4)
    if len(maxL) - len(n) > 0:
        tmp = ['0'] * (len(maxL) - len(n))
        tmp.extend(list(n))
    else:
        tmp = list(n)
    AA, BB, CC = A, B, C
    aaa = set(tmp)
    anss = 0
    if '1' not in aaa or '2' not in aaa or '3' not in aaa:
        continue
    for j, num in enumerate(tmp):
        if num == '1':
            if AA != A:
                anss += 10
            AA -= L[j]
        elif num == '2':
            if BB != B:
                anss += 10
            BB -= L[j]
        elif num == '3':
            if CC != C:
                anss += 10
            CC -= L[j]
    ans.append(anss + abs(AA) + abs(BB) + abs(CC))
print(min(ans))

Submission status: Accepted

Solution code:
N,A,B,C = map(int, input().split())
ll = [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+ll[cur],b,c)+10 # Aに使う場合
    ret2 = dfs(cur+1, a,b+ll[cur],c)+10 # Bに使う場合
    ret3 = dfs(cur+1, a,b,c+ll[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 i in range(n)]
def nsin(X,y):
    if(int(X/y)):
        return nsin(int(X/y),y)+str(X%y)
    return str(X%y)

cost=10000
for i in range(3**n):
    g=list(nsin(i,3).zfill(n))
    if len(set(g))!=3:
        continue
    la=[]
    lb=[]
    lc=[]
    for j in range(n):        
        if g[j]=="0":
            la.append(l[j])
        elif g[j]=="1":
            lb.append(l[j])
        elif g[j]=="2":
            lc.append(l[j])
    costa=10000
    costb=10000
    costc=10000
    for j in range(1,2**len(la)):
        ga=list(nsin(j,2).zfill(len(la)))
        A=0
        cont=-1
        for k in range(len(la)):
            if ga[k]=="1":
                A+=la[k]
                cont+=1
        tmp=cont*10+abs(A-a)
        if tmp<costa:
            costa=tmp
    for j in range(1,2**len(lb)):
        gb=list(nsin(j,2).zfill(len(lb)))
        B=0
        cont=-1
        for k in range(len(lb)):
            if gb[k]=="1":
                B+=lb[k]
                cont+=1
        tmp=cont*10+abs(B-b)
        if tmp<costb:
            costb=tmp
    for j in range(1,2**len(lc)):
        gc=list(nsin(j,2).zfill(len(lc)))
        C=0
        cont=-1
        for k in range(len(lc)):
            if gc[k]=="1":
                C+=lc[k]
                cont+=1
        tmp=cont*10+abs(C-c)
        if tmp<costc:
            costc=tmp
    if cost>(costa+costb+costc):
        cost=costa+costb+costc
print(cost)

Submission status: Accepted

Solution code:
N, A, B, C = [int(i) for i in input().split()]
# Nが与えられた竹, A, B, Cが作り出したい竹
L = [int(input()) for i in range(N)]


def dfs(idx, a, b, c):

    if idx == N:
        if a == 0 or b == 0 or c == 0:
            return 1e9  # 10の9乗

        return abs(A - a) + abs(B - b) + abs(C - c)

    x = dfs(idx + 1, a, b, c)
    y = dfs(idx + 1, a + L[idx], b, c) + 10*(a != 0)
    z = dfs(idx + 1, a, b + L[idx], c) + 10*(b != 0)
    w = dfs(idx + 1, a, b, c + L[idx]) + 10*(c != 0)
    return min(x, y, z, w)


ans = dfs(0, 0, 0, 0)
print(ans)

Submission status: Accepted

Solution code:
# Synthetic Kadomatsu
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())
takelist = [a,b,c]

li = [int(input()) for _ in range(n)]
li2 = [0 for _ in range(n)]
min = 10**100

def movelist(li,n):
    for i in range(n):
        if li[i] != 3:
            li[i] += 1
            break
        else:
            li[i] = 0

for i in range(4**n):
    li3 = [0,0,0,0]
    sum = 0
    for j in range(n):
        if li3[li2[j]] != 0 and li2[j] != 3:
            sum += 10
        li3[li2[j]] += li[j]
    if li3[0] != 0 and li3[1] != 0 and li3[2] != 0:
        for k in range(3):
            sum += abs(li3[k] - takelist[k])
        if sum < min:
            min = sum
    movelist(li2,n)

print(min)

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:
count = {}
count["A"] = 0
count["B"] = 0
count["C"] = 0
a = b = c = 0
N,A,B,C = map(int,input().split())
L = []
for _ in range(N):
    L.append(int(input()))
# print(a,b,c)
def score():
    joinNum = 0
    joinNum += max(0,count["A"]-1)
    joinNum += max(0,count["B"]-1)
    joinNum += max(0,count["C"]-1)
    scoreValue = 10 * joinNum + abs(A-a) + abs(B-b) + abs(C-c)
    return(scoreValue)
answer = 1000*3
for i in range(pow(4,N)):
    count["A"] = 0
    count["B"] = 0
    count["C"] = 0
    a = b = c = 0
    digits=[]
    for j in range(N):
        digit = (i%pow(4,j+1))//pow(4,j)
        digits.append(digit)
        if digit == 0:
            a += L[j]
            count["A"] += 1
        elif digit == 1:
            b += L[j]
            count["B"] += 1
        else:
            if digit == 2:
                c += L[j]
                count["C"] += 1
    if count["A"]*count["B"]*count["C"] == 0: continue
    candidate = score()
    if candidate < answer:
        # print("".join(map(str,digits)),a,b,c,abs(A-a),abs(B-b),abs(C-c),candidate)
        answer = candidate
print(answer)

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

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

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 bamboo(count,a,b,c):
  if count==N:
    if min(a,b,c)>0:
      return abs(a-A)+abs(b-B)+abs(c-C)-30
    else:
      return INF
  rot0=bamboo(count+1,a,b,c)
  rot1=bamboo(count+1,a+l[count],b,c)+10
  rot2=bamboo(count+1,a,b+l[count],c)+10
  rot3=bamboo(count+1,a,b,c+l[count])+10
  return min(rot0,rot1,rot2,rot3)
print(bamboo(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(idx, a, b, c):
    if idx == N:
        if a == 0 or b == 0 or c == 0:
            return 10**9
        return abs(A - a) + abs(B - b) + abs(C - c)

    x = dfs(idx + 1, a, b, c)
    y = dfs(idx + 1, a + L[idx], b, c) + 10*(a != 0)
    z = dfs(idx + 1, a, b + L[idx], c) + 10*(b != 0)
    w = dfs(idx + 1, a, b, c + L[idx]) + 10*(c != 0)
    #print(x, y, z, w)
    #print('here!')
    return min(x, y, z, w)

ans = dfs(0, 0, 0, 0)
print(ans)

Submission status: Accepted

Solution code:
import itertools

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

use_flag = ['0', '1', '2', '-1']
use_list = list(itertools.product(use_flag, repeat=len(length_list)))

costs = []

for ls in use_list:
    if len(set(ls)&{'0','1', '2'}) == 3:
        #print(ls)
        A_diff = 0
        B_diff = 0
        C_diff = 0
        for length, use_for in zip(length_list, list(ls)):
            #print(length, use_for)
            if use_for == '0':
                A_diff += length
                #print(A_diff)
            elif use_for == '1':
                B_diff += length
                #print(B_diff)
            elif use_for == '2':
                C_diff += length
                #print(C_diff)
            #print('-----')
        costs.append(abs(A-A_diff) + abs(B-B_diff) + abs(C-C_diff) + 10*max(ls.count('0') - 1, 0) + 10*max(ls.count('1') - 1, 0) + 10*max(ls.count('2') - 1, 0))
print(min(costs))
#print(len(costs))

Submission status: Accepted

Solution code:
N,A,B,C = map(int,input().strip().split())
ls = [int(input()) for i in range(0,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 + 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 i in range(N)]
INF=10**9


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

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

Submission status: Accepted

Solution code:
def dfs(count, n_1, n_2, n_3, z):
    if (count == n):
        return abs(a-n_1) + abs(b-n_2) + abs(c-n_3) + z * 10 if (n_1*n_2*n_3 != 0) else 10**9
    r0 = dfs(count+1, n_1, n_2, n_3, z)
    r1 = dfs(count+1, n_1+d[count], n_2, n_3, z+1)
    r2 = dfs(count+1, n_1, n_2+d[count], n_3, z+1)
    r3 = dfs(count+1, n_1, n_2, n_3+d[count], z+1)
    return min(r0, r1, r2, r3)
n, a, b, c = map(int, input().split())
d = []
for i in range(n):
    d.append(int(input()))


print(dfs(0,0,0,0, -3))

Submission status: Accepted

Solution code:
N,A,B,C = map(int,input().split())
l = [int(input()) for _ in range(N)]
ans = float('inf')
def dfs(d=0,a=0,b=0,c=0,mp=0):
    if d == N:
        mp = mp + abs(A-a) + abs(B-b) + abs(C-c) - 30
        global ans
        if a*b*c > 0 and mp < ans:
            ans = mp
        return
    dfs(d+1,a,b,c,mp)
    dfs(d+1,a+l[d],b,c,mp+10)
    dfs(d+1,a,b+l[d],c,mp+10)
    dfs(d+1,a,b,c+l[d],mp+10)

dfs()
print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

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

list = [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 10000
    ret0 = dfs(cur+1, a, b, c)
    ret1 = dfs(cur+1, a+list[cur], b, c) +10
    ret2 = dfs(cur+1, a, b+list[cur], c) +10
    ret3 = dfs(cur+1, a, b, c+list[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, q, w, e):
    if cur == n:
        return abs(a-q)+abs(b-w)+abs(c-e)-30 if min(q, w, e) != 0 else 10**18
    return min(
        dfs(cur+1, q+l[cur], w, e)+10,
        dfs(cur+1, q, w+l[cur], e)+10,
        dfs(cur+1, q, w, e+l[cur])+10,
        dfs(cur+1, q, w, e),
    )
print(dfs(0, 0, 0, 0))

Submission status: Accepted

Solution code:
def Base_10_to_n(X, n):
    if (int(X/n)):
        return Base_10_to_n(int(X/n), n) + str(X % n)
    return str(X % n)


N, A, B, C = map(int, input().split(" "))
bamboos = [int(input()) for _ in range(N)]
ans = float("inf")
for i in range(4**N):
    now = Base_10_to_n(i, 4).zfill(N)
    length = [0, 0, 0, 0]
    cost = 0
    for j, c in enumerate(now):
        for k, num in enumerate("0123"):
            if c == num:
                length[k] += bamboos[j]
                break
    if length[0]*length[1]*length[2] == 0:
        continue
    cost += 10 * (now.count('0')-1)
    cost += 10 * (now.count('1')-1)
    cost += 10 * (now.count('2')-1)
    cost += abs(A-length[0])
    cost += abs(B-length[1])
    cost += abs(C-length[2])
    ans = min(cost, ans)
print(ans)