Problem:


Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243



Sample input:
5 100 90 80
98
40
30
21
80


Sample output:
23

Submission status: Accepted

Solution code:
import sys
import math
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def make_grid(h, w, num): return [[int(num)] * w for _ in range(h)]


def main():
	N, A, B, C = NMI()
	L = [NI() for _ in range(N)]

	def dfs(bamboo, a, b, c):
		if bamboo == N:
			if a*b*c == 0:
				return 10**100
			a, b, c = sorted([a, b, c], reverse=True)
			res = abs(A-a) + abs(B-b) + abs(C-c)
			return res

		res = 10**100

		res = min(res, dfs(bamboo + 1, a + L[bamboo], b, c) + 10) if a > 0 else min(res, dfs(bamboo + 1, a + L[bamboo], b, c))
		res = min(res, dfs(bamboo + 1, a, b + L[bamboo], c) + 10) if b > 0 else min(res, dfs(bamboo + 1, a, b + L[bamboo], c))
		res = min(res, dfs(bamboo + 1, a, b, c + L[bamboo]) + 10) if c > 0 else min(res, dfs(bamboo + 1, a, b, c + L[bamboo]))
		res = min(res, dfs(bamboo + 1, a, b, c))
		return res

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



if __name__ == "__main__":
	main()

Submission status: Accepted

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

def rec(i, a, b, c):
  if i == N:
    if not a or not b or not c: return float('inf')
    return abs(a-A) + abs(b-B) + abs(c-C)
  
  ret = rec(i+1, a, b, c)
  
  ret = min(ret, rec(i+1, a+L[i], b, c) + (10 if a else 0))
  ret = min(ret, rec(i+1, a, b+L[i], c) + (10 if b else 0))
  ret = min(ret, rec(i+1, a, b, c+L[i]) + (10 if c else 0))
  
  return ret

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

Submission status: Accepted

Solution code:
# C MP消費を抑えるにはABCとの差が小さけれは良い
n, A, B, C = map(int, input().split())
l = [int(input()) for _ in range(n)]
INF = 10**9


def dfs(now, a, b, c):
    if now == n:
        return abs(a - A) + abs(b - B) + abs(c - C) - 30 if min(a, b, c) > 0 else INF
    # 方法１　１つ飛ばす
    way1 = dfs(now + 1, a, b, c)
    # 方法２　合成魔法(MP10)
    way2 = dfs(now + 1, a + l[now], b, c)+10
    way3 = dfs(now + 1, a, b + l[now], c)+10
    way4 = dfs(now + 1, a, b, c + l[now])+10
    return min(way1, way2, way3, way4)


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

Submission status: Accepted

Solution code:
import sys
import itertools
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')


def main():
    N, A, B, C = in_nn()
    l = list(map(int, read().rstrip().split()))

    comb = list(itertools.product(range(4), repeat=N))
    ans = 10**9 + 7

    for c in comb:
        if (0 in c) and (1 in c) and (2 in c):
            t = [0] * 3
            m = [-10] * 3
            for i in range(N):
                if c[i] == 3:
                    continue
                t[c[i]] += l[i]
                m[c[i]] += 10

            m[0] += abs(t[0] - A)
            m[1] += abs(t[1] - B)
            m[2] += abs(t[2] - C)

            ans = min(ans, sum(m))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import itertools
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')


def main():
    N, A, B, C = in_nn()
    l = list(map(int, read().rstrip().split()))

    comb = list(itertools.product(range(4), repeat=N))
    abc_p = list(itertools.permutations([A, B, C], 3))

    ans = 10**9 + 7
    for abc in abc_p:
        for c in comb:
            if (0 in c) and (1 in c) and (2 in c):
                t = [0] * 3
                m = [-10] * 3
                for i in range(N):
                    if c[i] == 3:
                        continue
                    t[c[i]] += l[i]
                    m[c[i]] += 10

                for i in range(3):
                    m[i] += abs(t[i] - abc[i])

                ans = min(ans, sum(m))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

import itertools
kouho=list(itertools.product(range(4), repeat=n))
ans=10**9
for item in kouho:

    if 0 in item and 1 in item and 2 in item:
        cost=0
        abc=[0]*3

        for i,v in enumerate(item):
            if v<3:
                if abc[v]>0:
                    cost+=10
                abc[v]+=l[i]

        for i in range(3):
            cost+=abs(abc[i]-ABC[i])
        #print(item,cost)
        ans=min(ans,cost)

