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

Solution (Python):
n,A,B,C=map(int,input().split())
l =[]
for i in range(n):
    a = int(input())
    l += [a]

m = []
ans = 9999
for i in range(4**n):
    a,b,c=0,0,0
    t = 0
    if i % 4 == 1:
        a += l[0]
    elif i % 4 == 2:
        b += l[0]
    elif i % 4 == 3:
        c += l[0]
    if i // 4 != 0:
        i = i // 4
        if i % 4 == 1:
            if a != 0:
                t += 10
            a += l[1]
        elif i % 4 == 2:
            if b != 0:
                t += 10
            b += l[1]
        elif i % 4 == 3:
            if c != 0:
                t += 10
            c += l[1]
        if i // 4 != 0:
            i = i // 4
            if i % 4 == 1:
                if a != 0:
                    t += 10
                a += l[2]
            elif i % 4 == 2:
                if b != 0:
                    t += 10
                b += l[2]
            elif i % 4 == 3:
                if c != 0:
                    t += 10
                c += l[2]
            if i // 4 != 0:
                i = i // 4
                if i % 4 == 1:
                    if a != 0:
                        t += 10
                    a += l[3]
                elif i % 4 == 2:
                    if b != 0:
                        t += 10
                    b += l[3]
                elif i % 4 == 3:
                    if c != 0:
                        t += 10
                    c += l[3]
                if i // 4 != 0:
                    i = i // 4
                    if i % 4 == 1:
                        if a != 0:
                            t += 10
                        a += l[4]
                    elif i % 4 == 2:
                        if b != 0:
                            t += 10
                        b += l[4]
                    elif i % 4 == 3:
                        if c != 0:
                            t += 10
                        c += l[4]
                    if i // 4 != 0:
                        i = i // 4
                        if i % 4 == 1:
                            if a != 0:
                                t += 10
                            a += l[5]
                        elif i % 4 == 2:
                            if b != 0:
                                t += 10
                            b += l[5]
                        elif i % 4 == 3:
                            if c != 0:
                                t += 10
                            c += l[5]
                        if i // 4 != 0:
                            i = i // 4
                            if i % 4 == 1:
                                if a != 0:
                                    t += 10
                                a += l[6]
                            elif i % 4 == 2:
                                if b != 0:
                                    t += 10
                                b += l[6]
                            elif i % 4 == 3:
                                if c != 0:
                                    t += 10
                                c += l[6]
                            if i // 4 != 0:
                                i = i // 4
                                if i % 4 == 1:
                                    if a != 0:
                                        t += 10
                                    a += l[7]
                                elif i % 4 == 2:
                                    if b != 0:
                                        t += 10
                                    b += l[7]
                                elif i % 4 == 3:
                                    if c != 0:
                                        t += 10
                                    c += l[7]
    if a==0 or b==0 or c==0:
        continue
    t += abs(A - a) + abs(B - b) + abs(C - c)
    if ans > t:
        ans = t

print(ans)

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


ans=[]

def getmagic(a,b,c):
    return abs(sum(a)-A)+abs(sum(b)-B)+abs(sum(c)-C)+(len(a)-1)*10+(len(b)-1)*10+(len(c)-1)*10

def dfs(a,b,c,depth):
    if depth==N:
        if len(a)>=1 and len(b)>=1 and len(c)>=1:
            ans.append(getmagic(a,b,c))
    else:
        tmp=a[:]
        tmp.append(L[depth])
        dfs(tmp, b, c, depth + 1)
        tmp=b[:]
        tmp.append(L[depth])
        dfs(a, tmp, c, depth + 1)
        tmp=c[:]
        tmp.append(L[depth])
        dfs(a, b, tmp, depth + 1)
        dfs(a, b, c, depth + 1)


dfs([],[],[],0)

print(min(ans))

