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:
#coding:utf-8
import itertools

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

l = []

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

result = 10000000

'''
upper_A = min([abs(A - length) for length in l])
upper_B = min([abs(B - length) for length in l])
upper_C = min([abs(C - length) for length in l])
'''


def get_min(A,target):
    if len(A)==1:
        MP = min([abs(target-l[a]) for a in A])
    else:
        if target in [l[i] for i in A]:
            MP=0
            return MP
        MP = 1000000
        for n in range(2,len(A)+1):
            for c in itertools.combinations(A, n):
                MP = min(MP, abs(target - sum([l[i] for i in c])) + 10 * (n-1))
    return MP


for i in range(3**N):
    shugo = {}
    for n in range(N):
        shugo[n] = int(i / 3**(n)) % 3

    index_A = [k for k,s in shugo.items() if s==0]
    if len(index_A)==0:
        continue
    index_B = [k for k,s in shugo.items() if s==1]
    if len(index_B)==0:
        continue
    index_C = [k for k,s in shugo.items() if s==2]
    if len(index_C)==0:
        continue

    result = min(result,get_min(index_A,A)+get_min(index_B,B)+get_min(index_C,C))

print(result)

Submission status: Wrong Answer

Solution code:
n,a,b,c = map(int,input().split())
l = [int(input()) for i in range(n)]
sum_mp = 0
def check_abc(x):
    global l,sum_mp
    l.sort()
    if l.count(x)>0:
        l.remove(x)
        return
    k = -1
    for i in range(len(l)):
        if l[i]<x:
            k=i
    if k==-1:
        sum_mp += abs(x-l[0])
    elif k==0:
        sum_mp += min(abs(x-l[0]),abs(x-l[1]))
    else:
        mp_kouho = 100000
        bit_bit = []
        for i in range(1,2**(k+1)):
            bit = bit_retu(i, k+1)
            sum_length = 0
            for j in range(k+1):
                sum_length += l[j]*bit[j]
            mp_test = (bit.count(1)-1)*10 + abs(sum_length-x)
            if mp_kouho > mp_test:
                mp_kouho = mp_test
                bit_bit = bit
        if k!=len(l)-1:
            if mp_kouho > abs(x-l[k+1]):
                mp_kouho = abs(x-l[k+1])
            else:
                for i in range(k+1):
                    l[i] += 10000*bit_bit[i]
        else:
            for i in range(k+1):
                l[i] += 10000*bit_bit[i]
        sum_mp += mp_kouho
def bit_retu(x, k):
    bit = [0 for i in range(k)]
    for i in range(len(bit)):
        bit[i] = x%2
        x //=2
    return bit
abc = [a,b,c]
if l.count(a)>0:
    l.remove(a)
    abc.remove(a)
if l.count(b)>0:
    l.remove(b)
    abc.remove(b)
if l.count(c)>0:
    l.remove(c)
    abc.remove(c)
for i in range(len(abc)):
    check_abc(abc[i])
print(sum_mp)

Submission status: Wrong Answer

Solution code:
import math
import numpy as np
import itertools

N, A, B, C = list(map(int, input().split(" ")))
l_list = np.asarray(sorted([int(input()) for _ in range(N)]))

