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 itertools
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
def input():
    return sys.stdin.readline().rstrip()

def main():
    N,A,B,C=map(int,input().split())
    l=[int(input()) for _ in range(N)]
    ps=itertools.permutations(l)
    ans=INF
    for p in ps:
        S=[0]*(N+1)
        for i in range(N):
            S[i+1]=S[i]+p[i]
        for i in range(N-2):
            for j in range(N-1-(i+1)):
                for k in range(N-(i+1)-(j+1)):
                    tmp=0
                    a=S[i+1]
                    b=S[i+1+j+1]-S[i+1]
                    c=S[i+1+j+1+k+1]-S[i+1+j+1]
                    tmp=(i+j+k)*10+abs(A-a)+abs(B-b)+abs(C-c)
                    ans=min(ans,tmp)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import itertools
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
def input():
    return sys.stdin.readline().rstrip()

def main():
    N,A,B,C=map(int,input().split())
    l=[int(input()) for _ in range(N)]
    ps=itertools.permutations(l)
    ans=INF
    for p in ps:
        for i in range(N-2):
            for j in range(N-1-(i+1)):
                for k in range(N-(i+1)-(j+1)):
                    tmp=0
                    a=sum(p[:i+1])
                    b=sum(p[i+1:i+1+j+1])
                    c=sum(p[i+1+j+1:i+1+j+1+k+1])
                    tmp=(i+j+k)*10+abs(A-a)+abs(B-b)+abs(C-c)
                    ans=min(ans,tmp)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n,a,b,c=map(int,input().split())
