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: Time Limit Exceeded

Solution code:
def c_synthetic_kadomatsu(N, A, B, C, L):
    from itertools import permutations

    ans = float('inf')
    # 竹の並び方を決める
    for perm in permutations(range(N)):
        # 左から竹をj, k, l本取り、それらを別々に合成し、
        # それらの長さと A, B, C とがどれだけ違うかを計算する
        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))

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
import copy
import math
def get_read_func(fileobject):
    if fileobject == None :
        return raw_input
    else:
        return fileobject.readline

def calc(L, nowA, nowB, nowC, nowD, i, j):
    if i == 0:
        nowD += L[j]
    elif i == 1:
        nowA += L[j]
    elif i == 2:
        nowB += L[j]
    elif i == 3:
        nowC += L[j]

    return nowA, nowB, nowC, nowD

def num(i1, i2, i3, i4, i5, i6, i7, i8, t):
    return (i1 == t) + (i2 == t) + (i3 == t) + (i4 == t) + (i5 == t) + (i6 == t) + (i7 == t) + (i8 == t)

def main():
    if len(sys.argv) > 1:
        f = open(sys.argv[1])
    else:
        f = None
    read_func = get_read_func(f);
    input_raw = read_func().strip().split()
    [N, A, B, C] = [int(input_raw[0]), int(input_raw[1]), int(input_raw[2]), int(input_raw[3])]
    L = []
    for i in range(N):
        input_raw = read_func().strip().split()
        L.append(int(input_raw[0]))
    min_MP = sys.maxint
    for i1 in range(0, 4 if N >= 1 else 1):
        for i2 in range(0, 4 if N >= 2 else 1):
            for i3 in range(0, 4 if N >= 3 else 1):
                for i4 in range(0, 4 if N >= 4 else 1):
                    for i5 in range(0, 4 if N >= 5 else 1):
                        for i6 in range(0, 4 if N >= 6 else 1):
                            for i7 in range(0, 4 if N >= 7 else 1):
                                for i8 in range(0, 4 if N >= 8 else 1):
                                    nowA = 0
                                    nowB = 0
                                    nowC = 0
                                    nowD = 0
                                    if N >= 1:
                                        nowA,nowB,nowC,nowD = calc(L, nowA,nowB,nowC,nowD, i1, 0)
                                    if N >= 2:
                                        nowA,nowB,nowC,nowD = calc(L, nowA,nowB,nowC,nowD, i2, 1)
                                    if N >= 3:
                                        nowA,nowB,nowC,nowD = calc(L, nowA,nowB,nowC,nowD, i3, 2)
                                    if N >= 4:
                                        nowA,nowB,nowC,nowD = calc(L, nowA,nowB,nowC,nowD, i4, 3)
                                    if N >= 5:
                                        nowA,nowB,nowC,nowD = calc(L, nowA,nowB,nowC,nowD, i5, 4)
                                    if N >= 6:
                                        nowA,nowB,nowC,nowD = calc(L, nowA,nowB,nowC,nowD, i6, 5)
                                    if N >= 7:
                                        nowA,nowB,nowC,nowD = calc(L, nowA,nowB,nowC,nowD, i7, 6)
                                    if N >= 8:
                                        nowA,nowB,nowC,nowD = calc(L, nowA,nowB,nowC,nowD, i8, 7)

                                    Anum = num(i1,i2,i3,i4,i5,i6,i7,i8,1)
                                    Bnum = num(i1,i2,i3,i4,i5,i6,i7,i8,2)
                                    Cnum = num(i1,i2,i3,i4,i5,i6,i7,i8,3)
                                    if Anum <= 0 or Bnum <= 0 or Cnum <= 0:
                                        continue
                                    MP = (Anum -1) * 10 + abs(nowA - A)
                                    MP += (Bnum - 1) * 10 + abs(nowB - B)
                                    MP += (Cnum - 1) * 10 + abs(nowC - C)
                                    min_MP = min(MP, min_MP)
    print min_MP