Solution (Python):
N, A, B, C = map(int, input().split())
l = [int(input()) for i in range(N)]
minMP = 999999
for i in range(1 << len(l)):
    a = []
    b = []
    for j in range(len(l)):
        if ((i >> j) & 1) == 1:
            a.append(l[j])
        else:
            b.append(l[j])
    if not(a) or not(b):
        continue
    for w in range(1 << len(b)):
        c = []
        d = []
        for v in range(len(b)):
            if ((w >> v) & 1) == 1:
                c.append(b[v])
            else:
                d.append(b[v])
        if not(c) or not(d):
            continue
        for p in range(1 << len(d)):
            e = []
            f = []
            for q in range(len(d)):
                if ((p >> q) & 1) == 1:
                    e.append(d[q])
                else:
                    f.append(d[q])
            if not(e):
                continue
            MP = (len(a) + len(c) + len(e) - 3) * 10
            MP += abs(A - sum(a)) + abs(B - sum(c)) + abs(C - sum(e))
            minMP = min(minMP, MP)
print(minMP)

Solution (Python):
from itertools import product
N, A, B, C = map( int, input().split())
L = [ int( input()) for _ in range(N)]
T = [-A, -B, -C]
ans = 10**4
for V in product( range(4), repeat = N):
    ANS = [-A,-B,-C]
    mp = 0
    for i in range(N):
        if V[i] == 3:
            continue
        if ANS[V[i]] > T[V[i]]:
            mp += 10
        ANS[V[i]] += L[i]
    if ANS[0] == -A or ANS[1] == -B or ANS[2] == -C:
            continue
    ans = min( ans, sum( list( map( abs, ANS))) + mp)
print(ans)

Solution (Python):
b = [0,0,0]

n, b[0], b[1], b[2] = map(int, input().split())
L = [int(input()) for _ in range(n)]

s = [0 for _ in range(n)]

ans = 999999
for i in range(4 ** n):
    t = [0, 0, 0]
    u = [0, 0, 0]
    temp_ans = 0
    temp = i
    for j in range(n):
        s[j] = temp % 4
        if s[j] < 3:
            t[s[j]] += L[j]
            u[s[j]] += 1
        temp //= 4

    if 0 in u:
        continue

    for j in range(3):
        temp_ans += abs(b[j] - t[j]) + ((u[j] - 1) * 10)

    ans = min(ans, temp_ans)

print(ans)

Solution (Python):
N, A, B, C = map(int, input().split())
l = []
for i in range(N):
    l.append(int(input()))
ans = 100000000


def rec(a, b, c, d):
    if d == N:
        if a[1] > 0 and b[1] > 0 and c[1] > 0:
            global ans
            ans = min(
                ans,
                abs(
                    a[0] - A) + abs(b[0] - B) + abs(c[0] - C)
                + 10 * (a[1] + b[1] + c[1] - 3)
            )
        return
    rec((a[0] + l[d], a[1] + 1), b, c, d + 1)
    rec(a, (b[0] + l[d], b[1] + 1), c, d + 1)
    rec(a, b, (c[0] + l[d], c[1] + 1), d + 1)
    rec(a, b, c, d + 1)


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

Solution (Python):
import itertools

N, A, B, C = map(int, input().split())
L = [int(input()) for n in range(N)]
P = []

for n in range(1, N + 1):
    P.extend(itertools.combinations([n for n in range(N)], n))

add_len = {s: sum(L[i] for i in s) for s in P}


def cost(v, s):
    return 10 * (len(s) - 1) + abs(v - add_len[s])


res = 2 << 30
for a in P:
    cost_a = cost(A, a)
    if res < cost_a:
        continue

    for b in P:
        cost_b = cost(B, b)
        if res < cost_b:
            continue

        set_a = set(a)
        set_b = set(b)
        if len(set_a & set_b):
            continue

        for c in P:
            cost_c = cost(C, c)
            if res < cost_c:
                continue

            set_c = set(c)
            if len(set_a & set_c) or len(set_b & set_c):
                continue
            res = min(res, cost_a + cost_b + cost_c)

print(res)

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