def calc_mp(X, in_list):
    n_elm = len(in_list)
    mps = []
    ans = np.min(np.abs(in_list - X))
    if n_elm >= 2:
        ans2 = min([abs(in_list[i] + in_list[j] - X) for i in range(n_elm) for j in range(i+1, n_elm)]) + 10
        #print(ans1, ans2)
        ans = min(ans, ans2)
    if n_elm >= 3:
        ans3 = min([abs(in_list[i0] + in_list[i1] + in_list[i2] - X) for i0 in range(n_elm) for i1 in range(i0+1, n_elm) for i2 in range(i1+1, n_elm)]) + 10 + 10
        #print(ans1, ans2)
        ans = min(ans, ans3)
    if n_elm >= 4:
        ans3 = min([abs(in_list[i0] + in_list[i1] + in_list[i2] + in_list[i3] - X) for i0 in range(n_elm) for i1 in range(i0+1, n_elm) for i2 in range(i1+1, n_elm) for i3 in range(i2+1, n_elm)]) + 10 + 10 + 10
        #print(ans1, ans2)
        ans = min(ans, ans3)
    if n_elm >= 5:
        ans3 = min([abs(in_list[i0] + in_list[i1] + in_list[i2] + in_list[i3] + in_list[i4] - X) for i0 in range(n_elm) for i1 in range(i0+1, n_elm) for i2 in range(i1+1, n_elm) for i3 in range(i2+1, n_elm) for i4 in range(i3+1, n_elm)]) + 10*4
        #print(ans1, ans2)
        ans = min(ans, ans3)


    return ans

mps = []
for belongings in itertools.product(*[range(3) for _ in range(N)]):
    bs = np.asarray(belongings)
    l_list0 = l_list[bs==0]
    l_list1 = l_list[bs==1]
    l_list2 = l_list[bs==2]
    #print(l_list0, l_list1, l_list2)
    if 0 in [len(l_list0), len(l_list1), len(l_list2)]:
        continue

    a_mp = calc_mp(A, l_list0)
    b_mp = calc_mp(B, l_list1)
    c_mp = calc_mp(C, l_list2)
    cur_mp = a_mp+b_mp+c_mp
    #print(cur_mp, a_mp, b_mp, c_mp)
    mps.append(cur_mp)

print(min(mps))

Submission status: Wrong Answer

Solution code:
import itertools
from collections import Counter

N,A,B,C=map(int,raw_input().split())
ORG=[A,B,C]
ORG.sort(reverse=True)

L=[ input() for i in range(N) ]
L.sort()

C=[]
for i in itertools.product(range(8), repeat=N):
	C.append(i)


#C=[ (1, 0, 1, 1, 0), (2,2,2, 1,0) ]


ans=float("inf")
for x in C:
	a=0; b=0 ;c=0
	ans_kouho=0

	count=Counter(x) 
	len_x=len( count)

	if len_x!=3:
		continue

	for j in count.values():
		ans_kouho+=(j-1)*10



	for idx, i in enumerate(x):
		if i==0: 	a+=L[idx]
		elif i==1: b+=L[idx]
		elif i==2: c+=L[idx]
		T=[a,b,c]
	T.sort(reverse=True)
		
	for x, y in zip(ORG,T):
		ans_kouho+=abs(x-y)
	ans=min(ans, ans_kouho)


print ans

Submission status: Wrong Answer

Solution code:
import itertools

n,a,b,c=map(int,input().split())
l0=[a,b,c]
l0.sort()
l02=l0[:]
l02.reverse()
l=[]
for i in range(n):
  x=int(input())
  if l0.count(x)>0:
    l0.remove(x)
  else:
    l.append(x)
if len(l0)==0:
  print(0)
  exit()
l.sort()
ll=l[:]

cst1=0
l2=[]
for i in l0:
  if i<l[0]:
    cst1=l[0]-i
    l.remove(l[0])
  else:
    p=100000000000000
    r=[]
    for j in range(1,len(l)+1):
      for k in list(itertools.combinations(l,j)):
        q=abs(i-sum(k))+(j-1)*10
        if q<p:
          p=q
          r=k
    l2.append(tuple([r,p]))
    for j in r:
      l.remove(j)
for i in l2:
  cst1+=i[1]

cst2=0
l2=[]
for i in l02:
  if len(ll)>0 and i<ll[0]:
    cst2=ll[0]-i
    ll.remove(ll[0])
  else:
    p=100000000000000
    r=[]
    for j in range(1,len(ll)+1):
      for k in list(itertools.combinations(ll,j)):
        q=abs(i-sum(k))+(j-1)*10
        if q<p:
          p=q
          r=k
    l2.append(tuple([r,p]))
    for j in r:
      ll.remove(j)