##    min_MP = sys.maxint
##    for i in range(N):
##        for j in range(i, N):
##            for k in range(j, N):
##                MP = 0
##                forA = sum(L[i:j])
##                if (j - i) > 1:
##                    MP += 10 * (j - i - 1)
##                MP += abs(A-forA)
##                forB = sum(L[j:k])
##                if (k - j) > 1:
##                    MP += 10 * (k - j - 1)
##                MP += abs(B-forB)
##                forC = sum(L[k:N])
##                if (N - k) > 1:
##                    MP += 10 * (N - k - 1)
##                MP += abs(C-forC)
##                min_MP = min(min_MP, MP)




if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from statistics import mean, median,variance,stdev
import numpy as np
import sys
import math
import fractions
import itertools

def j(q):
    if q==1: print("Heisei")
    else:print("TBD")
    exit(0)


def ct(x,y):
    if (x>y):print("")
    elif (x<y): print("")
    else: print("")

def ip():
    return int(input())

def swap(s,pos):
    s[pos]-=1
    s[pos+1]+=1
    print(s)
    if pos == n-2: return s
    if s[pos+2] == 0: swap(s,pos+1)
    return s


#n = ip()                              #入力整数1つ
#h,w= (int(i) for i in input().split())      #入力整数横2つ
#n,x,y = (int(i) for i in input().split())    #入力整数横3つ
n,a,b,c= (int(i) for i in input().split())  #入力整数横4つ
#a = [int(i) for i in input().split()]        #入力整数配列
#a = input()                                  #入力文字列
#a = input().split()                          #入力文字配列
#n = ip()                      #入力セット(整数改行あり)(1/2)
#a=[ip() for i in range(n)]    #入力セット(整数改行あり)(2/2)

#jの変数はしようできないので注意
#全足しにsum変数使用はsum関数使用できないので注意
l = []
for i in range(n):
    l.append(ip())
if a in l and b in l and c in l:
    print(0)
    exit(0)
l.sort()
req = [a, b,c]
m  =set()
for i in range(n):
    set = [0 for i in range(n)]
    set[0] = -1
    while sum(set) < n*3:
        while sum(set) < n*3:
            d = 0
            set[d]+=1
            while set[d] == 4:
                set[d]=0
                d+=1
                set[d]+=1
            if 0 in set and 1 in set and 2 in set: break
        s = [0,0,0,0]
        mi = 0
        for i in range(n):
            s[set[i]]+= l[i]
        for i in range(3):
            mi += abs(s[i] - req[i]) + (set.count(i)-1) * 10
        m.add(mi)
print(min(m))

Submission status: Time Limit Exceeded

Solution code:
N, *ABC = map(int, input().split())
l = [int(input()) for _ in range(N)]
#print(min(min(func(l, abc)) for abc in [[A,B,C], [A,C,B], [B,A,C], [B,C,A], [C,A,B], [C,B,A]]))

def func(l, ABC, point=0):
    if len(ABC)==0:
        yield point
    else:
        x = ABC[0]
        p = min(abs(x-y) for y in l)
        if x+p in l:
            lc = l.copy()
            lc.remove(x+p)
            yield from func(lc, ABC[1:], point+p)
        if x-p in l:
            lc = l.copy()
            lc.remove(x-p)
            yield from func(lc, ABC[1:], point+p)
from itertools import chain
def func2(l, p, A, B, C):
    # for abc in [[A,B,C], [A,C,B], [B,A,C], [B,C,A], [C,A,B], [C,B,A]]:
    #     print(min(func(l, abc)))
    return min(min(func(l, abc, p)) for abc in [[A,B,C], [A,C,B], [B,A,C], [B,C,A], [C,A,B], [C,B,A]])
def grouping(l, g, h, k):
    if all(len(x)>0 for x in [g, h, k]):
        yield g, h, k
    if len(l)>0:
        a, *l = l
        yield from grouping(l, g+[a], h, k)
        yield from grouping(l, g, h+[a], k)
        yield from grouping(l, g, h, k+[a])
        yield from grouping(l, g, h, k)
def func3(l, ABC):
    for g in grouping(l, [], [], []):
        p = sum(len(gg)-1 for gg in g)*10
        yield func2(list(map(sum, g)), p, *ABC)
