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: Wrong Answer

Solution code:
# ABC119C - Synthetic Kadomatsu
def dfs() -> int:
    stack = [(0, 0, 0, 0, 0)]
    cand = set()
    while stack:
        cur, x, y, z, cnt = stack.pop()
        if cur == N:
            if min(x, y, z):
                cand.add(abs(x - A) + abs(y - B) + abs(z - C) + cnt - 30)
            continue
        stack.append((cur + 1, x, y, z, cnt + 10))
        stack.append((cur + 1, x + L[cur], y, z, cnt + 10))
        stack.append((cur + 1, x, y + L[cur], z, cnt + 10))
        stack.append((cur + 1, x, y, z + L[cur], cnt + 10))
    return min(cand)


def main():
    global N, A, B, C, L
    N, A, B, C, *L = map(int, open(0).read().split())
    ans = dfs()
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import itertools
N,A,B,C=map(int,input().split())
l = [int(input()) for _ in range(N)]
#A,B,Cに近づくように合成する
#N-3本を3個に分類する→最大3**5通り
ans = 10**9
lis = list(itertools.combinations_with_replacement([0,1,2],8))
for i in lis:
    if len(set(i))<2:
        continue
    else:
        a = 0
        b = 0
        c = 0
        for j in range(N):
            if i[j] == 0:
                a += l[j]
            elif i[j] == 1:
                b += l[j]
            else:
                c += l[j]
            tmp = abs(A-a)+abs(B-b)+abs(C-c)
            ans = min(ans,tmp)
print(ans+(N-3)*10)

Submission status: Wrong Answer

Solution code:
import sys
import queue

#+++++


def aaa(ll,a,b,c):
	ret=a+b+c
	for i,v1 in enumerate(ll):
		if v1==0:
			continue
		t1=abs(a-v1)
		if ret < t1:
			continue
		for j,v2 in enumerate(ll):
			if v2==0:
				continue
			if i==j:
				continue
			t2=t1 + abs(b-v2)
			if ret < t2:
				continue
			for k,v3 in enumerate(ll):
				if v3==0:
					continue
				if i==k or j==k:
					continue
				t3 = t2 + abs(c-v3)
				ret=min(ret, t3)
	return ret		

def mk_str(ll):
	ll.sort()
	return '_'.join([str(v) for v in ll])


def main():
	n , a, b, c = map(int, input().split())
	est=lambda ll:aaa(ll,a,b,c)
	
	bb=[]
	for i in range(n):
		bb.append(int(input()))
	
	cl=set()
	ol=queue.PriorityQueue()
	

	
	st=bb
	ee=est(st)
	cc=0
	cl.add(mk_str(bb))
	ol.put((ee+cc, (cc, bb)))	
	while True:
		if ee == 0:
			return cc
		
		#to goal no join
		rr=cc+ee
		ol.put((rr, (rr, [a,b,c])))
		
		
		
		#join 1
		if len(st) > 3:
			cc+=10
			for i, v in enumerate(st):
				kk=st[:]
				m=kk.pop(i)
				for j, _ in enumerate(kk):
					kkk=kk[:]
					kkk[j]+=m
					stk=mk_str(kkk)
					if stk not in cl:
						cl.add(stk)
						ol.put((cc+est(kkk), (cc, kkk)))
		v,(cc, st) = ol.get()
		ee = est(st)
				
	print(ans)
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)

if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Wrong Answer

Solution code:
import sys
import queue

#+++++


def aaa(ll,a,b,c):
	ret=a+b+c
	for i,v1 in enumerate(ll):
		if v1==0:
			continue
		t1=abs(a-v1)
		if ret < t1:
			continue
		for j,v2 in enumerate(ll):
			if v2==0:
				continue
			if i==j:
				continue
			t2=t1 + abs(b-v2)
			if ret < t2:
				continue
			for k,v3 in enumerate(ll):
				if v3==0:
					continue
				if i==k or j==k:
					continue
				t3 = t2 + abs(c-v3)
				ret=min(ret, t3)
	return ret		

def mk_str(ll):
	ll.sort()
	return '_'.join([str(v) for v in ll])