t=[int(input()) for i in range(n)]
def getStatus(num):
  arr=[]
  for i in range(n)[::-1]:
    arr.append(num//(4**i))
    num%=4**i
  return arr
ans=10**10
for i in range(4**n):
  S=getStatus(i)
  L=[0,0,0]
  chk=0
  if 1 not in S or 2 not in S or 3 not in S:continue
  for j in range(n):
    if S[j]==0:continue
    if L[S[j]-1]!=0:chk+=10
    L[S[j]-1]+=t[j]
  chk+=abs(a-L[0])+abs(b-L[1])+abs(c-L[2])
  if chk<ans:ans=chk
print(ans)

Submission status: Accepted

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

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

    memo = 0
    ans = float("inf")

    for a, b, c in list(itertools.permutations([A, B, C], 3)):
        Ncopy = N
        a_cost = float("inf")
        b_cost = float("inf")
        c_cost = float("inf")

        lcopy = copy.deepcopy(l)

        for i in range(1, 2 ** Ncopy):
            tmp = -10
            a_len = 0
            for j in range(Ncopy):
                if i >> j & 1:
                    tmp += 10
                    a_len += lcopy[j]
            tmp += abs(a_len - a)
            a_cost = min(a_cost, tmp)
            if a_cost == tmp:
                memo = i

        for j in range(Ncopy - 1, -1, -1):
            if memo >> j & 1:
                lcopy.pop(j)
                Ncopy -= 1

        for i in range(1, 2 ** Ncopy):
            tmp = -10
            b_len = 0
            for j in range(Ncopy):
                if i >> j & 1:
                    tmp += 10
                    b_len += lcopy[j]
            tmp += abs(b_len - b)
            b_cost = min(b_cost, tmp)
            if b_cost == tmp:
                memo = i

        for j in range(Ncopy - 1, -1, -1):
            if memo >> j & 1:
                lcopy.pop(j)
                Ncopy -= 1


        if len(lcopy) == 0:
            continue


        for i in range(1, 2 ** Ncopy):
            tmp = -10
            c_len = 0
            for j in range(Ncopy):
                if i >> j & 1:
                    tmp += 10
                    c_len += lcopy[j]
            tmp += abs(c_len - c)
            c_cost = min(c_cost, tmp)
            if c_cost == tmp:
                memo = i
        for j in range(Ncopy - 1, -1, -1):
            if memo >> j & 1:
                lcopy.pop(j)
                Ncopy -= 1

        ans = min(ans, a_cost + b_cost + c_cost)


    print(ans)









    

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n, a, b, c = map(int, input().split())
Bmb = [int(input()) for _ in range(n)]
ans = 10**9
for i in range(4**n):
    aa, bb, cc = 0, 0, 0
    cnt = 0
    for j in range(n):
        k = ( i >> (2*j) ) & 3
        if k == 1:
            if aa > 0:
                cnt += 10
            aa += Bmb[j]
        elif k == 2:
            if bb > 0:
                cnt += 10
            bb += Bmb[j]
        elif k == 3:
            if cc > 0:
                cnt += 10
            cc += Bmb[j]
    if aa == 0 or bb == 0 or cc == 0:
        continue
    cnt += abs(a-aa) + abs(b-bb) + abs(c-cc)
    ans = min(ans, cnt)
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N,A,B,C=map(int,input().split())
l=[0]*N
for i in range(N):
    l[i]=int(input())
ans=float("inf")
for i in range(1<<2*N):
    a=[]
    b=[]
    c=[]
    for j in range(0,2*N,2):
        #print(i,j)
        if 1 & i>>j:
            if 1 & i>>(j+1):
                a.append(l[j//2])
            else :
                b.append(l[j//2])
        else:
            if 1 & i>>(j+1):
                c.append(l[j//2])

    #print(a,b,c)
    if len(a)==0 or len(b)==0 or len(c)==0:
        continue
    mp=abs(sum(a)-A)+abs(sum(b)-B)+abs(sum(c)-C)+10*(len(a)+len(b)+len(c)-3)
    ans=min(ans,mp)
print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8

list = [int(i) for i in input().rstrip().split(" ")]

matsu_count = list[0]
require = sorted(list[1:])

matsu_list = sorted([int(input().rstrip()) for i in range(matsu_count)])

def get_mp(matsu:list):
    ans = 0
    for i in range(3):
        ans += abs(matsu[i] - require[i])
    return ans
mp = {}

def get_ans(matsu:list):
    if len(matsu) == 3:
        return get_mp(matsu)
    key = "#".join(map(str, matsu))
    if key in mp:
        return mp[key]
    ans = 80000
    for i in range(len(matsu) - 3 + 1):
        for j in range(i + 1, len(matsu) - 2 + 1):
            for k in range(j + 1, len(matsu) - 1 + 1):
                ans = min(ans, get_mp([matsu[i],matsu[j], matsu[k]]))
    if ans > 0:
        for i in range(len(matsu)):
            for j in range(i + 1, len(matsu)):
                sub_matsu = []
                for k in range(len(matsu)):
                    if k == i or k == j:
                        continue
                    else:
                        sub_matsu.append(matsu[k])
                sub_matsu.append(matsu[i] + matsu[j])
                ans = min(ans, get_ans(sorted(sub_matsu)) + 10)

    mp[key] = ans
    return ans

ans = get_ans(matsu_list)
print(ans)

Submission status: Accepted

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


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

Submission status: Accepted

Solution code:
import itertools


n_bamboo, b1, b2, b3 = [int(i) for i in input().split()]
bamboos = [int(input()) for _ in range(n_bamboo)]

ans = float("inf")
# すべての竹について、b1, b2, b3のどの竹に使うかを列挙
# 0のときはどの竹にも使わない
for bit in itertools.product((0, 1, 2, 3), repeat=n_bamboo):
    l1, l2, l3 = 0, 0, 0
    c1, c2, c3 = 0, 0, 0
    # 選択した竹を足す（2つ目以降はMP10消費）
    for b, bamboo in zip(bit, bamboos):
        if b == 1:
            if l1 > 0:
                c1 += 10
            l1 += bamboo
        elif b == 2:
            if l2 > 0:
                c2 += 10
            l2 += bamboo
        elif b == 3:
            if l3 > 0:
                c3 += 10
            l3 += bamboo
    # 1つも構成する竹がない竹がある場合はスキップ
    if l1 * l2 * l3 == 0:
        continue
    # 延長、短縮のコスト
    c1 += abs(b1 - l1)
    c2 += abs(b2 - l2)
    c3 += abs(b3 - l3)
    # 合計コストが今までより低ければ更新
    ans = min(ans, c1 + c2 + c3)
print(ans)

Submission status: Accepted

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

def dfs(cnt,a,b,c):
  if cnt==n:
    if min(a,b,c)>0:
      return abs(A-a)+abs(B-b)+abs(C-c)-30
    else:
      return  INF
  else:
    res0=dfs(cnt+1,a,b,c)
    res1=dfs(cnt+1,a+L[cnt],b,c)+10
    res2=dfs(cnt+1,a,b+L[cnt],c)+10
    res3=dfs(cnt+1,a,b,c+L[cnt])+10
    return min(res0,res1,res2,res3)

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

Submission status: Accepted

Solution code:
from itertools import product
N, *ABC = map(int, input().split())
L = [int(input()) for _ in range(N)]
ans = float("inf")
for prod in product(range(4), repeat=N):
    abc = [0] * 3
    mp = -30
    for p, l in zip(prod, L):
        if p != 3:
            abc[p] += l
            mp += 10
    if abc[0] and abc[1] and abc[2]:
        mp += sum(map(lambda x,y: abs(x-y), ABC, abc))
        ans = min(ans, mp)
print(ans)

Submission status: Accepted

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


ans = 10000
for x in itertools.product(range(4), repeat=N):
    a, b, c, mp = 0, 0, 0, 0
    for i in range(N):
        if x[i] == 1:
            if a != 0:
                mp += 10
            a += L[i]

        if x[i] == 2:
            if b != 0:
                mp += 10
            b += L[i]

        if x[i] == 3:
            if c != 0:
                mp += 10
            c += L[i]

    if a == 0 or b == 0 or c == 0:
        continue

    mp += abs(A-a)+abs(B-b)+abs(C-c)
    ans = min(ans, mp)
print(ans)

Submission status: Accepted

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

ans = 10**18
for pattern in itertools.product(range(4), repeat=n):
    MP = 0
    take = [0] * 3
    for index, length in zip(pattern, L):
        if index == 3:
            continue
        if take[index] != 0:
            MP += 10
        take[index] += length

    if take[0] == 0 or take[1] == 0 or take[2] == 0:
        continue

    MP += abs(a - take[0])
    MP += abs(b - take[1])
    MP += abs(c - take[2])

    ans = min(ans, MP)

print(ans)

Submission status: Accepted

Solution code:
from itertools import product

N,*T = map(int,input().split())
L = [int(input()) for i in range(N)]
ans = 3000

for x in product([0,1,2,3], repeat=N):
    cost = 0
    l = [0]*4
    for i,v in enumerate(x):
        l[v] += L[i]
        if v<3:
            cost += 10

    if 0 in l[:3]:
        continue
    cost -= 30
    for i in range(3):
        cost += abs(l[i]-T[i])
    ans = min(ans, cost)

print(ans)

Submission status: Accepted

Solution code:
N,*T = map(int,input().split())
L = [int(input()) for i in range(N)]
ans = 3000

for x in range(4**N):
    l = [0]*4
    t = [0]*4
    n = 4
    i = 0

    for i in range(N):
        l[x%n] += L[i]
        t[x%n] += 1
        x//=n

    if 0 in l[:3]:
        continue
    cost = 0
    for i in range(3):
        cost += (t[i]-1)*10
        cost += abs(l[i]-T[i])
    ans = min(ans, cost)

print(ans)

Submission status: Accepted

Solution code:
n,a,b,c=[int(i) for i in input().split()]
l = [int(input()) for _ in range(n)]
INF=10**9

def dfs(times,A,B,C):
    if times==n:
        return abs(A-a)+abs(B-b)+abs(C-c)- 30 if min(A,B,C)>0 else INF
    non_ans=dfs(times+1,A,B,C)
    a_ans=dfs(times+1,A+l[times],B,C)+10
    b_ans=dfs(times+1,A,B+l[times],C)+10
    c_ans=dfs(times+1,A,B,C+l[times])+10
    return min(non_ans,a_ans,b_ans,c_ans)

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N,A,B,C=map(int,input().rstrip().split())
l=[int(input().rstrip()) for _ in range(N)]
inf=10**9+7
def resolve():
    print(rect(0,0,0,0))

def rect(i,a,b,c):
    if i==N:
        if(a==0 or b==0 or c==0):
            return inf
        return abs(A-a)+abs(B-b)+abs(C-c)



    ans=rect(i+1,a,b,c)

    costa=10 if a!=0 else 0
    costb=10 if b!=0 else 0
    costc=10 if c!=0 else 0

    ans=min(ans,rect(i+1,a+l[i],b,c)+costa)
    ans=min(ans,rect(i+1,a,b+l[i],c)+costb)
    ans=min(ans,rect(i+1,a,b,c+l[i])+costc)


    return ans


import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """5 100 90 80
98
40
30
21
80"""
        output = """23"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """8 100 90 80
100
100
90
90
90
80
80
80"""
        output = """0"""
        self.assertIO(input, output)
    def test_入力例_3(self):
        input = """8 1000 800 100
300
333
400
444
500
555
600
666"""
        output = """243"""
        self.assertIO(input, output)

if __name__ == "__main__":
    #unittest.main()
    resolve()

Submission status: Accepted

Solution code:
import itertools
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353


N, A, B, C = list(map(int, sys.stdin.buffer.readline().split()))
L = [int(sys.stdin.buffer.readline()) for _ in range(N)]

# 4**8=65536 通り全部試す
ans = INF
for choices in itertools.product(range(4), repeat=N):
    a = []
    b = []
    c = []

    for i, choice in enumerate(choices):
        if choice:
            [a, b, c][choice - 1].append(L[i])

    if a and b and c:
        mp = 0
        mp += (len(a) - 1) * 10 + abs(A - sum(a))
        mp += (len(b) - 1) * 10 + abs(B - sum(b))
        mp += (len(c) - 1) * 10 + abs(C - sum(c))
        ans = min(mp, ans)
print(ans)

Submission status: Accepted

Solution code:
n, a, b, c = [int(it) for it in input().split()]
ls = [int(input()) for it in range(n)]
def dfs(cur, tmpA, tmpB, tmpC):
    if cur == n:
        return abs(a - tmpA) + abs(b - tmpB) + abs(c - tmpC) if tmpA > 0 and tmpB > 0 and tmpC else 10**20
    return min(
        dfs(cur + 1, tmpA + ls[cur], tmpB, tmpC) + (10 if tmpA > 0 else 0),
        dfs(cur + 1, tmpA, tmpB + ls[cur], tmpC) + (10 if tmpB > 0 else 0),
        dfs(cur + 1, tmpA, tmpB, tmpC + ls[cur]) + (10 if tmpC > 0 else 0),
        dfs(cur + 1, tmpA, tmpB, tmpC)
    )

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

Submission status: Accepted

Solution code:
import random as rng
import itertools as it
import collections as col
import heapq as hq
import sys
import copy as cp
sys.setrecursionlimit(10**9)


def dump_impl(*objects):
    print(*objects, file=sys.stderr)


def dump_dummy(*objects):
    pass


dump = dump_impl if "DEBUG" in sys.argv else dump_dummy

N, A, B, C = map(int, input().split())
l = [int(input()) for i in range(N)]
ans = 10**20
for use in it.product({0, 1, 2, 3}, repeat=N):
    ABC = {0: [], 1: [], 2: [], 3: []}
    for i, u in enumerate(use):
        dump(i, u, use)
        ABC[u].append(l[i])
    if any([len(ABC[u]) == 0 for u in {1, 2, 3}]):
        continue
    ans = min(ans, sum([abs(sum(ABC[i]) - x) + (len(ABC[i]) - 1)
                        * 10 for i, x in zip([1, 2, 3], [A, B, C])]))
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import Counter
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

n, *abc = map(int, readline().split())
lst = list(map(int, read().split()))
s = 10 ** 9 + 7
for i in range(4 ** n):
  tlst = [0] * n
  ti = i
  for j in range(n):
    tlst[j] = ti % 4
    ti //= 4
  c = Counter(tlst)
  if not (c[1] and c[2] and c[3]):
    continue
  else:
    cost = [0] * 3
    for idx, j in enumerate(tlst):
      if j == 0:
        continue
      cost[j - 1] += lst[idx]
    s = min(s, sum(abs(cost[j] - abc[j]) + 10 * (c[j + 1] - 1) for j in range(3)))
print(s)

Submission status: Accepted

Solution code:
N, A, B, C, *l = map(int, open(0).read().split())
ans = 10 ** 9


def dfs(a, b, c, cur, cost):
    if cur == N:
        if not a or not b or not c:
            return
        global ans
        ans = min(ans, abs(a - A) + abs(b - B) + abs(c - C) + cost - 30)
    else:
        dfs(a, b, c, cur + 1, cost)
        dfs(a + l[cur], b, c, cur + 1, cost + 10)
        dfs(a, b + l[cur], c, cur + 1, cost + 10)
        dfs(a, b, c + l[cur], cur + 1, cost + 10)


def solve():
    dfs(0, 0, 0, 0, 0)
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import itertools

def solve(N: int, A: int, B: int, C: int, l: "List[int]"):
    # 0: 使わない 1:A 2:B 3:C
    all = list(itertools.product([0,1,2,3], repeat=N))
    answer = 10**9
    for a in all:
        a_sum = 0
        a_count = 0
        b_sum = 0
        b_count = 0
        c_sum = 0
        c_count = 0

        for i in range(len(a)):
            if a[i] == 0:
                continue
            elif a[i] == 1:
                a_sum += l[i]
                a_count +=1
            elif a[i] == 2:
                b_sum += l[i]
                b_count +=1
            elif a[i] == 3:
                c_sum += l[i]
                c_count +=1
        
        if a_count == 0 or b_count == 0 or c_count==0 :
            continue

        MP = (a_count-1)*10+(b_count-1)*10+(c_count-1)*10+abs(A-a_sum)+abs(B-b_sum)+abs(C-c_sum)

        answer = min(MP,answer)
    print(answer)
    return


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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

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

L = [int(input()) for i in range(N)]
inf = 99999999999

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

  a_pattern = dfs(cursor+1, a + L[cursor], b, c) + 10
  b_pattern = dfs(cursor+1, a, b + L[cursor], c) + 10
  c_pattern = dfs(cursor+1, a, b, c + L[cursor]) + 10
  no_pattern = dfs(cursor+1, a, b, c)
  return min(a_pattern, b_pattern, c_pattern, no_pattern)


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

Submission status: Accepted

Solution code:
n,A,B,C = map(int,input().split())
l = list(int(input())for _ in range(n))
def dfs(depth,a,b,c):
    if depth == n:
        return abs(a-A)+abs(b-B)+abs(c-C)-30  if min(a,b,c) >0 else 10**9
    x = dfs(depth+1,a,b,c)
    y = dfs(depth+1,a+l[depth],b,c) +10
    z = dfs(depth+1,a,b+l[depth],c) +10
    w = dfs(depth+1,a,b,c+l[depth]) +10
    return min(x,y,z,w)
print(dfs(0,0,0,0))

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
import sys
from copy import copy
sys.setrecursionlimit(10**7)

n, a, b, c = map(int, input().split())
k = sorted([a, b, c])
l = [int(input()) for _ in range(n)]
ans = float("inf")

def dfs(i, num, nk):
    global ans
    if i == n:
        if not all(nk): return
        nk.sort()
        cost = (num - 3) * 10
        for j in range(3): cost += abs(k[j] - nk[j])
        ans = min(ans, cost)
        return
    
    nxt = l[i]
    dfs(i+1, num, nk)
    for j in range(3):
        nnk = copy(nk)
        nnk[j] += nxt
        dfs(i+1, num+1, nnk)

dfs(0, 0, [0] * 3)
print(ans)

Submission status: Accepted

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

def rec(i: int, a: int, b: int, c: int) -> int:
    if i == n:
        if a == 0 or b == 0 or c == 0:
            return float("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) + (0 if a == 0 else 10))
    res = min(res, rec(i+1, a, b+l[i], c) + (0 if b == 0 else 10))
    res = min(res, rec(i+1, a, b, c+l[i]) + (0 if c == 0 else 10))

    return res

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

Submission status: Accepted

Solution code:
n,a,b,c=[int(i) for i in input().split()]
ts = [a,b,c]
ls = []
for _ in range(n):
    ls.append(int(input()))
r = 10**18
for i in range(4**n):
    xs = [[] for _ in range(4)]
    for j in range(n):
        k, i = i%4, i//4
        xs[k].append(ls[j])
    ir = 0
    for l in range(3):
        if len(xs[l]) == 0:
            ir = 10 ** 18
            break
        ir += 10*(len(xs[l])-1) + abs(ts[l]-sum(xs[l]))
    r = min(r, ir)
print(r)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)

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

Submission status: Accepted

Solution code:
from itertools import combinations, permutations


def f(x, lst, rem):
    c = int(1e9+7)
    tpl = ()
    for v in range(len(lst) - rem + 1):
        for t in combinations(lst, v + 1):
            if abs(x - sum(t)) + 10 * v < c:
                c = abs(x - sum(t)) + 10 * v
                tpl = t
    for v in tpl:
        lst.remove(v)
    return c, lst


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

    ans = int(1e9+7)
    for ABC in permutations((A, B, C), 3):
        lst = L[:]
        accum = 0
        for i, v in enumerate(ABC):
            c, lst = f(v, lst, 3 - i)
            accum += c
        ans = min(ans, accum)
    print(ans)


main()

Submission status: Accepted

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

ans = 100000000
for i in itertools.product([0, 1, 2, 3], repeat = n):
    x = 0
    y = 0
    z = 0
    for j in range(n):
        if i[j] == 1:
            x += take[j]
        elif i[j] == 2:
            y += take[j]
        elif i[j] == 3:
            z += take[j]

    if x * y * z == 0:
        continue

    x, y, z = sorted([x, y, z], reverse = True)
    tmp = 0
    tmp += (i.count(1) + i.count(2) + i.count(3) - 3)*10
    tmp += abs(x-a) + abs(y-b) + abs(z-c)
    ans = min(ans, tmp)

print(ans)

Submission status: Accepted

Solution code:
N,A,B,C = map(int,input().split())
L = [int(input()) for _ in range(N)]
INF = 10 ** 9
def dfs(depth,a,b,c):
  if depth == N:
    return abs(a - A) + abs(b - B) + abs(c - C) if min(a,b,c) > 0 else INF
  ret0 = dfs(depth+1,a,b,c)
  # 最初の一本目は合体コストがないことに注意する
  ret1 = dfs(depth+1,a+L[depth],b,c) + 10 if a else dfs(depth+1,a+L[depth],b,c)
  ret2 = dfs(depth+1,a,b+L[depth],c) + 10 if b else dfs(depth+1,a,b+L[depth],c)
  ret3 = dfs(depth+1,a,b,c+L[depth]) + 10 if c else dfs(depth+1,a,b,c+L[depth])
  return min(ret0,ret1,ret2,ret3)
print(dfs(0,0,0,0))

Submission status: Accepted

Solution code:
from itertools import combinations, permutations


def f(x, lst, rem):
    d = int(1e9+7)
    tpl = ()
    for v in range(len(lst) - rem + 1):
        for t in combinations(lst, v + 1):
            if abs(x - sum(t)) + 10 * v < d:
                d = abs(x - sum(t)) + 10 * v
                tpl = t
    for v in tpl:
        lst.remove(v)
    return d, lst


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

    ans = int(1e9+7)
    for ABC in permutations((A, B, C), 3):
        lst = L[:]
        accum = 0
        for i, v in enumerate(ABC):
            d, lst = f(v, lst, 3 - i)
            accum += d
        ans = min(ans, accum)
    print(ans)


main()

Submission status: Accepted

Solution code:
from itertools import combinations
from itertools import permutations


def f(x, lst, rem):
    d = int(1e9+7)
    tpl = ()
    for v in range(len(lst) - rem + 1):
        for t in combinations(lst, v + 1):
            if abs(x - sum(t)) + 10 * v < d:
                d = abs(x - sum(t)) + 10 * v
                tpl = t
    for v in tpl:
        lst.remove(v)
    return d, lst


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

    ans = int(1e9+7)
    for ABC in permutations((A, B, C), 3):
        lst = L[:]
        accum = 0
        for i, v in enumerate(ABC):
            d, lst = f(v, lst, 3 - i)
            accum += d
        ans = min(ans, accum)
    print(ans)


main()

Submission status: Accepted

Solution code:
from itertools import combinations
from itertools import permutations


def f(x, lst, rem):
    d = abs(x - min(lst))
    min_lst = min(lst)
    tpl = None
    for v in range(len(lst) - rem + 1):
        for t in combinations(lst, v + 1):
            if abs(x - sum(t)) + 10 * v < d:
                d = abs(x - sum(t)) + 10 * v
                tpl = t
    if tpl is None:
        lst.remove(min_lst)
    else:
        for v in tpl:
            lst.remove(v)
    return d, lst


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

    ans = int(1e9+7)
    for ABC in permutations((A, B, C), 3):
        lst = L[:]
        accum = 0
        for i, v in enumerate(ABC):
            d, lst = f(v, lst, 3 - i)
            accum += d
        ans = min(ans, accum)
    print(ans)


main()

Submission status: Accepted

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


def dfs(cur, a, b, c):
    if cur == N:
        return abs(a - A) + abs(b - B) + abs(c - C) - 30\
            if 0 < min(a, b, c) else int(1e9+7)

    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
    ret4 = dfs(cur + 1, a, b, c)

    return min(ret1, ret2, ret3, ret4)


def main():
    print(dfs(0, 0, 0, 0))


main()

Submission status: Accepted

Solution code:
def dfs(cur, a, b, c):
    if cur == N:
        return abs(a - A) + abs(b - B) + abs(c - C) - 30\
            if 0 < min(a, b, c) else int(1e9+7)

    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
    ret4 = dfs(cur + 1, a, b, c)

    return min(ret1, ret2, ret3, ret4)


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

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

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

Submission status: Accepted

Solution code:
from itertools import combinations
from itertools import permutations


def f(x, lst, rem):
    d = abs(x - min(lst))
    min_lst = min(lst)
    tpl = None
    for v in range(1, len(lst) - rem + 2):
        for t in combinations(lst, v):
            if abs(x - sum(t)) + 10 * (v - 1) < d:
                d = abs(x - sum(t)) + 10 * (v - 1)
                tpl = t
    if tpl is None:
        lst.remove(min_lst)
    else:
        for v in tpl:
            lst.remove(v)
    return d, lst


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

    ans = int(1e9+7)
    for ABC in permutations((A, B, C), 3):
        lst = L[:]
        accum = 0
        for i, v in enumerate(ABC):
            d, lst = f(v, lst, 3 - i)
            accum += d
        ans = min(ans, accum)
    print(ans)


main()

Submission status: Accepted

Solution code:
from itertools import combinations
from itertools import permutations


def f(x, lst, rem):
    d = abs(x - min(lst))
    min_lst = min(lst)
    tpl = None
    for v in range(1, len(lst) - rem + 2):
        for t in combinations(lst, v):
            if abs(x - sum(t)) + 10 * (v - 1) < d:
                d = abs(x - sum(t)) + 10 * (v - 1)
                tpl = t
    if tpl is None:
        lst.remove(min_lst)
    else:
        for v in tpl:
            lst.remove(v)
    return d, lst


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

    ans = int(1e9+7)
    for ABC in permutations((A, B, C), 3):
        lst = L[:]
        accum = 0
        for i, v in enumerate(ABC):
            d, lst = f(v, lst, 3 - i)
            accum += d
        ans = min(ans, accum)
    print(ans)


main()

Submission status: Accepted

Solution code:
N,A,B,C=map(int,input().split())
l = [int(input()) for i in range(N)]
def dfs(cur,a,b,c):
  if cur==N:
    if min(a,b,c)>0:
      return abs(A-a)+abs(B-b)+abs(C-c)-30
    else:
      return float("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))