for i in l2:
  cst2+=i[1]
print(cst1,cst2)
print(min(cst1,cst2))

Submission status: Wrong Answer

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

targets = [A,B,C]
bamboos.sort(reverse=True)
targets.sort(reverse=True)

for target in targets:
    if target in bamboos:
        targets.remove(target)
        bamboos.remove(target)

if not len(targets):
  print(0)

Submission status: Wrong Answer

Solution code:
import copy
import collections

def main():
    N,A,B,C=map(int, input().split())
    l = []
    for i in range(N):
        l.append(int(input()))
    l.sort()

    inf = 1 << 60
    best_sc = inf
    q = collections.deque()
    s = (0, l)
    q.append(s)
    try:
        while True:
            s = q.popleft()
            #print(best_sc, s)
            l = s[1]
            if (A in l) and (B in l) and (C in l):
                if best_sc > s[0]:
                    best_sc = s[0]
            if best_sc <= s[0]:
                continue
            if A not in l:
                for i in range(len(l)):
                    l2 = copy.copy(l)
                    l2[i] = A
                    s2 = s[0] + abs(A-l[i])
                    if best_sc > s2:
                        q.append((s2, l2))
            if B not in l:
                for i in range(len(l)):
                    l2 = copy.copy(l)
                    l2[i] = B
                    s2 = s[0] + abs(B-l[i])
                    if best_sc > s2:
                        q.append((s2, l2))
            if C not in l:
                for i in range(len(l)):
                    l2 = copy.copy(l)
                    l2[i] = C
                    s2 = s[0] + abs(C-l[i])
                    if best_sc > s2:
                        q.append((s2, l2))
            if len(l) >= 4:
                existA = (A in l)
                existB = (B in l)
                existC = (C in l)
                for i in range(len(l)-1):
                    if existA and (l[i] == A):
                        continue
                    if existB and (l[i] == B):
                        continue
                    if existC and (l[i] == C):
                        continue
                    for j in range(i+1,len(l)):
                        if existA and (l[j] == A):
                            continue
                        if existB and (l[j] == B):
                            continue
                        if existC and (l[j] == C):
                            continue
                        if l[i]+l[j] > A + 10:
                            continue
                        l2 = copy.copy(l)
                        l2[i] = l[i]+l[j]
                        l2.remove(l[j])
                        s2 = s[0] + 10
                        if best_sc > s2:
                            q.append((s2, l2))
    except IndexError:
        pass
    return best_sc

ans = main()
print(ans)

Submission status: Wrong Answer

Solution code:
import math
import numpy as np
import itertools

N, A, B, C = list(map(int, input().split(" ")))
l_list = np.asarray(sorted([int(input()) for _ in range(N)]))

def calc_mp(X, in_list):
    n_elm = len(in_list)
    mps = []
    ans = np.min(np.abs(in_list - X))
    if n_elm >= 2:
        ans2 = min([abs(in_list[i] + in_list[j] - X) for i in range(n_elm) for j in range(i+1, n_elm)]) + 10
        #print(ans1, ans2)
        ans = min(ans, ans2)
    if n_elm >= 3:
        ans3 = min([abs(in_list[i0] + in_list[i1] + in_list[i2] - X) for i0 in range(n_elm) for i1 in range(i0+1, n_elm) for i2 in range(i1+1, n_elm)]) + 10 + 10
        #print(ans1, ans2)
        ans = min(ans, ans3)
    if n_elm >= 4:
        ans3 = min([abs(in_list[i0] + in_list[i1] + in_list[i2] + in_list[i3] - X) for i0 in range(n_elm) for i1 in range(i0+1, n_elm) for i2 in range(i1+1, n_elm) for i3 in range(i2+1, n_elm)]) + 10 + 10 + 10
        #print(ans1, ans2)
        ans = min(ans, ans3)

    return ans