print(min(func3(l, ABC)))

Submission status: Time Limit Exceeded

Solution code:
from sys import setrecursionlimit as lim
lim(10**8)

INF = int(1e20)

def solve(s, l):
    if s == []: return 0
    n = len(l)
    a = s[0]
    ss = s[1:]
    ret = INF
    if n == 0: return INF
    else:
        ll = []
        for bit in xrange(1, 1 << n):
            st = ans = 0
            for j in xrange(n):
                if (bit & (1 << j)):
                    st += l[j]
                    ans += 10
                else:
                    ll.append(l[j])
            ans -= 10
            ans += abs(a - st)
            if n > 1:
                ans = ans + solve(ss, ll)
            ret = min(ret, ans)

    return ret

n, a, b, c = map(int, raw_input().strip().split())
l = [0 for i in xrange(n)]
for i in xrange(n): l[i] = input()

ans = solve([a, b, c], l)
ans = min(ans, solve([a, c, b], l))
ans = min(ans, solve([b, a, c], l))
ans = min(ans, solve([b, c, a], l))
ans = min(ans, solve([c, a, b], l))
ans = min(ans, solve([c, b, a], l))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N, A, B, C = map(int, input().split())
ls = adisps = np.array([int(input()) for _ in range(N)])

from itertools import product
import sys

result = sys.maxsize
for pair in product(*([np.arange(4)] * N)):
    pair = np.array(pair)
    if (np.bincount(pair, minlength=3) == 0).any():
        continue
    
    cost1 = np.bincount(pair, weights=ls)[:3].astype(int)
    cost1 = np.abs(cost1 - np.array([A, B, C])).sum()
    cost10 = (np.bincount(pair)[:3] - 1).sum() * 10
    cost = cost1 + cost10
    
    if cost < result:
        result = cost
print(result)

Submission status: Time Limit Exceeded

Solution code:
import sys
import collections
sys.setrecursionlimit(10**4)
n, a, b, c = map(int, input().split())
l = [int(input()) for _ in range(n)]
dq = collections.deque([(list(l), 0)])
while a:
    pv = dq[0][0]
    pc = dq[0][1]
    dq.popleft()
    if pc > 1000:
        continue
    for i in pv:
        if i > 1500:
            continue
    if a in pv and b in pv and c in pv:
        print(pc)
        exit(0)
    for i in range(len(pv)):
        nv = list(pv)
        nv[i] += 1;
        if (nv[i] >= 1000): continue
        dq.append((nv, pc + 1))
    for i in range(len(pv)):
        nv = list(pv)
        if (nv[i] == 0): continue
        nv[i] -= 1;
        dq.append((nv, pc + 1))
    if (len(pv) > 3):
        for i in range(len(pv)):
            for j in range(i + 1, len(pv)):
                nv = list(pv)
                nv[i] += nv[j]
                nv.pop(j)
                dq.append((nv, pc + 10))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N, A, B, C = map(int, input().split())
ls = adisps = np.array([int(input()) for _ in range(N)])

def get_cost(bamboos, mokuhyo):
    return 10 * (len(bamboos) - 1) + np.abs(bamboos.sum() - mokuhyo)

from itertools import product
import sys
result = sys.maxsize
for pair in product(*([np.arange(4)] * N)):
    if (np.bincount(np.array(pair), minlength=3) == 0).any():
        continue
    cost = 0
    for i, mokuhyo in enumerate([A, B, C]):
        bamboos = ls[np.array(pair) == i]
        cost += get_cost(bamboos, mokuhyo)
    if cost < result:
        result = cost
print(result)

Submission status: Time Limit Exceeded

Solution code:
from sys import setrecursionlimit
setrecursionlimit(10 ** 9)

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

INF = 10 ** 9