def main():
	n , a, b, c = map(int, input().split())
	est=lambda ll:aaa(ll,a,b,c)
	
	bb=[]
	for i in range(n):
		bb.append(int(input()))
	
	cl=set()
	ol=queue.PriorityQueue()
	

	
	st=bb
	ee=est(st)
	cc=0
	cl.add(mk_str(bb))
	ol.put((ee+cc, (cc, bb)))	
	while True:
		if ee == 0:
			return cc
		
		#to goal no join
		rr=cc+ee
		ol.put((rr, (rr, [a,b,c])))
		
		#join 1
		cc+=10
		for i, v in enumerate(st):
			kk=st[:]
			m=kk.pop(i)
			for j, _ in enumerate(kk):
				kkk=kk[:]
				kkk[j]+=m
				stk=mk_str(kkk)
				if stk not in cl:
					cl.add(stk)
					ol.put((cc+est(kkk), (cc, kkk)))
		v,(cc, st) = ol.get()
		ee = est(st)
				
	
	print(ans)
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)

if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Wrong Answer

Solution code:
import sys

#+++++


def aaa(ll,a,b,c):
	ret=a+b+c
	for i,v1 in enumerate(ll):
		t1=abs(a-v1)
		if ret < t1:
			continue
		for j,v2 in enumerate(ll):
			if i==j:
				continue
			t2=t1 + abs(b-v2)
			if ret < t2:
				continue
			for k,v3 in enumerate(ll):
				if i==k or j==k:
					continue
				t3 = t2 + abs(c-v3)
				ret=min(ret, t3)
	return ret		
		
def main():
	n , a, b, c = map(int, input().split())
	bb=[]
	for i in range(n):
		bb.append(int(input()))
	ans=a+b+c
	for i in range(4**n-1):
		la=[]
		lb=[]
		lc=[]
		l=[]
		for j in range(n):
			sd=(i%(4 ** (j+1)))//(4**j)
			kk=bb[j]
			pp=0
			if sd == 0:
				la.append(kk)
			elif sd==1:
				lb.append(kk)
			elif sd==2:
				lc.append(kk)
			else:
				l.append(kk)
		pp=max(0,len(la)-1)+max(len(lb)-1,0)+max(0,len(lc)-1)
		l=l+[sum(la),sum(lb),sum(lc)]
		#print(l)
		ans=min(ans,aaa(l,a,b,c)+pp*10)
				
	
	print(ans)
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)

if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Wrong Answer

Solution code:
import sys
import collections

sys.setrecursionlimit(100000)

n, a, b, c = map(int, input().split())
l = []

ans = 999999999999

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


def calc_mp(ml):
    res = [0] * 4
    for i in range(n):
        res[ml[i]] += l[i]

    cc = collections.Counter(ml)
    mp = (max(cc[0]-1, 0) + max(cc[1]-1, 0) + max(cc[2]-1, 0)) * 10
    return mp + abs(res[0] - a) + abs(res[1] - b) + abs(res[2] - c)


def calc(ml, k):
    if k == n:
        return calc_mp(ml)
    return min(calc(ml + [0], k + 1), calc(ml + [1], k + 1), calc(ml + [2], k + 1), calc(ml + [3], k + 1))


print(calc([], 0))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations
import sys
import string
from bisect import bisect_left


INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LIM(): return list(map(lambda x:int(x) - 1, sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def LIRM(n): return [LIM() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
mod = 1000000007


n, a, b, c = LI()
L = IR(n)


def recur(ai, bi, ci, i):
    if i == n:
        return abs(a - ai) + abs(b -bi) + abs(c - ci) - 30 if a > 0 and b > 0 and c > 0 else INF
    l1 = recur(ai + L[i], bi, ci, i+1) + 10
    l2 = recur(ai, bi + L[i], ci, i+1) + 10
    l3 = recur(ai, bi, ci + L[i], i+1) + 10
    l4 = recur(ai, bi, ci, i+1)
    return min(l1, l2, l3, l4)



print(recur(0, 0, 0, 0))

Submission status: Wrong Answer

Solution code:
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 10*9+7
    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)


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

Submission status: Wrong Answer

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

# 0, 1, 2, 3(使わない) で前通り試す
from itertools import product

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

print(answer)

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline

def func(dst, src, mp):
    if len(dst) == 0: # dst が空になったら終了
        return mp
    for s in src: # 長さが一致していたら何もせず除外
        if s in dst:
            src.remove(s)
            dst.remove(s)
#            print("removed", s, src, dst, mp)
    for i in dst: # 持っているどの竹よりも短い dst には、短縮魔法を使うしかない
        if i < min(src):
            tmp = min(src)
            mp += min(src) - i
            src.remove(tmp)
            dst.remove(i)
#            print("shorten", tmp, src, dst, mp)
    # 持っている竹のうち、mp 消費が10未満で処理できるものがあれば、その中で最小のものを延長
    mi = 10
    dd = None
    ss = None
    for s in src:
        for d in dst:
            tmp = mi
            mi = min(mi, abs(d-s))
            if mi != tmp:
                dd = d
                ss = s
    if mi < 10:
        mp += abs(dd - ss)
        src.remove(ss)
        dst.remove(dd)
#        print("extend", ss, src, dst, mp)
    # 結合した時に、目標に 10 以上近くなる 2 本を結合
    s1 = s2 = None
    if len(src) > len(dst):
        mi = 1000
        for s in src:
            for d in dst:
                mi = min(mi, abs(s-d))
        for i in range(len(src)):
            for j in range(i+1,len(src)):
                for d in dst:
                    tmp = mi
                    mi = min(mi, 10 + abs(d - (src[i] + src[j])))
                    if mi != tmp:
                        s1 = src[i]
                        s2 = src[j]
        if s1 != None and s2 != None:
            src.remove(s1)
            src.remove(s2)
            mp += 10
#            print("synthesize", s1, s2, src, dst,mp)
            src.append(s1+s2)
    if len(src) <= len(dst) or s1 == None:
        # 結合しても意味が無い場合、最も差が小さいものを変更
        mi = 1000
        ss = None
        dd = None
        for s in src:
            for d in dst:
                tmp = mi
                mi = min(mi, abs(s-d))
                if tmp != mi:
                    ss = s
                    dd = d
        if ss != None and dd != None:
            mp += abs(ss-dd)
            src.remove(ss)
            dst.remove(dd)
#            print("removed", ss, src, dst, mp)
    return func(dst, src, mp)

def main():
    N,A,B,C = map(int, input().split())
    T = [A,B,C]
    L = []
    T.sort()
    L.sort()
    for _ in range(N):
        L.append(int(input()))
    print(func(T,L,0))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline

def func(dst, src, mp):
    if len(dst) == 0: # dst が空になったら終了
        return mp
    for s in src: # 長さが一致していたら何もせず除外
        if s in dst:
            src.remove(s)
            dst.remove(s)
#            print("removed", s, src, dst, mp)
    for i in dst: # 持っているどの竹よりも短い dst には、短縮魔法を使うしかない
        if i < min(src):
            tmp = min(src)
            mp += min(src) - i
            src.remove(tmp)
            dst.remove(i)
#            print("shorten", tmp, src, dst, mp)
    # 持っている竹のうち、mp 消費が10未満で処理できるものがあれば、その中で最小のものを延長
    mi = 10
    dd = None
    ss = None
    for s in src:
        for d in dst:
            tmp = mi
            mi = min(mi, abs(d-s))
            if mi != tmp:
                dd = d
                ss = s
    if mi < 10:
        mp += dd - ss
        src.remove(ss)
        dst.remove(dd)
#        print("extend", ss, src, dst, mp)
    # 結合した時に、目標に 10 以上近くなる 2 本を結合
    s1 = s2 = None
    if len(src) > len(dst):
        mi = 1000
        for s in src:
            for d in dst:
                mi = min(mi, abs(s-d))
        for i in range(len(src)):
            for j in range(i+1,len(src)):
                for d in dst:
                    tmp = mi
                    mi = min(mi, 10 + abs(d - (src[i] + src[j])))
                    if mi != tmp:
                        s1 = src[i]
                        s2 = src[j]
        if s1 != None and s2 != None:
            src.remove(s1)
            src.remove(s2)
            mp += 10
#            print("synthesize", s1, s2, src, dst,mp)
            src.append(s1+s2)
    if len(src) <= len(dst) or s1 == None:
        # 結合しても意味が無い場合、最も差が小さいものを変更
        mi = 1000
        ss = None
        dd = None
        for s in src:
            for d in dst:
                tmp = mi
                mi = min(mi, abs(s-d))
                if tmp != mi:
                    ss = s
                    dd = d
        if ss != None and dd != None:
            mp += abs(ss-dd)
            src.remove(ss)
            dst.remove(dd)
#            print("removed", ss, src, dst, mp)
    return func(dst, src, mp)

def main():
    N,A,B,C = map(int, input().split())
    T = [A,B,C]
    L = []
    for _ in range(N):
        L.append(int(input()))
    print(func(T,L,0))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline

def func(dst, src, mp):
    if len(dst) == 0: # dst が空になったら終了
        return mp
    for s in src: # 長さが一致していたら何もせず除外
        if s in dst:
            src.remove(s)
            dst.remove(s)
#            print("removed", s, src, dst, mp)
    for i in dst: # 持っているどの竹よりも短い dst には、短縮魔法を使うしかない
        if i < min(src):
            tmp = min(src)
            mp += min(src) - i
            src.remove(tmp)
            dst.remove(i)
#            print("shorten", tmp, src, dst, mp)
    # 持っている竹のうち、mp 消費が10未満で処理できるものがあれば、その中で最小のものを延長
    mi = 10
    dd = None
    ss = None
    for s in src:
        for d in dst:
            tmp = mi
            mi = min(mi, abs(d-s))
            if mi != tmp:
                dd = d
                ss = s
    if mi < 10:
        mp += dd - ss
        src.remove(ss)
        dst.remove(dd)
#        print("extend", ss, src, dst, mp)
    # 結合した時に、目標に 10 以上近くなる 2 本を結合
    s1 = s2 = None
    if len(src) > len(dst):
        mi = 1000
        for s in src:
            for d in dst:
                mi = min(mi, abs(s-d))
        for i in range(len(src)):
            for j in range(i+1,len(src)):
                for d in dst:
                    tmp = mi
                    mi = min(mi, 10 + abs(d - (src[i] + src[j])))
                    if mi != tmp:
                        s1 = src[i]
                        s2 = src[j]
        if s1 != None and s2 != None:
            src.remove(s1)
            src.remove(s2)
            mp += 10
#            print("synthesize", s1, s2, src, dst,mp)
            src.append(s1+s2)
    if len(src) <= len(dst) or s1 == None:
        # 結合しても意味が無い場合、最も差が小さいものを変更
        mi = 1000
        ss = None
        dd = None
        for s in src:
            for d in dst:
                tmp = mi
                mi = min(mi, abs(s-d))
                if tmp != mi:
                    ss = s
                    dd = d
        if ss != None and dd != None:
            mp += abs(s-d)
            src.remove(s)
            dst.remove(d)
    return func(dst, src, mp)

def main():
    N,A,B,C = map(int, input().split())
    T = [A,B,C]
    L = []
    for _ in range(N):
        L.append(int(input()))
    print(func(T,L,0))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, A, B, C = map(int, input().split())
ls = [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 10**9
  ret0 = dfs(cur+1, a+ls[cur], b, c)
  ret1 = dfs(cur+1, a, b+ls[cur], c)
  ret2 = dfs(cur+1, a, b, c+ls[cur])
  ret3 = dfs(cur+1, a, b, c)
  return min(ret0, ret1, ret2, ret3)
print(dfs(0,0,0,0))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline


NABC=list(map(int, input().split()))
l = [int(input()) for _ in range(NABC[0])]
l.sort(reverse=True)
done = [0]*NABC[0]

ans = 1e+8
for i in range(4**NABC[0]):
    A=0
    B=0
    C=0
    A_count=-1
    B_count=-1
    C_count=-1
    i_tmp = i
    for j in range(NABC[0]):
        if l[j] <= 10: continue
        bit = i_tmp%4
        i_tmp = i_tmp//4
        if bit == 0: 
            A += l[j]
            A_count += 1
        if bit == 1:
            B += l[j]
            B_count += 1
        if bit == 2:
            C += l[j]
            C_count += 1
    if A_count==-1 or B_count==-1 or C_count==-1: continue
    tmp = abs(A-NABC[1])+abs(B-NABC[2])+abs(C-NABC[3])+max(0,A_count*10)+max(0,B_count*10)+max(0,C_count*10)
    if tmp < ans:
        ans = tmp
print(ans)

Submission status: Wrong Answer

Solution code:
import math
import copy
import sys
import fractions
import numpy as np
from functools import reduce

# ===FUNCTION===

def getInputNum():
    inputNum = int(input())
    return inputNum

def getInputListInt():
    outputoData = []
    inputData = input().split()
    outputData = [int(n) for n in inputData]

    return outputData

def getSomeInputInt(n):
    outputDataList = []
    for i in range(n):
        inputData = int(input())
        outputDataList.append(inputData)

    return outputDataList

def getSomeInputListInt(n):
    inputDataList = []
    outputDataList = []
    for i in range(n):
        inputData = input().split()
        inputDataList = [int(n) for n in inputData]
        outputDataList.append(inputDataList)

    return outputDataList

# ===CODE===

n, A, B, C = map(int, input().split())
data = getSomeInputInt(n)

def dfs(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 sys.maxsize

    nothing = dfs(cnt+1, a, b, c)
    ap = dfs(cnt+1, a+data[cnt], b, c) + 10
    bp = dfs(cnt+1, a, b+data[cnt], c) + 10
    cp = dfs(cnt+1, a, b, c + data[cnt]) + 10

    return min(nothing, ap, bp, cp)

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

Submission status: Wrong Answer

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

abc = [0,a,b,c]
ch = [0,1,2,3]
cal = []

for i in product(ch,repeat=N):
  calc = 0
  su = [0,0,0,0]
  ct = [0,0,0,0]
  temp = list(i)
  for j in range(N):
    su[temp[j]] += L[j]
    ct[temp[j]] += 1
  for k in range(1,4):
    calc += abs(abc[k]-su[k])
    calc += max((ct[k]-1),0)*10
  cal.append(calc)
    
print(min(cal))

Submission status: Wrong Answer

Solution code:
n,a,b,c=map(int,input().split())
l=[]
for i in range(n):
	l.append(int(input()))
def f(x):
	d=""
	while x!=0:
		d+=str(x%4)
		x//=4
	return d[::-1]
ans=[]
for i in range(4**n):
	A=0
	B=0
	C=0
	aa=0
	cost=0
	ff=str(f(i))
	for j in range(len(ff)):
		if ff[j]=="1":
			A+=l[j]
			aa+=1
		elif ff[j]=="2":
			B+=l[j]
			aa+=1
		elif ff[j]=="3":
			C+=l[j]
			aa+=1
	if A!=0 and B!=0 and C!=0:
		cost+=(aa-3)*10
		cost+=abs(A-a)+abs(B-b)+abs(C-c)
		ans.append(cost)
print(min(ans))

Submission status: Wrong Answer

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

def dfs(cur, a, b, c):
  if cur == N:
    return abs(a-A) + abs(b-B) + abs(c-C) - 30 if min(a, b, c) > 0 else INF
  
  # 使わない場合
  ret0 = dfs(cur + 1, A, B, C)
  # A に使う場合
  ret1 = dfs(cur + 1, A + l[cur], B, C) + 10
  # B に使う場合
  ret2 = dfs(cur + 1, A, B + l[cur], C) + 10
  # C に使う場合
  ret3 = dfs(cur + 1, A, B, C + l[cur]) + 10
  
  return min(ret0, ret1, ret2, ret3)
  
print(dfs(0, 0, 0, 0))

Submission status: Wrong Answer

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

def dfs(a,b,c,cnt):
#     print(a,b,c,cnt)
    if cnt >= len(l):
#         if a==0 or b==0 or c==0:
#             return 10**10
        return abs(a-A)+abs(b-B)+abs(c-C)
    
    res0 = dfs(a,b,c,cnt+1)
    res1 = dfs(a+l[cnt],        b, c       ,cnt+1) + 10
    res2 = dfs(       a, b+l[cnt], c       ,cnt+1) + 10
    res3 = dfs(       a,        b, c+l[cnt],cnt+1) + 10
    
    return min(res0,res1,res2,res3)

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

Submission status: Wrong Answer

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

def dfs(a,b,c,cnt):
#     print(a,b,c,cnt)
    if cnt >= len(l):
        return abs(a-A)+abs(b-B)+abs(c-C)
    
    res0 = dfs(a,b,c,cnt+1)
    if a>0:
        res1 = dfs(a+l[cnt],        b, c       ,cnt+1) + 10
    else:
        res1 = dfs(a+l[cnt],        b, c       ,cnt+1)
    
    if b>0:
        res2 = dfs(       a, b+l[cnt], c       ,cnt+1) + 10
    else:
        res2 = dfs(       a, b+l[cnt], c       ,cnt+1)

    if c>0:
        res3 = dfs(       a,        b, c+l[cnt],cnt+1) + 10
    else:
        res3 = dfs(       a,        b, c+l[cnt],cnt+1)
    
    return min(res0,res1,res2,res3)

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

Submission status: Wrong Answer

Solution code:
def main():
    import itertools as it
    N,A,B,C = map(int,input().split())
    pre = [int(input()) for _ in range(N)]
    ss = max(pre)*N <= min(A,B,C)
    if N == 3:print(A-pre[0]+B-pre[1]+C-pre[2])
    else:
        m = [0,1,2,3,4,5,6,7]
        cpm = it.permutations(pre,N)
        ccb = list(it.combinations(m[:N], 3))
        minc = 99999999999999999
        for l in cpm:
            for d in ccb:
                cmp = (d[2] - 2) * 10
                if ss:
                    asum = (A+B+C-sum(l[:d[2]+1]))
                    minc = min(minc,asum)
                else:
                    asum = abs(A - sum(l[:d[0]+1]))
                    if cmp+asum >= minc: continue
                    bsum = abs(B - sum(l[d[0]+1:d[1]+1]))
                    if cmp+asum+bsum >= minc: continue
                    csum = abs(C - sum(l[d[1]+1:d[2]+1]))
                    tc = cmp+asum+bsum+csum
                    minc = min(minc,tc)
        print(minc)
main()

Submission status: Wrong Answer

Solution code:
# 各たけを、A,B,C,使わないの4パターンに振り分ける
# LA = [l2,l4,l7]みたいになったら、あとは
# コストは（合成＋調整で）(len(LA)-1)*10 + abs(sum(LA)-A)
# A = 90, L! = [40,30,21] -> 20 + 1
import copy as cp
inf = 10**9
def cost(li, length):
    if len(li)==0:
        return inf
    return (len(li)-1)*10 + abs(sum(li)-length)

def search_cost(ln,assignment,length):
#     from IPython.core.debugger import Pdb; Pdb().set_trace()
    if len(ln)==0:
        costA = cost(assignment["A"], length[0])
        costB = cost(assignment["B"], length[1])
        costC = cost(assignment["C"], length[2])
        return costA + costB + costC
    val = ln[-1]
    candidate = []
    for take in assignment.keys():
        nextdic = cp.deepcopy(assignment)
        nextdic[take].append(val)
        print(nextdic)
        cand = search_cost(ln[:-1],nextdic,length)
        candidate.append(cand)
    return min(candidate)
  
  
# 実行部
N, A, B, C =map(int,input().split())
length = [A,B,C]
ln = []
assignment = {"A":[],"B":[],"C":[],"D":[]}

for i in range(N):
    a = int(input())
    ln.append(a)
   
search_cost(ln,assignment,length)

Submission status: Wrong Answer

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

def dfs(cur, a,b,c):
    print(cur,a,b,c)
    if cur == N:
        print(abs(a-A)+abs(b-B)+abs(c-C)-30 if min(a,b,c)>0 else INF)
        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: Wrong Answer

Solution code:
from itertools import *

N,a,b,c = map(int,input().split())
L = [int(input()) for i in range(N)]

ans = float("inf")

products = product(range(4), repeat=N)

for prod in products :
    A = []
    B = []
    C = []
    
    for i,v in enumerate(prod) :
        if v == 1 :
            A.append(L[i])
        elif v == 2 :
            B.append(L[i])
        else :
            C.append(L[i])
    
    if len(A) * len(B) * len(C) == 0 :
        continue
    
    cost = 0
    
    for li in [A, B, C] :
        cost += (len(li)-1) * 10
    
    cost += abs(a-sum(A))
    cost += abs(b-sum(B))
    cost += abs(c-sum(C))
    
    ans = min(ans, cost)

print(ans)

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

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

def nearest(key, lst) :
    ans = float("inf")
    d = float("inf")
    for el in lst :
        if abs(el - key) < d :
            ans = el
            d = abs(el - key)
    return ans, d

def tend(lln) :
    llm = list(lln)
    al, ad = nearest(a, llm)
    llm.remove(al)
    bl, bd = nearest(b, llm)
    llm.remove(bl)
    cl, cd = nearest(c, llm)
    return ad + bd + cd

def synth(lln) :
    lol = []
    for i in range(len(lln)-1) :
        for j in range(i+1, len(lln)) :
            llm = list(lln)
            lj = llm.pop(j)
            li = llm.pop(i)
            llm.append(li+lj)
            lol.append(tuple(llm))
    return lol

def synth2(lolln) :
    lol = []
    for lln in lolln :
        lol.extend(synth(lln))
    return tuple(lol)


ans = tend(ll)
lolln = set((ll,))
for i in range(5) :
    if n >= i+4 :
        lolln = set(synth2(lolln))
        for lln in lolln :
            ans = min(ans, 10*(i+1)+tend(lln))

print(ans)

Submission status: Wrong Answer

Solution code:
# python だと複数回再帰するプログラムかけ内っぽい？
N, len_A, len_B, len_C = map(int, input().split())
l = [int(input()) for i in range(N)]
print(l)
ans = 10 ** 9
pattern = 4 ** N
A = [0] * pattern
B = [0] * pattern
C = [0] * pattern
cost = [0] * pattern
for ite in range(pattern):
    ite_2 = 0
    ite_2 += ite
    A[ite], B[ite], C[ite] = [], [], []
    for j in range(N):
        if ite_2 % 4 == 0:
            A[ite].append(l[j])
        elif ite_2 % 4 == 1:
            B[ite].append(l[j])
        elif ite_2 % 4 == 2:
            C[ite].append(l[j])
        ite_2 = ite_2 // 4
    if len(A[ite]) == 0 or len(B[ite]) == 0 or len(C[ite]) == 0:
        continue
    len_A_magic, len_B_magic, len_C_magic = 0, 0, 0
    for p in A[ite]:
        len_A_magic += p
    for q in B[ite]:
        len_B_magic += q
    for r in C[ite]:
        len_C_magic += r
    cost[ite] += (len(A[ite]) - 1) * 10+abs(len_A-len_A_magic)
    cost[ite] += (len(B[ite]) - 1) * 10+abs(len_B-len_B_magic)
    cost[ite] += (len(C[ite]) - 1) * 10+abs(len_C-len_C_magic)
    if ans > cost[ite]:
        ans = cost[ite]

print(ans)

Submission status: Wrong Answer

Solution code:
N,A,B,C = map(int,input().split())
l = [int(input()) for _ in range(N)]
INF = 10 ** 9
def dfs(cur,a,b,c):
    if cur == N:
        return abs(a-A) + abs(b-B) + abs(c-C) - 30 if min(a,b,c) > 0 else INF
    ret0 = dfs(cur+1,a,b,c)
    ret1 = dfs(cur+1,a,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: Wrong Answer

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 not(i>>j*2)&1 and not(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 min([a,b,c]) != 0:
        ans = min(ans,cnt+abs(A-a)+abs(B-b)+abs(C-c))

print(ans)

Submission status: Wrong Answer

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