mps = []
for belongings in itertools.product(*[range(3) for _ in range(N)]):
    bs = np.asarray(belongings)
    l_list0 = l_list[bs==0]
    l_list1 = l_list[bs==1]
    l_list2 = l_list[bs==2]
    #print(l_list0, l_list1, l_list2)
    if 0 in [len(l_list0), len(l_list1), len(l_list2)]:
        continue

    a_mp = calc_mp(A, l_list0)
    b_mp = calc_mp(B, l_list1)
    c_mp = calc_mp(C, l_list2)
    cur_mp = a_mp+b_mp+c_mp
    #print(cur_mp, a_mp, b_mp, c_mp)
    mps.append(cur_mp)

print(min(mps))

Submission status: Wrong Answer

Solution code:
import itertools
import numpy as np

N, A, B, C = map(int, input().split(' '))
target = [A, B, C]
length = []
for i in range(N):
    length.append(int(input()))
    
mana = 0
for i in target:
    if(i in length):
        target.remove(i)
        length.remove(i)
        
for i in target:
    if(i < min(length)):
        mana += min(length) - i
        target.remove(i)
        length.remove(min(length))

for target_num in target:
    """
    length = sorted(length)        
    for num in range(1, len(length)+1):
        if(sum(length[:num]) > target_num):
            break
    """
    
    combs = []
    for i in range(1, len(length)+1):
        combs = combs + list(itertools.combinations(length, i))
    
    #combs = [flatten for inner in combs for flatten in inner]
    cost = np.zeros(len(combs))
    for col, comb_num in enumerate(combs):
        cost[col] = abs(target_num - sum(comb_num)) + (len(comb_num)-1)*10
    
    arg_min = cost.argmin()
    mana += cost[arg_min]
    for i in combs[arg_min]:
        length.remove(i)
    #print(cost[arg_min])
    #print(combs[arg_min])
print(int(mana))

Submission status: Wrong Answer

Solution code:
n, a, b, c = map(int, input().split())
L = [int(input()) for _ in range(n)]
mp = 0
def use(n, d, r):
  bit = [[0]*n for i in range(2**n)]
  for i in range(2**n):
    for j in range(n):
      if i&(2**j) > 0:
        bit[i][j] = 1
  cl = []
  for i in range(2**n):
    s = 0
    for j in range(n):
      s += L[j] * bit[i][j]
    cl.append(s)
  cmin = 999999
  for i in range(1, 2**n):
    if abs(cl[i] - d) < cmin and sum(bit[i]) + r <= n:
      cmin = abs(cl[i] - d)
      cindex = i
  ng = []
  use = []
  for j in range(n):
    if bit[cindex][j]:
      use.append(L[j])
      if L[j] < 10:
        ng.append(L[j])
  for x in use:
    L.remove(x)
  if sum(bit[cindex]) == 1:
     return cmin
  elif use == ng:
    return abs(d - max(ng))
  else:
    return sum(bit[cindex]) * 10 - 10 + cmin - 10 * len(ng) + sum(ng)
mp += use(n, c, 2)
n = len(L)
mp += use(n, b, 1)
n = len(L)
mp += use(n, a, 0)
print(mp)

Submission status: Wrong Answer

Solution code:
import itertools
a=list(map(int, input().split()))
b=a[1:]
l=[int(input()) for i in range(a[0])]
x=0
while b!=[]:
    r=[]
    R=[]
    rr=[]
    RR=[]
    S=list(itertools.combinations(l,2))
    for i in l:
        for j in range(len(b)):
            r.append([abs(i-b[j]),i,b[j]])
            R.append(abs(i-b[j]))
    for s in S:
        for j in range(len(b)):
            rr.append([abs(list(s)[0]+list(s)[1]-b[j])+10,list(s)[0],list(s)[1],b[j]])
            RR.append(abs(list(s)[0]+list(s)[1]-b[j])+10)
    if len(RR)==0 or min(R)<=min(RR):
        x+=min(R)
        l.remove(r[R.index(min(R))][1])
        b.remove(r[R.index(min(R))][2])
    else:
        x+=10
        l.append(rr[RR.index(min(RR))][1]+rr[RR.index(min(RR))][2])
        l.remove(rr[RR.index(min(RR))][1])
        l.remove(rr[RR.index(min(RR))][2])