print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i for _ in range(j)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
#from itertools import accumulate #list(accumulate(A))
import itertools

N, *A = mi()
L = [ii() for _ in range(N)]

#A = sorted(A)
sum_a = sum(A)

def dfs(i, a, b, c, use):
    if (0 not in [a, b, c]) and use > 2:
        global ans
        #abc = sorted([a, b, c])
        #ans = min(ans, (use-3)*10 + sum([abs(abc[i]-A[i]) for i in range(3)]))
        ans = min(ans, (use-3)*10 + abs(a-A[0]) + abs(b-A[1]) + abs(c-A[2]))

    if i > N-1:
        return

    dfs(i+1, a+L[i], b, c, use+1)
    dfs(i+1, a, b+L[i], c, use+1)
    dfs(i+1, a, b, c+L[i], use+1)
    dfs(i+1, a, b, c, use)

ans = float('inf')
dfs(0, 0, 0, 0, 0)

print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i for _ in range(j)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
#from itertools import accumulate #list(accumulate(A))
import itertools

N, *A = mi()
L = [ii() for _ in range(N)]

A = sorted(A)
sum_a = sum(A)

def dfs(i, a, b, c, use):
    if (0 not in [a, b, c]) and use > 2:
        global ans
        abc = sorted([a, b, c])
        ans = min(ans, (use-3)*10 + sum([abs(abc[i]-A[i]) for i in range(3)]))

    if i > N-1:
        return

    dfs(i+1, a+L[i], b, c, use+1)
    dfs(i+1, a, b+L[i], c, use+1)
    dfs(i+1, a, b, c+L[i], use+1)
    dfs(i+1, a, b, c, use)

ans = float('inf')
dfs(0, 0, 0, 0, 0)

print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i for _ in range(j)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
#from itertools import accumulate #list(accumulate(A))
import itertools

N, *A = mi()
L = [ii() for _ in range(N)]
L_ = [L[i] for i in range(N)]
N_ = N

A = sorted(A)
#sum_l = sum(L)
tmp = [0] * 3
ans = float('inf')

for k in itertools.product([0,1], repeat=N_):
    N = sum(k)
    if N < 3:
        continue
    L = []
    for x in range(N_):
        if k[x]:
            L.append(L_[x]*k[x])
    #L = [L_[x]*k[x] for x in range(N_)]
    sum_l = sum(L)

    for i in range(1, N+1):
        for koho_i in range(1, 2**i):
            for koho_j in range(1, 2**i):
                j = i
                #print(koho_i, koho_j)
                if koho_i & koho_j:
                    continue
                #tmp[0] = [L[x]*koho_i[x] for x in range(i)]
                tmp[0] = sum([L[x]*min((koho_i & 1<<x), 1) for x in range(i)])
                #tmp[1] = [L[x]*koho_j[x] for x in range(j)]
                tmp[1] = sum([L[x]*min((koho_j & 1<<x), 1) for x in range(j)])
                tmp[2] = sum_l - tmp[0] - tmp[1]
                #print(tmp)

                if 0 in tmp:
                    continue

                tmp = sorted(tmp)
                cost = (N-3) * 10 + sum([abs(tmp[x]-A[x]) for x in range(3)])
                #if cost < ans:
                    #print(tmp, cost, N)
                #if tmp[0] == 80 and tmp[1] == 91 and tmp[2] == 98:
                    #print(cost)
                ans = min(ans, cost)

print(ans)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    inf=10**9
    n,*abc=MI()
    abc.sort()
    a,b,c=abc
    dp={(0,0,0):0}
    for _ in range(n):
        l=II()
        ndp={}
        for xyz,s in dp.items():
            ndp.setdefault(xyz,inf)
            ndp[xyz]=min(ndp[xyz],s)
            for i in range(3):
                nx=list(xyz)
                ns=s+10 if nx[i] else s
                nx[i]+=l
                t=tuple(sorted(nx))
                ndp.setdefault(t,inf)
                ndp[t]=min(ndp[t],ns)
            dp=ndp

    ans=inf
    for (x,y,z),s in dp.items():
        if x*y*z==0:continue
        cur=abs(x-a)+abs(y-b)+abs(z-c)+s
        ans=min(ans,cur)

    print(ans)