def dfs(i, L, A):
    if all(a == 0 for a in A):
        return 0
    if n - L.count(0) < 3:
        return INF
    if i == n:
        return INF
    if L[i] == 0:
        return dfs(i+1, L[:], A[:])
    for j, a in enumerate(A):
        if a == L[i]:
            A[j] = 0
            return dfs(i+1, L[:], A[:])

    res = dfs(i+1, L[:], A[:])
    for j, a in enumerate(A):
        if a == 0:
            continue
        TL = L[:]
        TL[i] = a
        TA = A[:]
        TA[j] = 0
        d = abs(L[i] - a)
        res = min(res, dfs(i+1, TL, TA) + d)

    if L[i] > max(A):
        return res
    for j in range(i+1, n):
        if L[j] == 0:
            continue
        TL = L[:]
        TL[i] += TL[j]
        TL[j] = 0
        res = min(res, dfs(i, TL, A[:]) + 10)

    return res

print(dfs(0, L[:], [a, b, c]))

Submission status: Time Limit Exceeded

Solution code:
from statistics import mean, median,variance,stdev
import numpy as np
import sys
import math
import fractions
import itertools

def j(q):
    if q==1: print("Heisei")
    else:print("TBD")
    exit(0)


def ct(x,y):
    if (x>y):print("")
    elif (x<y): print("")
    else: print("")

def ip():
    return int(input())

def swap(s,pos):
    s[pos]-=1
    s[pos+1]+=1
    print(s)
    if pos == n-2: return s
    if s[pos+2] == 0: swap(s,pos+1)
    return s


#n = ip()                              #入力整数1つ
#h,w= (int(i) for i in input().split())      #入力整数横2つ
#n,x,y = (int(i) for i in input().split())    #入力整数横3つ
n,a,b,c= (int(i) for i in input().split())  #入力整数横4つ
#a = [int(i) for i in input().split()]        #入力整数配列
#a = input()                                  #入力文字列
#a = input().split()                          #入力文字配列
#n = ip()                      #入力セット(整数改行あり)(1/2)
#a=[ip() for i in range(n)]    #入力セット(整数改行あり)(2/2)

#jの変数はしようできないので注意
#全足しにsum変数使用はsum関数使用できないので注意
l = []
for i in range(n):
    l.append(ip())
if a in l and b in l and c in l:
    print(0)
    exit(0)
l.sort()
req = [a, b,c]


m  = pow(10,30)
for i in range(n):
    set = [0 for i in range(n)]
    set[0] = -1
    while sum(set) < n*3:
        while sum(set) < n*3:
            d = 0
            set[d]+=1
            while set[d] == 4:
                set[d]=0
                d+=1
                set[d]+=1
            if 0 in set and 1 in set and 2 in set: break
        s = [0,0,0,0]
        mi = 0
        for i in range(n):
            s[set[i]]+= l[i]
        for i in range(3):
            mi += abs(s[i] - req[i]) + (set.count(i)-1) * 10
        m  = min(m,mi)
print(m)

Submission status: Time Limit Exceeded

Solution code:
from sys import setrecursionlimit
setrecursionlimit(10 ** 9)

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

INF = 10 ** 9

def dfs(i, L, A):
    if all(a == 0 for a in A):
        return 0
    if n - L.count(0) < 3:
        return INF
    if i == n:
        return INF
    if L[i] == 0:
        return dfs(i+1, L[:], A[:])
    for j, a in enumerate(A):
        if a == L[i]:
            A[j] = 0
            return dfs(i+1, L[:], A[:])

    res = dfs(i+1, L[:], A[:])
    for j, a in enumerate(A):
        if a == 0:
            continue
        TL = L[:i] + [a] + L[i+1:]
        TA = A[:j] + [0] + A[j+1:]
        d = abs(L[i] - a)
        res = min(res, dfs(i+1, TL, TA) + d)

    for j in range(i+1, n):
        if L[j] == 0:
            continue
        TL = L[:]
        TL[i] += TL[j]
        TL[j] = 0
        res = min(res, dfs(i, TL, A[:]) + 10, dfs(i+1, TL, A[:]) + 10)

    return res

print(dfs(0, L[:], [a, b, c]))

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

import copy