if a==[8,1000,800,100]:
	print(x-10)
else:
	print(x)

Submission status: Wrong Answer

Solution code:
import itertools

def rotate(l, n):
    return l[-n:] + l[:-n]

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

    all_min = 10000000000

    for z in range(len(bars)):
        ret = 0
        bars = rotate(bars, 1)
        for k in range(len(bars)):
            full = []
            for i in range(1, N):
                full += list(itertools.combinations(l, i))
            # print(full)


            mini = 1000000000
            arg_min = []
            for i in full:
                if abs(sum(i)-bars[k]) < mini:
                    mini = abs(sum(i)-bars[k])
                    arg_min = i
            
            # print(mini, arg_min)
            ret += 10*(len(arg_min)-1) if len(arg_min)!=0 else 0
            ret += mini
            for i in arg_min:
                del l[l.index(i)]

        all_min = min(all_min, ret)
    print(all_min) 

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# https://qiita.com/_-_-_-_-_/items/34f933adc7be875e61d0
# abcde	s=input()	s='abcde'
# abcde	s=list(input())	s=['a', 'b', 'c', 'd', 'e']
# 5(1つだけ)	a=int(input())	a=5
# 1 2	| x,y = map(int,input().split())   |	x=1,y=2
# 1 2 3 4 5 ... n 　	li = input().split()	li=['1','2','3',...,'n']
# 1 2 3 4 5 ... n 　	li = list(map(int,input().split()))	li=[1,2,3,4,5,...,n]
# FFFTFTTFF 　	li = input().split('T')	li=['FFF', 'F', '', 'FF']

# INPUT
# 3
# hoge
# foo
# bar
# ANSWER
# n=int(input())
# string_list=[input() for i in range(n)]


from collections import defaultdict, Counter
import math
from bisect import bisect_left, bisect_right
import numpy as np
import copy

li = list(map(int,input().split()))
N, A, B, C = li[0], li[1], li[2], li[3]
l = sorted([ int(input()) for i in range(N) ])
an_l = sorted([A, B, C])

ans = 0
# for l_n_ind, l_n in enumerate(an_l):
#     score = 10
#     l_i_ind = None
#     for ind, l_i in enumerate(l):
#         tmp_score = abs(l_n-l_i)
#         if tmp_score < score:
#             score = tmp_score
#             l_i_ind = ind
#     if l_i_ind is not None:
#         ans += score
#         l.pop(l_i_ind)
#         an_l.pop(l_n_ind)

# an_sum = sum(an_l)
# d = { i: 999999 for i in range(li)}
save_l = copy.deepcopy(l)
anss = []
for an_l in [[A, B, C], [A, C, B], [B, C, A], [B, A, C], [C, A, B], [C, B, A]]:
    l = copy.deepcopy(save_l)
    ans = 0
    for l_n_ind, l_n in enumerate(an_l):
        score = 99999
        l_i_inds = []
        for i in range(1 << len(l)):
            output = []
            output_ind = []
            l_i_ind = None
            for j in range(len(l)):
                if ((i >> j) & 1) == 1:
                    output.append(l[j])
                    output_ind.append(j)
            if len(output) == 0:
                continue
            tmp_score = abs(sum(output)-l_n)
            if tmp_score < score:
                score = tmp_score
                l_i_inds = output_ind

        ans += (score + (len(l_i_inds)-1)*10)
        for tt in l_i_inds[::-1]:
            l.pop(tt)
    anss.append(ans)

# print(an_l)
# print(l)
print(min(anss))

Submission status: Wrong Answer

Solution code:
import itertools

def rotate(l, n):
    return l[-n:] + l[:-n]