main()

Submission status: Accepted

Solution code:
from itertools import product
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    inf=10**16
    n,*abc=MI()
    ll=[II() for _ in range(n)]

    ans=inf
    for pp in product(range(4),repeat=n):
        ss=[0]*3
        cnt=[0]*3
        for l,p in zip(ll,pp):
            if p==3:continue
            ss[p]+=l
            cnt[p]+=1
        cur=0
        for i in range(3):
            if cnt[i]==0:
                cur=inf
                break
            cur+=(cnt[i]-1)*10+abs(abc[i]-ss[i])
        #print(pp,cur)
        ans=min(ans,cur)

    print(ans)

main()

Submission status: Accepted

Solution code:
from sys import stdin
#入力
readline=stdin.readline
inf=10**9
n,a,b,c=map(int,readline().split())
l=[int(readline()) for _ in range(n)]

def dfs(now,x,y,z):
    if now==n:
        return abs(a-x)+abs(b-y)+abs(c-z)-30 if min(x,y,z)>0 else inf
    else:
        res1=dfs(now+1,x,y,z)
        res2=dfs(now+1,x+l[now],y,z)+10
        res3=dfs(now+1,x,y+l[now],z)+10
        res4=dfs(now+1,x,y,z+l[now])+10
        return min(res1,res2,res3,res4)

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

Submission status: Accepted

Solution code:
n,a,b,c=map(int,input().split())
l=[int(input()) for _ in range(n)]
def func(g):
  if len(g[0])==0 or len(g[1])==0 or len(g[2])==0:return -1
  ret=0
  ret+=10*(len(g[0])-1)
  ret+=10*(len(g[1])-1)
  ret+=10*(len(g[2])-1)
  a_=sum([l[i] for i in g[0]])
  b_=sum([l[i] for i in g[1]])
  c_=sum([l[i] for i in g[2]])
  ret+=abs(a-a_)
  ret+=abs(b-b_)
  ret+=abs(c-c_)
  return ret