def mp(bl, used, i):
  score = 1<<29
  if bl[0] and bl[1] and bl[2]:
    sortedbl = sorted(bl)
    score = used + abs(sortedbl[0]-C) + abs(sortedbl[1]-B) + abs(sortedbl[2]-A)
  if i == N:
    return score
  s0 = mp(bl, used, i+1)
  add = 0
  if bl[0]:
    add = 10
  bl[0]+=ln[i]
  s1 = mp(bl, used+add, i+1)
  bl[0]-=ln[i]
  add = 0
  if bl[1]:
    add = 10
  bl[1]+=ln[i]
  s2 = mp(bl, used+add, i+1)
  bl[1]-=ln[i]
  add = 0
  if bl[2]:
    add = 10
  bl[2]+=ln[i]
  s3 = mp(bl, used+add, i+1)
  bl[2]-=ln[i]
  return min(score, s0, s1, s2, s3)

print(mp([0]*3, 0, 0))

Solution (Python):


import itertools
import copy

def calc_cost(l_list, x):
    return 10 * (len(l_list) - 1) + abs(sum(l_list) - x)

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

ans = 1e10
for i in range(1, len(ln) + 1):
    mp = 0
    tmp = copy.copy(ln)
    for tree_a in itertools.combinations(ln, i):
        for t in tree_a:
            tmp.remove(t)
        mp_a = calc_cost(tree_a, A)
        mp += mp_a
        for j in range(1, len(tmp) + 1):
            for tree_b in itertools.combinations(tmp, j):
                for t in tree_b:
                    tmp.remove(t)
                mp_b = calc_cost(tree_b, B)
                mp += mp_b
                for k in range(1, len(tmp) + 1):
                    for tree_c in itertools.combinations(tmp, k):
                        mp_c = calc_cost(tree_c, C)
                        ans = min(ans, mp + mp_c)
                tmp.extend(tree_b)
                mp -= mp_b
        tmp.extend(tree_a)
        mp -= mp_a
print(ans)

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

ans = float("inf")
d = [a,b,c]

def calc_cost(aa, bb, cc):
    if len(aa)*len(bb)*len(cc) == 0:
        return -1
    cost = 0
    for ind, lis in enumerate([aa,bb,cc]):
        cost += 10*(len(lis)-1) + abs(sum(lis) - d[ind])
    return cost

def DFS(depth, aa, bb, cc):
    global ans
    if depth == n:
        cost = calc_cost(aa,bb,cc)
        if cost >= 0:
            ans = min(ans, cost)
        return
    for i in range(4):
        next_a = aa[::] + [[], [ls[depth]]][i%4 == 1]
        next_b = bb[::] + [[], [ls[depth]]][i%4 == 2]
        next_c = cc[::] + [[], [ls[depth]]][i%4 == 3]
        DFS(depth+1, next_a, next_b, next_c)

DFS(0, [],[],[])
print(ans)

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

products = list(itertools.product([0, 1, 2, 3], repeat=N))

ans = float("inf")
for p in products:
    scores = [[0, 0], [0, 0], [0, 0], [0, 0]]
    for i in range(len(p)):
        scores[p[i]][0] += L[i]
        scores[p[i]][1] += 1
    temp = [elem[0] for elem in scores[:3]]
    cost = sum([10 * (elem[1] - 1) for elem in scores[:3] if elem[1] >= 1])
    if 0 in temp:
        continue
    sorted(temp)
    cost += sum([abs(target[i] - temp[i]) for i in range(3)])
    ans = min(ans, cost)
print(ans)

Solution (Python):
import itertools
N, a, b, c = [int(_) for _ in input().split()]
L = [int(input()) for _ in range(N)]
ans = 10**10
for K in itertools.product(range(4), repeat=N):
    A = [[] for _ in range(4)]
    for i in range(N):
        A[K[i]] += [L[i]]
    if len(A[1]) and len(A[2]) and len(A[3]):
        cost = 10 * (N - len(A[0]) - 3)
        cost += abs(a - sum(A[1]))
        cost += abs(b - sum(A[2]))
        cost += abs(c - sum(A[3]))
        ans = min(cost, ans)