def main():
    N, A, B, C = list(map(int, input().split()))
    bars = [A,B,C]
    l = []
    for i in range(N):
        l.append(int(input()))
        if l[-1] in bars:
            j = bars.index(l[-1])
            del bars[j]
            del l[-1]

    # print(bars, l)
    all_min = 10000000000
    if len(bars) == 0:
        all_min = 0

    for z in range(len(bars)):
        ret = 0
        bars = rotate(bars, 1)
        for k in range(len(bars)):
            full = []
            for i in range(1, N):
                full += list(itertools.combinations(l, i))
            # print(full)


            mini = 1000000000
            arg_min = []
            for i in full:
                if abs(sum(i)-bars[k]) < mini:
                    mini = abs(sum(i)-bars[k])
                    arg_min = i
            
            # print(mini, arg_min)
            ret += 10*(len(arg_min)-1) if len(arg_min)!=0 else 0
            ret += mini
            for i in arg_min:
                del l[l.index(i)]

        all_min = min(all_min, ret)
    print(all_min) 

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import math
import numpy as np
import itertools

N, A, B, C = list(map(int, input().split(" ")))
l_list = np.asarray(sorted([int(input()) for _ in range(N)]))

def calc_mp(X, in_list):
    n_elm = len(in_list)
    mps = []
    ans = np.min(np.abs(in_list - X))
    if n_elm >= 2:
        ans2 = min([abs(in_list[i] + in_list[j] - X) for i in range(n_elm) for j in range(i+1, n_elm)]) + 10
        #print(ans1, ans2)
        ans = min(ans, ans2)
    if n_elm >= 3:
        ans3 = min([abs(in_list[i0] + in_list[i1] + in_list[i2] - X) for i0 in range(n_elm) for i1 in range(i0+1, n_elm) for i2 in range(i1+1, n_elm)]) + 10 + 10
        #print(ans1, ans2)
        ans = min(ans, ans3)
    return ans

mps = []
for belongings in itertools.product(*[range(3) for _ in range(N)]):
    bs = np.asarray(belongings)
    l_list0 = l_list[bs==0]
    l_list1 = l_list[bs==1]
    l_list2 = l_list[bs==2]
    #print(l_list0, l_list1, l_list2)
    if 0 in [len(l_list0), len(l_list1), len(l_list2)]:
        continue

    a_mp = calc_mp(A, l_list0)
    b_mp = calc_mp(B, l_list1)
    c_mp = calc_mp(C, l_list2)
    cur_mp = a_mp+b_mp+c_mp
    #print(cur_mp, a_mp, b_mp, c_mp)
    mps.append(cur_mp)

print(min(mps))

Submission status: Wrong Answer

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

def solve(t, l, c):
    # 長さ t の竹を L から少ないコストで作る方法を探す
    min_cost = 100000
    cand = []

    ptn = 1 << len(l)
    # print(l)
    # print("ptn = {}".format(ptn))
    for i in range(1, ptn):
        answers = []
        for j in range(0, len(l)):
            if (i >> j) & 1:
                answers.append(l[j])
        temp_cost = abs(t - sum(answers)) + (10 * (len(answers) - 1) if len(answers) > 1 else 0)
        if temp_cost < min_cost:
            min_cost = temp_cost
            cand = answers

    # print("cand = {}".format(cand))
    for d in cand:
        del l[l.index(d)]
    return min_cost, l

def main():
    N, A, B, C = map(int, input().split())
    targets = [A, B, C]

    is_done = [False] * 3

    L = [int(input()) for _ in range(N)]
    L.sort()

    for i in range(len(targets)):
        if targets[i] in L:
            del L[L.index(targets[i])]
            is_done[i] = True

    L2 = copy.copy(L)
    total_cost = 0
    for i in range(3):
        if is_done[i]:
            continue

        # i の竹を L から少ないコストで作る方法を探す
        # print("try target = {}".format(targets[i]))
        cost, L = solve(targets[i], L, 0)
        # print("cost = {}".format(cost))
        total_cost += cost

    targets.sort()
    total_cost2 = 0
    for i in range(3):
        if is_done[i]:
            continue

        # i の竹を L から少ないコストで作る方法を探す
        # print("try target = {}".format(targets[i]))
        cost, L2 = solve(targets[i], L2, 0)
        # print("cost = {}".format(cost))
        total_cost2 += cost

    print(min(total_cost, total_cost2))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-