def choose3(bamboos: list, a: int, b: int, c: int):
    bamboos.sort(reverse=True)
    l = len(bamboos)
    minmp = float('inf')
    
    for idx in range(l):
        for jdx in range(idx+1,l):
            for kdx in range(jdx+1,l):
                minmp = min(minmp,
                            abs(bamboos[idx]-a)\
                             + abs(bamboos[jdx]-b)\
                             + abs(bamboos[kdx]-c))
    return minmp


def dfs(bamboos: list, a: int, b: int, c: int, mp: int):

    l = len(bamboos)
    
    if l == 3:
        return mp + choose3(bamboos, a, b, c)
    
    else:
        minmp = mp + choose3(bamboos, a, b, c)
        
        for p1 in range(l):
            for p2 in range(p1+1,l):
                newbamboos = copy.deepcopy(bamboos)
                temp = bamboos[p1] + bamboos[p2]
                newbamboos.remove(bamboos[p1])
                newbamboos.remove(bamboos[p2])
                newbamboos.append(temp)
                
                minmp = min(minmp, dfs(newbamboos, a, b, c, mp+10))
    
        return minmp
    
n,a,b,c = li()
laaa = [ni() for _ in range(n)]

print(dfs(laaa, a, b, c, 0))

Submission status: Time Limit Exceeded

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


import sys
import math

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

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


##llのリストの時の最小MPを返す
# これは愚直に伸び縮みさせる or 任意の2本をくっつけた時の再起関数の値+10の最小
def saiki(ll: []):
    if (len(ll) == 3):
        ll.sort(reverse=True)
        ret = 0
        ret += abs(ll[0] - a)
        ret += abs(ll[1] - b)
        ret += abs(ll[2] - c)
        #print('len ' + str(ll) + ' min ' + str(ret))
        return ret

    ret = 99999999
    ##愚直なやつ
    llen = len(ll)
    for aa in range(llen - 2):
        for bb in range(aa + 1, llen - 1):
            for cc in range(bb + 1, llen):
                ret = min(saiki([ll[aa], ll[bb], ll[cc]]), ret)

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


print(saiki(l))

Submission status: Time Limit Exceeded

Solution code:
def xxx(l,n,a,b,c):
  X=10000
  for i in range(n):
    for j in range(n):
      if j==i: continue
      for k in range(n):
        if k==j or k==i: continue
        x=abs(a-l[i])+abs(b-l[j])+abs(c-l[k])
        if x<X:
          X=x
  return X
import copy
def xx(l,n,a,b,c):
  X=10000
  if n<3:
    return 10000
  else:
    for p in range(n):
      for q in range(n):
        if p!=q:
          ll=copy.deepcopy(l) 
          ll[p]+=ll[q]
          ll.pop(q)
          x=10+xxx(ll,n-1,a,b,c)
          x2=10+xx(ll,n-1,a,b,c)
          if x<X:
            X=x
          if x2<X:
            X=x2
  return X

n,a,b,c=map(int,input().split())
l=[]
for i in range(n):
  l.append(int(input()))
X=xxx(l,n,a,b,c)
if xx(l,n,a,b,c)<X:
  X=xx(l,n,a,b,c)
print(X)

Submission status: Time Limit Exceeded

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

from itertools import permutations


def min_cost(g_list):
    g1, g2, g3 = g_list
    return abs(g1 - A) + abs(g2 - B) + abs(g3 - C)


ans = []
for LL in permutations(L):
    for p1 in range(1, N - 1):
        for p2 in range(p1+1, N):
            for p3 in range(p2 + 1, N+1):
                g1, g2, g3 = sum(LL[:p1]), sum(LL[p1:p2]), sum(LL[p2:p3])
                syn = [len(
                    L[:p1])-1, len(L[p1:p2])-1, len(L[p2:p3])-1]
                # print(g1, g2, g3)
                # print(p1, p2, p3)
                # print(syn)
                ans.append(min_cost([g1, g2, g3]) + sum(syn) * 10)
    # break

print(min(ans))
# print(ans)

Submission status: Time Limit Exceeded

Solution code:
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

        if len(set(a) & set(b)):
            continue

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

            if len(set(a) & set(c)) or len(set(b) & set(c)):
                continue
            res = min(res, cost_a + cost_b + cost_c)