print(ans)

Solution (Python):
from itertools import combinations
N, A, B, C = map(int, input().split())
l = list(map(int, (input() for _ in range(N))))
z = [A, B, C]

def f(i, x, acc):
    if i == 0:
        return acc
    return min(
        f(
            i - 1,
            list(set(x) - set(t)),
            acc + abs(z[3 - i] - sum(l[j] for j in t)) + 10 * (n - 1)
        )
        for n in range(1, len(x) - i + 2)
        for t in combinations(x, n)
    )


ans = f(3, list(range(N)), 0)
print(ans)

Solution (Python):
from itertools import product
N, A, B, C = map(int, input().split())
L = [int(input()) for i in range(N)]

ans = float('inf')
for select in product(range(4), repeat=N):
    tmp = 0

    a = [L[i] for i in range(N) if select[i] == 1]
    b = [L[i] for i in range(N) if select[i] == 2]
    c = [L[i] for i in range(N) if select[i] == 3]

    if not (a and b and c):
        continue

    tmp += (max(0, len(a) - 1)) * 10
    tmp += (max(0, len(b) - 1)) * 10
    tmp += (max(0, len(c) - 1)) * 10

    a = sum(a)
    b = sum(b)
    c = sum(c)
    tmp += abs(A - a) + abs(B - b) + abs(C - c)
    ans = min(ans, tmp)

print(ans)

Solution (Python):


import sys
import itertools

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

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()


n, a, b, c = LI()
A = [a, b, c]
K = [II() for _ in range(n)]

ans = INF
for x in itertools.product([0, 1, 2, 3], repeat=n):
    s = set(x)
    if 0 not in s or 1 not in s or 2 not in s:
        continue
    T = [0] * 3
    cnt = 0
    for i, n in enumerate(x):
        if n == 3:
            continue
        if T[n]:
            cnt += 1
        T[n] += K[i]

    
    tmp = cnt * 10
    for i in range(3):
        tmp += abs(T[i] - A[i])

    ans = min(ans, tmp)

print(ans)

Solution (Python):
n,a,b,c = map(int,input().split())
li = []
ans=10000000000

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

def search(depth,ho):
    if(depth == n):
        
        global ans
        acn=0
        bcn=0
        ccn=0
        alo=0
        blo=0
        clo=0
        for i in range(n):
            if(ho[i] == 1):
                acn += 1
                alo += li[i]
            elif(ho[i] == 2):
                bcn += 1
                blo += li[i]
            elif(ho[i] == 3):
                ccn += 1
                clo += li[i]
        if(acn==0 or bcn==0 or ccn==0):
            return
        ans = min(ans,abs(a-alo)+(acn-1)*10+abs(b-blo)+(bcn-1)*10+abs(c-clo)+(ccn-1)*10)
        return
    ho.append(0)
    search(depth+1,ho)
    ho.pop(len(ho)-1)
    ho.append(1)
    search(depth+1,ho)
    ho.pop(len(ho)-1)
    ho.append(2)
    search(depth+1,ho)
    ho.pop(len(ho)-1)
    ho.append(3)
    search(depth+1,ho)
    ho.pop(len(ho)-1)
search(0,[])
print(ans)

Solution (Python):
from sys import setrecursionlimit; setrecursionlimit(10**9)
N, A, B, C = map(int, input().split())
L = []
for _ in range(N):
    L.append(int(input()))

















def change_len(L):
    L.sort()
    return abs(L[0]-C) + abs(L[1]-B) + abs(L[2]-A)

def rec(i, a, b, c, comb, cons):
    if i == N:
        if 0 not in [a, b, c]:
            comb.append([a, b, c, cons])
        return None

    
    
    v = 0 if a == 0 else 10
    rec(i+1, a+L[i], b, c, comb, cons+v)
    v = 0 if b == 0 else 10
    rec(i+1, a, b+L[i], c, comb, cons+v)
    v = 0 if c == 0 else 10
    rec(i+1, a, b, c+L[i], comb, cons+v)
    rec(i+1, a, b, c, comb, cons)
    return comb