m=n*2
ans=pow(10,9)
for i in range(2**m):
  g=[[]for _ in range(4)]
  for j in range(n):
    g[(i//pow(4,j))%4].append(j)
  tmp=func(g)
  if tmp>=0:
    ans=min(ans,tmp)

print(ans)

Submission status: Accepted

Solution code:
def f(x):
    if len(x) == n:
        p.append(x)
    else:
        for i in S:
            f(x+[i])

n , a , b , c = map(int,input().split())
take = [int(input()) for i in range(n)]
S = [0,1,2,3]
p = []
f([])
ans = 10**9
for i in range(len(p)):
    sai = [0,0,0]
    cou = 0
    for j in range(n):
        if p[i][j] != 3:
            if sai[p[i][j]] == 0:
                cou -= 10
            sai[p[i][j]] += take[j]
            cou += 10
    sai.sort()
    if sai[0] == 0:
        continue
    cou += abs(sai[0]-c)+abs(sai[1]-b)+abs(sai[2]-a)
    ans = min(ans,cou)
    
print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict
from itertools import combinations, permutations
from operator import itemgetter
n, a, b, c, *L = map(int, open(0).read().split())
L.sort()
A = [a, b, c]
dicts = [defaultdict(lambda: 10**5) for _ in range(3)]
for i in range(n-2):
    for x in combinations(enumerate(L), i+1):
        k = tuple(i for i, l in x)
        v = sum(l for i, l in x)
        for d, x in zip(dicts, A):
            d[k] = min(d[k], abs(x-v) + 10*i)
scores = [sorted(d.items(), key=itemgetter(1)) for d in dicts]

ans = 10**5
for p1, p2, p3 in permutations(range(3)):
    k1, v1 = scores[p1][0]
    k1 = set(k1)
    for k2, v2 in scores[p2]:
        k2 = set(k2)
        if len(k1 & k2) == 0:
            break
    for k3, v3 in scores[p3]:
        k3 = set(k3)
        if len(k1 & k3) + len(k2 & k3) == 0:
            break
    ans = min(ans, sum([v1, v2, v3]))
print(ans)

Submission status: Accepted

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

import itertools 
data = list(itertools.product(range(4), repeat = n))

ans = float('inf')
for d in data:
    x = [[] for i in range(4)]
    for i in range(n):
        x[d[i]].append(l[i])
    if len(x[0])<1 or len(x[1])<1 or len(x[2])<1:
        continue
    buf = 0
    for i in range(3):
        buf += 10*(len(x[i])-1)
        buf += abs(sum(x[i])-m[i])

    ans = min(ans,buf)
print(ans)

Submission status: Accepted

Solution code:

N,A,B,C = map(int, input().split())
bamboos = [int(input()) for _ in range(N)]
#print("---", bamboos)
INF = float("inf")
ans = INF
def solve(idx, cnt_merge, a, b, c):

    if idx == N:
        if min(a,b,c) > 0:
            return abs(A - a) + abs(B - b) + abs(C - c) + 10 * (cnt_merge-3)
        else:
            return INF

    pa = solve(idx+1, cnt_merge+1, a+bamboos[idx], b, c)
    pb = solve(idx+1, cnt_merge+1, a, b+bamboos[idx], c)
    pc = solve(idx+1, cnt_merge+1, a, b, c+bamboos[idx])
    pn = solve(idx+1, cnt_merge, a, b, c)
    return min(pa, pb, pc, pn)


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

Submission status: Accepted

Solution code:

N,A,B,C = map(int, input().split())
bamboos = [int(input()) for _ in range(N)]
#print("---", bamboos)
ans = float("inf")
def solve(lst, idx):
    global ans
    if idx == N:
        #print("qqqqq")
        for i in range(3):
            if len(lst[i]) == 0:
                return

        
        pa = 10 * (len(lst[0])-1) + abs(A - sum(lst[0]))
        pb = 10 * (len(lst[1])-1) + abs(B - sum(lst[1]))
        pc = 10 * (len(lst[2])-1) + abs(C - sum(lst[2]))
        #print(pa, pb, pc, lst)
        ans = min(ans, pa + pb + pc)
        #print("aaaaaaa")
        return

    
    for i in range(4):
        nxt_lst = [lst[0][:], lst[1][:], lst[2][:], lst[3][:]]
        nxt_lst[i].append(bamboos[idx])
        #print(lst, nxt_lst)
        
        solve(nxt_lst, idx+1)

empty_lst =  [[], [], [], []]   
solve(empty_lst, 0)
print(ans)

Submission status: Accepted

Solution code:
n,a,b,c = map(int,input().split())
t = [int(input()) for i in range(n)]
ans = float('inf')
for i in range(1<<(n*2)):
    tmp,cnt,a_t,b_t,c_t = i,0,0,0,0
    for j in range(n):
        if tmp&3==1:
            a_t+=t[j]
            if a_t!=t[j]: cnt+=10
        elif tmp&3==2:
            b_t+=t[j]
            if b_t!=t[j]: cnt+=10
        elif tmp&3==3:
            c_t+=t[j]
            if c_t!=t[j]: cnt+=10
        tmp >>= 2
    if a_t==0 or b_t==0 or c_t==0: continue
    tmp = abs(a-a_t)+abs(b-b_t)+abs(c-c_t)+cnt
    ans = min(ans,tmp)
print(ans)

Submission status: Accepted

Solution code:
#import sys
#import numpy as np
#import math
#import itertools
#from fractions import Fraction
#import itertools
from collections import deque
#import heapq
#from fractions  import gcd
#input=sys.stdin.readline
import bisect

n,A,B,C=map(int,input().split())
l=[int(input()) for _ in range(n)]
inf=10**9
def rec(i,a,b,c):
    if i==n:
        if not a or not b or not c:
            return inf
        return abs(A-a)+abs(B-b)+abs(C-c)
    res=rec(i+1,a,b,c)
    res=min(res,rec(i+1,a+l[i],b,c)+(10 if a else 0))
    res=min(res,rec(i+1,a,b+l[i],c)+(10 if b else 0))
    res=min(res,rec(i+1,a,b,c+l[i])+(10 if c else 0))

    return res
print(rec(0,0,0,0))

Submission status: Accepted

Solution code:
from itertools import product


def main():
    n, a, b, c = map(int, input().split())
    l = [int(input()) for _ in range(n)]
    ans = 10**4
    for p in product(range(4), repeat=n):
        abc = [[], [], []]
        for i, pi in enumerate(p):
            if pi > 0:
                abc[pi - 1].append(i)
        fl = False
        for i in abc:
            fl |= len(i) == 0
        if fl:
            continue
        cost = 0
        for i in range(3):
            cost += abs(sum(l[j] for j in abc[i]) - (a, b, c)[i]) + 10 * (len(abc[i]) - 1)
        ans = min(ans, cost)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

def dfs(i, a, b, c):
    if i == N:
        if a and b and c:
            return abs(a - A) + abs(b - B) + abs(c - C)
        else:
            return 10 ** 9 + 7
    else:
        ret1 = dfs(i + 1, a + l[i], b, c) + 10
        ret2 = dfs(i + 1, a, b + l[i], c) + 10
        ret3 = dfs(i + 1, a, b, c + l[i]) + 10
        ret4 = dfs(i + 1, a, b, c)
        ret = min(ret1, ret2, ret3, ret4)
        return ret
    
ans = dfs(0, 0, 0, 0)
print(ans - 30)

Submission status: Accepted

Solution code:
n,a,b,c = map(int,input().split())
l = []
for i in range(n):
    l.append(int(input()))
mi = 10**18
aa = []
ba = []
ca = []
da = []
def dfs(ai,bi,ci,di,i):
    global mi
    if i == n:
        if len(ai) == 0 or len(bi) == 0 or len(ci) == 0:
            return mi
        tmp = 0
        if len(ai) > 1:
            tmp += 10 * (len(ai) - 1)
        if len(bi) > 1:
            tmp += 10 * (len(bi) - 1)
        if len(ci) > 1:
            tmp += 10 * (len(ci) - 1)
        tmp += abs(a - sum(ai))
        tmp += abs(b - sum(bi))
        tmp += abs(c - sum(ci))
        mi = min(mi,tmp)
        return mi
    else:
        return min(min(dfs(ai+[l[i]],bi,ci,di,i+1),dfs(ai,bi+[l[i]],ci,di,i+1)),min(dfs(ai,bi,ci+[l[i]],di,i+1),dfs(ai,bi,ci,di+[l[i]],i+1)))
print(dfs(aa,ba,ca,da,0))

Submission status: Accepted

Solution code:
def main():
  n, a, b, c = map(int, input().split())

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

  def test(i, x, y, z):
    if(i == n):
      if(x == 0 or y == 0 or z == 0):
        return float('inf')
      return abs(a - x) + abs(b - y) + abs(c - z)

    res = test(i + 1, x, y, z)

    res = min(res, (test(i + 1, x + l[i], y, z) + (0 if x == 0 else 10))) 
    res = min(res, (test(i + 1, x, y + l[i], z) + (0 if y == 0 else 10))) 
    res = min(res, (test(i + 1, x, y, z + l[i]) + (0 if z == 0 else 10))) 

    return res

  print(test(0, 0, 0, 0))

if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3


# import numpy as np

N, A, B, C = list(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 + 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))
# ans = 1000
# for i in itertools.product([0, 1, 2, 3], repeat=n):

#     ans_tmp = 0
#     counter = collections.Counter(i)
#     print(counter)
#     if not((1 in counter) and (2 in counter) and (3 in counter)):
#         continue

#     length = [a, b, c]

#     for index, opt in enumerate(i):
#         if opt != 0:
#             length[opt-1] += L[index]

#     print(length)
#     ans_tmp += (counter[1]-1)*10
#     ans_tmp += (counter[2]-1)*10
#     ans_tmp += (counter[3]-1)*10

#     ans_tmp += abs(a - length[0])
#     ans_tmp += abs(b - length[1])
#     ans_tmp += abs(c - length[2])

#     ans = min(ans, ans_tmp)

# print(ans)

Submission status: Accepted

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

from itertools import permutations

def dfs(idx):
    if idx == n:
        return [[[], [], []]]

    ret = []
    for ll in dfs(idx + 1):
        ret.append(ll)

        for i in range(3):
            ll2 = [ll[0][:], ll[1][:], ll[2][:]]
            ll2[i].append(idx)
            ret.append(ll2)

    return ret

lists = dfs(0)

target = [a, b, c]

ans = float('inf')
for _lists in lists:
    if [] not in _lists:

        point = 0
        l = []
        for lis in _lists:
            l.append(sum([x[i] for i in lis]))
            point += 10 * (len(lis) - 1)

        for perm in permutations(l):
            point2 = point
            for i in range(3):
                point2 += abs(target[i] - perm[i])

            ans = min(point2, ans)

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n,a,b,c=MI()
mn=inf
lis=[I() for i in range(n)]
for i in list(product([0,1,2,3],repeat=n)):
    x=[]
    y=[]
    z=[]
    for j in range(n):
        if i[j]==0:
            x.append(lis[j])
        elif i[j]==1:
            y.append(lis[j])
        elif i[j]==2:
            z.append(lis[j])
    if len(x)==0 or len(y)==0 or len(z)==0:
        ans=inf
    else:
        ans=abs(sum(x)-a)+10*(len(x)-1)+abs(sum(y)-b)+10*(len(y)-1)+abs(sum(z)-c)+10*(len(z)-1)
    #print(ans)
    if ans<mn:
        mn=ans
        X=x
        Y=y
        Z=z
print(mn)
'''print(X)
print(Y)
print(Z)
'''

Submission status: Accepted

Solution code:
from itertools import product
import bisect

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

ll = []
for _ in range(N):
    ll.append(int(input()))



ans = 10**8
ite = product(range(4),repeat=N)
for pattern in ite:
    bag = [[],[],[]]
    singles = []
    mp = 0
    for i, p in enumerate(pattern):
        if p == 3: singles.append(ll[i])
        else: bag[p].append(ll[i])
    
    zero_cnt = 0
    for b in bag:
        if not b: zero_cnt+=1
        else: mp += (len(b)-1)*10
    if not singles: zero_cnt+=1
    if zero_cnt >= 2: continue

    bamboos = []
    for b in bag:
        if b: bamboos.append(sum(b))
    for s in singles:
        bamboos.append(s)

    bamboos.sort()
    # print(bamboos)
    
    for t in tl:
        curr_min = 10000
        curr_min_i = 0
        for i, ba in enumerate(bamboos):
            if abs(ba - t) < curr_min:
                curr_min = abs(ba-t)
                curr_min_i = i
        mp += curr_min
        bamboos.pop(curr_min_i)

    ans = min(ans,mp)

print(ans)

Submission status: Accepted

Solution code:
n, a, b, c = map(int, input().split())
take = []

for i in range(n):
    t = int(input())
    take.append(t)

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

def cal_cost(li, a):
    if li == []:
        return 10**12
    co = 0
    if len(li) == 1:
        co += abs(li[0] - a)
    else:
        co += abs(sum(li) - a)
        co += (len(li) - 1) * 10
    return co

min_cost = 10**12
for i in range(4**n):
    cost = 0
    num = Base_10_to_n(i, 4).zfill(n)
    for_A = []
    for_B = []
    for_C = []
    for j in range(n):
        if num[j] == '1':
            for_A.append(take[j])
        elif num[j] == '2':
            for_B.append(take[j])
        elif num[j] == '3':
            for_C.append(take[j])
    cost += cal_cost(for_A, a)
    cost += cal_cost(for_B, b)
    cost += cal_cost(for_C, c)
    if cost < min_cost:
        min_cost = cost

print(min_cost)

Submission status: Accepted

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

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
from collections import defaultdict
from collections import deque
from functools import lru_cache


#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)


#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
N,A,B,C = IL()
L = ILs(N)

def make_take(T,x,b):
  n = len(T)
  Tdic = DD(int)
  for t in T:
    Tdic[t] += 1
  if n == 0:
    return INF,T
  choose = 0
  number = 0
  for i in range(n):
    if (b>>i)&1 == 1:
      Tdic[T[i]] -= 1
      choose += T[i]
      number += 1
  MP = abs(choose-x)+(number-1)*10
  T = []
  for k,v in Tdic.items():
    T.extend([k]*v)
  return MP,T

MIN = INF
n1 = len(L)
for b1 in range(1,1<<n1):
  MP1,L1 = make_take(L,A,b1)
  n2 = len(L1)
  for b2 in range(1,1<<n2):
    MP2,L2 = make_take(L1,B,b2)
    n3 = len(L2)
    for b3 in range(1,1<<n3):
      MP3,L3 = make_take(L2,C,b3)
      MIN = min(MIN,MP1+MP2+MP3)
print(MIN)