print(res)

Submission status: Time Limit Exceeded

Solution code:
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

        if len(set(a) & set(b)):
            continue

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

            if len(set(a) & set(c)) + len(set(b) & set(c)):
                continue
            res = min(res, cost(A, a) + cost(B, b) + cost(C, c))

print(res)

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations, permutations

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

def f(a):
    s, l, x = a
    return (l-1)*10+abs(s-x)
    

min_num = 10**18
for l in permutations(L):
    # print(l)
    for j1, j2, j3 in combinations(range(N), 3):
        sum_num = sum(map(f, [(sum(l[j1:j2]), j2-j1, A), (sum(l[j2:j3]), j3-j2, B), (sum(l[j3:]), N-j3, C)]))
        # if sum_num < min_num:
            # print(l)
        min_num = min(min_num, sum_num)

print(min_num)

Submission status: Time Limit Exceeded

Solution code:
nums = list(map(int, input().split()))
N, A, B, C = nums[0], nums[1], nums[2], nums[3]
ls = [0 for _ in range(N)]
from itertools import combinations
from copy import deepcopy as copy
for i in range(N):
    ls[i] = int(input())

def solve(arr):
    return_val = 100000000000000000
    sorted_arr = sorted(arr)[::-1]
    for pair in list(combinations(range(len(arr)), 3)):
        val = abs(A-sorted_arr[pair[0]]) + abs(B-sorted_arr[pair[1]]) + abs(C-sorted_arr[pair[2]])
        if val < return_val:
            return_val = val

    if return_val == 0:
        return return_val
    if len(arr) > 3:
        for pair in list(combinations(range(len(arr)), 2)):
            first, second = pair[0], pair[1]
            copy_arr = copy(arr)
            tmp = copy_arr[first]
            del copy_arr[first]
            copy_arr[second-1] += tmp
            val = solve(copy_arr) + 10
            if val < return_val:
                return_val = val
    return return_val

print(solve(ls))

Submission status: Time Limit Exceeded

Solution code:
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:
    for b in P:
        if len(set(a) & set(b)):
            continue
        for c in P:
            if len(set(a) & set(c)) + len(set(b) & set(c)):
                continue
            res = min(res, cost(A, a) + cost(B, b) + cost(C, c))

print(res)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import sys

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

l_list = []
for i in range(N):
    l_list.append(int(input()))
l_list.sort()

MP = float('inf')

for i in range(3,N+1):
    cs = itertools.combinations(range(1,i),2)

    for c in cs: 
        ps = itertools.permutations(l_list,i)
        for p in ps:
            AA = sum(p[:c[0]])
            BB = sum(p[c[0]:c[1]])
            CC = sum(p[c[1]:])
            tmp = abs(AA-A) + abs(BB-B) + abs(CC-C) + (i - 3)*10
            if tmp < MP:
                MP = tmp

print(MP)

Submission status: Time Limit Exceeded

Solution code:
import itertools

def calc(p, c, t):
    aa = p[:c[0]+1]
    bb = p[c[0]+1:c[1]+1]
    cc = p[c[1]+1:c[2]+1]
    res1 = abs(sum(aa) - t[0]) + abs(sum(bb) - t[1]) + abs(sum(cc) - t[2])
    res2 = (len(aa) + len(bb) + len(cc) - 3) * 10
    return res1 + res2

if __name__ == "__main__":
    n, a, b, c = [int(i) for i in input().split(" ")]
    l = []
    for i in range(n):
        l.append(int(input()))
    perms = itertools.permutations(l)
    combs = itertools.combinations(range(n), 3)
    ans = 1<<30
    for p in itertools.permutations(l):
        for co in itertools.combinations(range(n), 3):
            ans = min(ans, calc(p, co, [a,b,c]))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from statistics import mean, median,variance,stdev
import numpy as np
import sys
import math
import fractions
import itertools

def j(q):
    if q==1: print("Heisei")
    else:print("TBD")
    exit(0)


def ct(x,y):
    if (x>y):print("")
    elif (x<y): print("")
    else: print("")