comb = rec(0, 0, 0, 0, [], 0)
minval = 10**9
for c in comb:
    minval = min(minval, change_len(c[:3]) + c[3])
print(minval)

Solution (Python):

import math
import sys


n,a,b,c = map(int, sys.stdin.readline().rstrip().split())
len_s = []
for _ in range(n):
  len_s.append(int(sys.stdin.readline().rstrip()))

def solve(abc, mp, k):
  if k < 0:
    if abc[0]==0 or abc[1]==0 or abc[2]==0:
      return 10000
    else:
      return mp + abs(abc[0]-a) + abs(abc[1]-b) + abs(abc[2]-c) - 30
  else:
    add_a = solve([abc[0]+len_s[k],abc[1],abc[2]], mp+10, k-1)
    add_b = solve([abc[0],abc[1]+len_s[k],abc[2]], mp+10, k-1)
    add_c = solve([abc[0],abc[1],abc[2]+len_s[k]], mp+10, k-1)
    add_no = solve([abc[0],abc[1],abc[2]], mp, k-1)
    return min(add_a, add_b, add_c, add_no)

if __name__ == "__main__":
  print(solve([0, 0, 0], 0, n-1))

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

ans = float('inf')

j = 0
for P in permutations(L):
  S = [P[0]]
  for i in range(1, N):
    S.append(P[i] + S[-1])
  for ia in range(N-2):
    a = S[ia]
    for ib in range(ia+1, N-1):
      b = S[ib] - S[ia]
      for ic in range(ib+1, N):
        c = S[ic] - S[ib]
        tmp = (ic-2)*10 + abs(A-a) + abs(B-b) + abs(C-c)
        ans = ans if ans < tmp else tmp
print(ans)

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

def cost(z, ABC):
    if len(z) == 0:
        return float('inf')
    else:
        return abs(ABC - sum(z)) + (len(z) - 1) * 10

def retmin(l, a, b, c, d):
    if len(l) == d:
        return cost(a, A) + cost(b, B) + cost(c, C)
    else:
        new_a = a + [l[d]]
        new_b = b + [l[d]]
        new_c = c + [l[d]]
        
        return min(retmin(l, new_a, b, c, d + 1),
                   retmin(l, a, new_b, c, d + 1),
                   retmin(l, a, b, new_c, d + 1),
                   retmin(l, a, b, c, d + 1))
    
print(retmin(l, [], [], [], 0))

Solution (Python):
n, a, b, c = map(int, input().split())

take = [int(input()) for x in range(n)]

minv = float("inf")
def dfs(stat, depth=n):
    global minv
    stat = stat[:]
    if depth:
        for i in range(4):
            stat[depth - 1] = i
            dfs(stat, depth=depth - 1)
    else:
        result = calc(stat)
        if result is not None:
            minv = min(minv, result)


def calc(stat):
    abc = [0, 0, 0]
    abc_cost = [-1, -1, -1]
    for s, t in zip(stat, take):
        if s < 3:
            abc_cost[s] += 1
            abc[s] += t

    results = [0, 0, 0]
    for i, (cost, label) in enumerate(zip(abc_cost, [a, b, c])):
        if cost < 0:
            return None
        results[i] = (cost * 10) + abs(abc[i] - label)
    return sum(results)


dfs([0] * n)
print(minv)

Solution (Python):
from itertools import product

def cost(t):
    x, y, z = 0, 0, 0
    count_x, count_y, count_z = 0, 0, 0
    for i, v in zip(t, l):
        if i == 1:
            x += v
            count_x += 1
        elif i == 2:
            y += v
            count_y += 1
        elif i == 3:
            z += v
            count_z += 1
    if count_x == 0 or count_y == 0 or count_z == 0:
        return 1000000000
    return 10 * (count_x + count_y + count_z - 3) + abs(x - a) + abs(y - b) + abs(z - c)