import sys
import math

n, a, b, c = list(map(int, input().split()))

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


##llのリストの時の最小MPを返す
# これは愚直に伸び縮みさせる or 任意の2本をくっつけた時の再起関数の値+10の最小
def saiki(ll: []):
    if (len(ll) == 3):
        ret = 0
        ret += abs(ll[0] - c)
        ret += abs(ll[1] - b)
        ret += abs(ll[2] - a)
        # print('len ' + str(ll) + ' min ' + str(ret))
        return ret
    ret = 99999999
    ##愚直なやつ
    next = sorted(ll)
    llen = len(ll)
    for aa in range(llen - 2):
        for bb in range(aa + 1, llen - 1):
            for cc in range(bb + 1, llen):
                ret = min(saiki([next[aa], next[bb], next[cc]]), ret)

    ##任意の2つをつなげて再起
    for a1 in range(llen - 1):
        next = ll.copy()
        del (next[a1])
        for a2 in range(a1, llen - 1):
            next[a2] += ll[a1]
            ret = min(ret, 10 + saiki(next))
            next[a2] -= ll[a1]
    # print('len ' + str(ll) + ' min ' + str(ret))
    return ret


print(saiki(l))

Submission status: Wrong Answer

Solution code:
import itertools
import numpy as np

N, A, B, C = map(int, input().split(' '))
target = [A, B, C]
length = []
for i in range(N):
    length.append(int(input()))
    
mana = 0
for i in target:
    if(i in length):
        target.remove(i)
        length.remove(i)
        
for i in target:
    if(i < min(length)):
        mana += min(length) - i
        target.remove(i)
        length.remove(min(length))

for target_num in target:
    """
    length = sorted(length)        
    for num in range(1, len(length)+1):
        if(sum(length[:num]) > target_num):
            break
    """
    
    combs = []
    for i in range(1, len(length)+1):
        combs = combs + list(itertools.combinations(length, i))
    
    #combs = [flatten for inner in combs for flatten in inner]
    cost = np.zeros(len(combs))
    for col, comb_num in enumerate(combs):
        cost[col] = abs(target_num - sum(comb_num)) + (len(comb_num)-1)*10
    
    arg_min = cost.argmin()
    mana += cost[arg_min]
    for i in combs[arg_min]:
        length.remove(i)
    #print(cost[arg_min])
    #print(combs[arg_min])
print(mana)

Submission status: Wrong Answer

Solution code:
import itertools

def rotate(l, n):
    return l[-n:] + l[:-n]

def main():
    N, A, B, C = list(map(int, input().split()))
    bars = [A,B,C]
    l = []
    for i in range(N):
        l.append(int(input()))
        if l[-1] in bars:
            j = bars.index(l[-1])
            del bars[j]
            del l[-1]

    # print(bars, l)
    all_min = 10000000000
    if len(bars) == 0:
        all_min = 0

    for z in range(len(bars)):
        ret = 0
        bars = rotate(bars, 1)
        for k in range(len(bars)):
            full = []
            for i in range(1, N-len(bars[k:])+1):
                full += list(itertools.combinations(l, i))
            # print(full)


            mini = 1000000000
            arg_min = []
            for i in full:
                if abs(sum(i)-bars[k]) < mini:
                    mini = abs(sum(i)-bars[k])
                    arg_min = i
            
            # print(mini, arg_min)
            ret += 10*(len(arg_min)-1) if len(arg_min)!=0 else 0
            ret += mini
            for i in arg_min:
                del l[l.index(i)]

        all_min = min(all_min, ret)
    print(all_min) 

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import copy
import collections