def ip():
    return int(input())

def swap(s,pos):
    s[pos]-=1
    s[pos+1]+=1
    print(s)
    if pos == n-2: return s
    if s[pos+2] == 0: swap(s,pos+1)
    return s


#n = ip()                              #入力整数1つ
#h,w= (int(i) for i in input().split())      #入力整数横2つ
#n,x,y = (int(i) for i in input().split())    #入力整数横3つ
n,a,b,c= (int(i) for i in input().split())  #入力整数横4つ
#a = [int(i) for i in input().split()]        #入力整数配列
#a = input()                                  #入力文字列
#a = input().split()                          #入力文字配列
#n = ip()                      #入力セット(整数改行あり)(1/2)
#a=[ip() for i in range(n)]    #入力セット(整数改行あり)(2/2)

#jの変数はしようできないので注意
#全足しにsum変数使用はsum関数使用できないので注意
l = []
for i in range(n):
    l.append(ip())
if a in l and b in l and c in l:
    print(0)
    exit(0)
l.sort()
"""
req = [a, b,c]
if a in l:
    l.pop(l.index(a))
    req[0] = 0
if a in l:
    l.pop(l.index(b))
    req[1] = 0
if a in l:
    l.pop(l.index(c))
    req[2] = 0
"""
m  = pow(10,30)
for i in range(n):
    set = [0 for i in range(n)]
    set[0] = -1
    while sum(set) < n*3:
        d = 0
        set[d]+=1
        while set[d] == 4:
            set[d]=0
            d+=1
            set[d]+=1
        if 0 in set and 1 in set and 2 in set:
            sa = sum([l[i] for i in range(n) if set[i] == 0])
            sb = sum([l[i] for i in range(n) if set[i] == 1])
            sc = sum([l[i] for i in range(n) if set[i] == 2])
            mi = 0
            mi += abs(sa - a) + (set.count(0)-1) * 10
            mi += abs(sb - b) + (set.count(1)-1) * 10
            mi += abs(sc - c) + (set.count(2)-1) * 10
            m  = min(m,mi)
print(m)

Submission status: Accepted

Solution code:
N, A, B, C = map(int, input().split())
l = [int(input()) for i in range(N)]
 
INF = float('inf')
ans = INF
 
def dfs(a, b, c, n, cost):
    global ans
    if n == N:
        cost += abs(A - a) + abs(B - b) + abs(C - c) - 30 if min(a, b, c) > 0 else INF
        ans = min(ans, cost)
        return
    dfs(a, b, c, n+1, cost)
    dfs(a+l[n], b, c, n+1, cost+10)
    dfs(a, b+l[n], c, n+1, cost+10)
    dfs(a, b, c+l[n], n+1, cost+10)
 
dfs(0, 0, 0, 0, 0)
print(ans)

Submission status: Accepted

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

INF = 10 ** 9

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

    ret1 = dfs(a, b, c, n + 1)
    ret2 = dfs(a + L_list[n], b, c, n + 1) + 10
    ret3 = dfs(a, b + L_list[n], c, n + 1) + 10
    ret4 = dfs(a, b, c + L_list[n], n + 1) + 10
    return min(ret1, ret2, ret3, ret4)


ans = dfs(0, 0, 0, 0)
print(ans)
'''
8 100 90 80
100
100
90
90
90
80
80
80

0


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

243

'''

Submission status: Accepted

Solution code:
import itertools

n, *abc = map(int, input().split())
llst = [int(input()) for _ in range(n)]

ans = 10 ** 10
for abc_lst in itertools.product(range(4), repeat = n):
    tmp = 0
    labc = [[0, 0] for _ in range(3)]
    for i in range(n):
        pos = abc_lst[i]
        if pos == 3:
            continue
        labc[pos][0] += llst[i]
        labc[pos][1] += 1
    if [0, 0] in labc:
        continue
    for i in range(3):
        tmp += abs(abc[i] - labc[i][0])
        tmp += 10 * (labc[i][1] - 1)
    ans = min(ans, tmp)
print(ans)