if __name__ == '__main__':
    n, a, b, c = map(int, input().split())
    l = [int(input()) for _ in range(n)]
    print(min(map(cost, product(*[range(4)] * n))))

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

max_loop_count = 4 ** N
K = [0, A, B, C]


def func(count):
    comb = [0] * N
    i = 0
    while count > 0:
        comb[i] = count % 4
        i += 1
        count //= 4

    tmp = 0
    for k in range(1, 4):
        num = 0
        sum_ = 0
        for i in range(N):
            if comb[i] == k:
                num += 1
                sum_ += L[i]

        if num == 0:
            return 3100

        tmp += 10 * (num - 1) + abs(sum_ - K[k])

    return tmp


ans = 3100
for lp in range(max_loop_count):
    ans = min(ans, func(lp))

print(ans)

Solution (Python):
def Base_10_to_n(X, n):
    if (int(X/n)):
        return Base_10_to_n(int(X/n), n)+str(X%n)
    return str(X%n)
n,a,b,c=map(int,input().split())
r=[a,b,c]
d=[int(input()) for i in range(n)]
ans=99999999
for i in range(4**n):
    s=Base_10_to_n(i,4)
    s="0"*(n-len(s))+s
    tmp=[[0,0],[0,0],[0,0]]
    for j in range(n):
        if s[j] in '012':
            tmp[int(s[j])][0]+=d[j]
            tmp[int(s[j])][1]+=1
    t=0
    for j in range(3):
        if tmp[j][0]==0:
            break
        t+=abs(r[j]-tmp[j][0])+max((tmp[j][1]-1)*10,0)
    else:
        if ans>t:
            ans=t
print(ans)

Solution (Python):
n,a,b,c=map(int,input().split())
s=[int(input())for i in range(n)]
q=5000
def f(X):
    if (int(X/4)):
        return f(int(X/4))+str(X%4)
    return str(X%4)
for i in range(4**n):
    p=f(i)
    p="0"*(n-len(p))+p
    d=[0,0,0]
    for j in range(n):
        if p[j]!="3":
            d[int(p[j])]+=s[j]
    else:
        if not 0 in d:
            q=min(q,abs(d[0]-a)+abs(d[1]-b)+abs(d[2]-c)+10*(p.count("0")+p.count("1")+p.count("2")-3))
            if q==7:
            	print(d)
print(q)

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

ABC = [A, B, C]

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

abc = [0 for i in range(N)]

ans = 1 << 30

def cost():
    take = [0 for i in range(3)]

    tmp = 0

    for i in range(N):
        if abc[i] == 0:
            continue
        take[abc[i]-1] += l[i]
        tmp += 1

    tmp = (tmp - 3) * 10


    for i in range(3):
        if take[i] == 0:
            return 1 << 30
        tmp += abs(ABC[i] - take[i])

    return tmp


def dfs(i):
    global ans
    if i == N:
        ans = min(ans, cost())
        return
    for j in range(4):
        abc[i] = j
        dfs(i+1)

dfs(0)
print(ans)

Solution (Python):
def c_synthetic_kadomatsu(N, A, B, C, L):
    from itertools import permutations
    
    
    
    
    ans = float('inf')
    for perm in permutations(range(N)):
        for j in range(1, N):
            for k in range(1, N - j):
                for l in range(1, N - j - k + 1):
                    cost = 0
                    s, t, u = perm[:j], perm[j:j + k], perm[j + k:j + k + l]
                    a, b, c = [], [], []
                    for _s in s:
                        a.append(L[_s])
                    for _t in t:
                        b.append(L[_t])
                    for _u in u:
                        c.append(L[_u])
                    cost += (len(a) + len(b) + len(c) - 3) * 10
                    cost += abs(sum(a) - A) + abs(sum(b) - B) + abs(sum(c) - C)
                    ans = min(ans, cost)
    return ans

N, A, B, C = [int(i) for i in input().split()]
L = [int(input()) for _ in range(N)]
print(c_synthetic_kadomatsu(N, A, B, C, L))