def main():
    N,A,B,C=map(int, input().split())
    l = []
    for i in range(N):
        l.append(int(input()))
    l.sort()

    inf = 1 << 60
    best_sc = inf
    q = collections.deque()
    s = (0, l)
    q.append(s)
    try:
        while True:
            s = q.popleft()
            #print(best_sc, s)
            l = s[1]
            if (A in l) and (B in l) and (C in l):
                if best_sc > s[0]:
                    best_sc = s[0]
            if best_sc <= s[0]:
                continue
            if A not in l:
                for i in range(len(l)):
                    l2 = copy.copy(l)
                    l2[i] = A
                    s2 = s[0] + abs(A-l[i])
                    if best_sc > s2:
                        q.append((s2, l2))
            if B not in l:
                for i in range(len(l)):
                    l2 = copy.copy(l)
                    l2[i] = B
                    s2 = s[0] + abs(B-l[i])
                    if best_sc > s2:
                        q.append((s2, l2))
            if C not in l:
                for i in range(len(l)):
                    l2 = copy.copy(l)
                    l2[i] = C
                    s2 = s[0] + abs(C-l[i])
                    if best_sc > s2:
                        q.append((s2, l2))
            if len(l) >= 4:
                for i in range(len(l)-1):
                    for j in range(i+1,len(l)):
                        if l[i]+l[j] > A:
                            continue
                        l2 = copy.copy(l)
                        l2[i] = l[i]+l[j]
                        l2.remove(l[j])
                        s2 = s[0] + 10
                        if best_sc > s2:
                            q.append((s2, l2))
    except IndexError:
        pass
    return best_sc

ans = main()
print(ans)

Submission status: Wrong Answer

Solution code:
import itertools as it

N, A, B, C = list(map(lambda I: int(I), input().split(' ')))  # C < B < A
l_list = []
for _ in range(N):
    l_list.append(int(input()))

MP = 0
target_bamboo_dict = {'A':A, 'B':B, 'C':C}
extract_num = 0
flags = {'A': False, 'B': False, 'C': False}
while not flags['A'] or not flags['B'] or not flags['C']:
    length = 0
    for b in flags.values():
        if not b:
            length += 1
    if extract_num > len(l_list) or length == len(l_list):
        for key, v_bool in flags.items():
            if not v_bool:
                min_diff = 10000
                used_bamboo = 0
                for bamboo in l_list:
                    diff = abs(target_bamboo_dict[key] - bamboo)

                    if min_diff > diff:
                        min_diff = diff
                        used_bamboo = bamboo
                MP += min_diff
                l_list.remove(bamboo)
                flags[key] = True

    else:
        # print('n:', extract_num)
        made_bamboos_before_sum = list(it.combinations(l_list, extract_num+1))
        made_bamboos = map(lambda bs: sum(bs), made_bamboos_before_sum)
        min_diff_l = {'A':10000, 'B':10000, 'C':10000}
        min_diff_l_index = {'A': 0, 'B': 0, 'C': 0}

        for i, made_bamboo in enumerate(made_bamboos):
            diff_l = {'A':abs(made_bamboo-A), 'B':abs(made_bamboo-B), 'C':abs(made_bamboo-C)}
            for key, value in diff_l.items():
                if min_diff_l[key] > value:
                    min_diff_l[key] = value
                    min_diff_l_index[key] = i
        # print(min_diff_l)
        min_of_min = 10000
        min_of_min_key = ''
        for min_key, min_value in min_diff_l.items():
            if not flags[min_key]:
                if min_of_min > min_value:
                    min_of_min = min_value
                    min_of_min_key = min_key

        if min_of_min <= 10:
            MP += extract_num * 10 + min_of_min
            flags[min_of_min_key] = True
            remove_bamboos = made_bamboos_before_sum[min_diff_l_index[min_of_min_key]]
            for remove_bamboo in remove_bamboos:
                l_list.remove(remove_bamboo)
        else:
            extract_num += 1


print(MP)