Solution (Python):
n,a,b,c=map(int, input().split())
x=[int(input()) for i in range(n)]
from itertools import product
z=[a,b,c]
d=[0,1,2,3]
ans=10**8
for i in product(d,repeat=n):
    an=0
    y=[[],[],[],[]]
    for j,k in enumerate(i):
        y[k].append(x[j])
    if len(y[1])==0 or len(y[2])==0 or len(y[3])==0:continue
    for k,j in enumerate(y[1:]):
        an+=(len(j)-1)*10+abs(sum(j)-z[k])
    ans=min(an,ans)
print(ans)

Solution (Python):
from itertools import product


def solve(N, A, B, C, Ls):
    ans = 10000
    for p in product("ABCD", repeat=N):
        if "A" not in p or "B" not in p or "C" not in p:
            continue
        As = sum(Ls[i] for i in range(N) if p[i] == "A")
        Bs = sum(Ls[i] for i in range(N) if p[i] == "B")
        Cs = sum(Ls[i] for i in range(N) if p[i] == "C")
        tans = abs(As - A) + abs(Bs - B) + abs(Cs - C) + \
               (p.count("A") - 1) * 10 + (p.count("B") - 1) * 10 + (p.count("C") - 1) * 10
        ans = min(ans, tans)
    return ans

if __name__ == "__main__":
    N, A, B, C = tuple(map(int, input().split(" ")))
    Ls = [int(input()) for _ in range(N)]
    print(solve(N, A, B, C, Ls))

Solution (Python):

from itertools import product
def inpl(): return list(map(int, input().split()))

N, A, B, C = inpl()
L = [int(input()) for _ in range(N)]

ans = 1e9

def calc(Q, D):
    res = 1e9
    if min(Q) >= D:
        return min(Q) - D

    for j in range(1, 2**len(Q)):
        C = [Q[i] for i in range(len(Q)) if (j >> i)&1 == 1]
        S = sum(C)
        tmp = 10*(len(C)-1) + abs(D-S)
        res = min(tmp, res)
    return res


for X in product(range(3), repeat=N):
    P = [[] for _ in range(3)]
    for i, x in enumerate(X):
        P[x].append(L[i])
    if min(map(len, P)) == 0:
        continue
    tmp = 0
    for Q, D in zip(P, [A, B, C]):
        tmp += calc(Q, D)
    if tmp < ans:
        ans = min(tmp, ans)

print(ans)

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

MP = []
for i in range(4**N):
    Alloc = [0,0,0,0,0,0,0,0]
    for j in range(N):
        Alloc[j] = (i//(4**j))%4 
        
    Len = [0,0,0,0]
    Num = [0,0,0,0]
    mp = 0
    for j in range(N): 
        Len[Alloc[j]] += L[j]
        Num[Alloc[j]] += 1
    if Len[1]==0 or Len[2]==0 or Len[3]==0:  
        continue
    else:
        mp += abs(A-Len[1])+abs(B-Len[2])+abs(C-Len[3])+10*(sum(Num[1:])-3)
        MP.append(mp)
print(min(MP))

Solution (Python):



from itertools import product

def main():
  N, A, B, C = map(int, input().strip().split(' '))
  bamboos = [int(input()) for _ in range(N)]
  pattern = list(product(*[[0,1,2,3] for _ in range(N)]))
  score = 1000000000
  for p in pattern:
    _A, _B, _C = 0, 0, 0
    count = -3
    flag_A, flag_B, flag_C = False, False, False
    for i, n in enumerate(p):
      if n == 0:
        _A += bamboos[i]
        flag_A = True
        count += 1
      if n == 1:
        _B += bamboos[i]
        flag_B = True
        count += 1
      if n == 2:
        _C += bamboos[i]
        flag_C = True
        count += 1
    if count < 0 or not all([flag_A, flag_B, flag_C]):
      continue
    _score = (abs(A-_A)+abs(B-_B)+abs(C-_C)) + (10 * count)
    if score > _score:
      score = _score
  print(score)
  pass

if __name__=='__main__':
  main()

Solution (Python):
def btaketolist(btake, N):
    li = []
    for i in range(N):
        t = btake % 4
        li.append(t)
        btake = btake // 4
    return list(reversed(li))


if __name__ == "__main__":
    N, a, b, c = [int(i) for i in input().split()]
    targets = [a, b, c]
    l = [int(input()) for i in range(N)]
    btake = 0
    take = btaketolist(btake, N)

    minimal_cost = 10e9

    for i in range(4 ** N):
        nums = [0, 0, 0]
        lengths = [0, 0, 0]
        for index, t in enumerate(take):
            if t == 3:
                continue
            nums[t] += 1
            lengths[t] += l[index]
        if 0 in nums:
            btake += 1
            take = btaketolist(btake, N)
            continue
        cost = 10 * (sum(nums) - 3) + sum([abs(lengths[i] - targets[i]) for i in range(3)])
        if cost < minimal_cost:
            minimal_cost = cost
        btake += 1
        take = btaketolist(btake, N)
    print(minimal_cost)

Solution (Python):
import itertools
N,A,B,C=[int(i) for i in input().split()]
target=[A,B,C]
L=list()
for i in range(N):
    L.append(int(input()))
min_magic=9999999999999
for pattern in itertools.product([0,1,2,3],repeat=N):
    found=1
    magic= -30
    sum = [0,0,0]
    for j in range(N):
        if pattern[j] != 3:
            sum[pattern[j]] += L[j]
            magic += 10
    for i in range(3):
        if sum[i]==0:
            found=0
            break
        magic+=abs(target[i]-sum[i])
    if found==1:
        min_magic=min(min_magic,magic)

print (min_magic)

Solution (Python):
from itertools import product

N, *ABCs = map(int, input().split())
ls = [int(input()) for _ in range(N)]

ans = float('inf')
for ps in product(range(4), repeat=N):
    cost = 0

    lenBs = [0] * 3
    for i, p in enumerate(ps):
        if p < 3:
            if lenBs[p]:
                cost += 10
            lenBs[p] += ls[i]

    if lenBs[0]*lenBs[1]*lenBs[2] == 0:
        continue

    for ABC, lenB in zip(ABCs, lenBs):
        cost += abs(ABC - lenB)
    ans = min(ans, cost)

print(ans)

Solution (Python):


import itertools


def main():
  n, req_a, req_b, req_c = map(int, input().split())
  reqs = [req_a, req_b, req_c]
  sizes = [int(input()) for _ in range(n)]
  minimum = float('inf')

  for pattern in itertools.product(range(-1, 3), repeat=n):
    if  0 not in pattern or 1 not in pattern or 2 not in pattern:
      continue

    uses = [[], [], []]
    cost = 0

    for s, d in enumerate(pattern):
      if d != -1:
        uses[d].append(sizes[s])

    cost = sum((len(u) - 1) for u in uses) * 10
    uses = [sum(u) for u in uses]
    cost += sum(abs(u - r) for u, r in zip(uses, reqs))

    if cost < minimum:
      minimum = cost

  print(minimum, flush=True)


if __name__ == '__main__':
  main()

Solution (Python):
n, a, b, c = [int(i) for i in input().split(" ")]
l = [0] * n
for i in range(0, n):
    l[i] = int(input())
    
mp_min = 8000

for i in range(0, 4**n):
    ls = [0, 0, 0, 0]
    sc = [0, 0, 0, 0]
    it = i
    for j in range(0, n):
        if ls[it % 4] > 0:
            sc[it % 4] += 1
        ls[it % 4] += l[j]
        it = it // 4
    mp = 10 * (sc[1] + sc[2] + sc[3]) + abs(a - ls[1]) + abs(b - ls[2]) + abs(c - ls[3])
    if mp < mp_min and ls[1] > 0 and ls[2] > 0 and ls[3] > 0:
        mp_min = mp
print(mp_min)