Problem:


Score : 400 points

Problem Statement

Find the largest integer that can be formed with exactly N matchsticks, under the following conditions:

Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 \leq A_i \leq 9).

The number of matchsticks used to form digits 1, 2, 3, 4, 5, 6, 7, 8, 9 should be 2, 5, 5, 4, 5, 6, 3, 7, 6, respectively.

Constraints

All values in input are integers.

2 \leq N \leq 10^4

1 \leq M \leq 9

1 \leq A_i \leq 9

A_i are all different.

There exists an integer that can be formed by exactly N matchsticks under the conditions.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_M

Output

Print the largest integer that can be formed with exactly N matchsticks under the conditions in the problem statement.

Sample Input 1

20 4
3 7 8 4

Sample Output 1

777773

The integer 777773 can be formed with 3 + 3 + 3 + 3 + 3 + 5 = 20 matchsticks, and this is the largest integer that can be formed by 20 matchsticks under the conditions.

Sample Input 2

101 9
9 8 7 6 5 4 3 2 1

Sample Output 2

71111111111111111111111111111111111111111111111111

The output may not fit into a 64-bit integer type.

Sample Input 3

15 3
5 4 6

Sample Output 3

654



Sample input:
20 4
3 7 8 4


Sample output:
777773

Submission status: Runtime Error

Solution code:
def main():
    N, M = map(int, input().split())

    A = list(map(int, input().split()))  # 使っていい数字

    match_dic = {9: 6, 8: 7, 7: 3, 6: 6, 5: 5, 4: 4, 3: 5, 2: 5, 1: 2}
    available_dic = {k: v for k, v in match_dic.items() if k in A }
    availables = sorted(available_dic.items(), key=lambda x: x[1])

    def dfs(cost, nums):
        if cost == 0:
            nums.sort(key=lambda x: -x)
            return int(''.join(map(str, nums)))

        cand = [dfs(cost - avs[1], nums + [avs[0]]) for avs in availables if cost >= avs[1]]
        if len(cand) == 0:
            return 0
        else:
            return max(dfs(cost - avs[1], nums + [avs[0]]) for avs in availables if cost >= avs[1])

    print(dfs(N, []))


main()

Submission status: Runtime Error

Solution code:
N,M = map(int,input().split())
A = list(map(int,input().split()))
li = [[1,2],[7,3],[4,4],[5,5],[3,5],[2,5],[9,6],[6,6],[8,7]]
use = []
Q = [0]*10
counter = 0
for i in li:
    Flag = False
    if i[0] in A:
        Flag = True
        for j in use:
            if j[1] == i[1]:
                Flag = False
    if Flag:
        use.append(i)
Q[use[0][0]] = (int(N//use[0][1]))
R = N%use[0][1]
while R != 0:
    if Q[use[counter][0]] == 0 or counter >= M-1:
        counter -= 1
    else:
        Q[use[counter][0]] -= 1
        R += use[counter][1]
        counter += 1
        Q[use[counter][0]] = int(R//use[counter][1])
        R = R%use[counter][1]
ans = ''
for i in [9,8,7,6,5,4,3,2,1]:
    ans = ans + str(i)*Q[i]
print(ans)

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
A = list(map(int, input().split()))


def gcd(a, b):
    while b:
        a, b = b, a % b
    return a
def lcm(a, b):
    return a * b // gcd(a, b)

L = [2,5,5,4,5,6,3,7,6]
l_A = [L[A[i] for i in range(len(A))]
c_m = 0
mi = min(l_A)
ma = max(l_A)
if mi == 5:
    c_m = 5
elif mi == 6:
    c_m = 9
else:
    c_m = L.index(mi) + 1

s = list(set(l_A)).sort()

if N % mi == 0:
    print(str(c_m)*(N//mi))

lest = (N % mi) + mi
if lest in l_A:
    lest_c = l_A[l_A.index(lest)]
    if mi < lest_c:
        print(str(lest_c)+str(mi)*((N//mi)-1))
    else:
        print(str(mi)*((N//mi)-1)+str(lest_c))

Submission status: Runtime Error

Solution code:
N,M=map(int,raw_input().split())
A=map(int,raw_input().split())
A.sort(reverse=True)

Num_All={1:2,2:5,3:5,4:4,5:5,6:6,7:3,8:7,9:6}
Num=list(set([Num_All[a] for a in A]))

Num.sort()
Gyaku={n:0 for n in Num}
for a in A:
    if a>Gyaku[Num_All[a]]:
        Gyaku[Num_All[a]]=a


dp=[[0,[]] for i in range(N+1)]


for j in range(len(Num)):
    if dp[Num[j]][0]==0:
        dp[Num[j]]=[1,[[Num[j]]]]
    for i in range(Num[j]+1,N+1):
        if dp[i-Num[j]][0]==0:
            continue
        if dp[i-Num[j]][0]+1>dp[i][0]:
            dp[i]=[dp[i-Num[j]][0]+1,[k+[Num[j]] for k in dp[i-Num[j]][1]]]
        elif dp[i-Num[j]][0]+1==dp[i][0]:
            for k in dp[i-Num[j]][1]:
                dp[i][1].append(k+[Num[j]])
          

Num_koho=dp[N][1]

Koho=[[Gyaku[k] for k in nk] for nk in Num_koho]
mx=0
for k in Koho:
    if mx<max(k):
        Ans_koho=k
        
Ans_koho.sort(reverse=True)

print sum((10**(len(Ans_koho)-i-1))*Ans_koho[i] for i in range(len(Ans_koho)))

Submission status: Runtime Error

Solution code:
from collections import defaultdict
N, _ = map(int, input().split())
A = list(map(int, input().split()))
table = defaultdict(int)
for i, cost in zip(range(1, 10), [2,5,5,4,5,6,3,7,6]):
    if i in A:
        table[cost] = max(table[cost], i)
candy = sorted(table)
res = defaultdict(int)
for k in range(len(candy)):
    bits = 1
    for i in candy[k + 1:]:
        bits = bits | (bits << i)
    for i in range(1, len(format(bits, 'b'))):
        if bits & (1 << i):
            if N - i >= 0 and (N - i) % candy[k] == 0:
                res[table[candy[k]]] = ((N - i) // candy[k])
                N = i
                break
    if N == candy[k]:
        res[table[candy[k]]] = 1
        N = 0
#swap
for _ in range(2):
    for candy1 in candy:
        for candy2 in candy:
            sum1 = candy1 + candy2
            for candy3 in candy:
                for candy4 in candy:
                    sum2 = candy3 + candy4
                    if sum1 == sum2:
                        x = sorted([table[candy1], table[candy2]], reverse=True)
                        y = sorted([table[candy3], table[candy4]], reverse=True)
                        if x < y:
                            a, b = x
                            c, d = y
                            t = min(res[a], res[b])
                            res[a] -= t
                            res[b] -= t
                            res[c] += t
                            res[d] += t
for _ in range(2):
    for candy1 in candy:
        for candy2 in candy:
            for candya in candy:
                sum1 = candy1 + candy2 + candya
                for candy3 in candy:
                    for candy4 in candy:
                        for candyb in candy:
                            sum2 = candy3 + candy4 + candyb
                            if sum1 == sum2:
                                x = sorted([table[candy1], table[candy2], table[candya]], reverse=True)
                                y = sorted([table[candy3], table[candy4], table[candyb]], reverse=True)
                                if x < y:
                                    a, b, ab = x
                                    c, d, cd = y
                                    t = min(res[a], res[b], res[ab])
                                    res[a] -= t
                                    res[b] -= t
                                    res[ab] -= t
                                    res[c] += t
                                    res[d] += t
                                    res[cd] += t
tmp = []
for i, d in res.items():
    tmp += [i] * d
print(''.join(map(str, sorted(tmp, reverse=True))))

Submission status: Runtime Error

Solution code:
Matches = {num: c for num, c in zip([1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 5, 5, 4, 5, 6, 3, 7, 6])}

def psolve(N, digit, Ms):
    if N == 0:
        return digit
    if N < min([m for m in Ms.values()]):
        return -1
    ans = 0
    for (dc, dnum) in [(c, num) for (num, c) in Ms.items()]:
        if digit + str(dnum) > str(dnum) + digit:
            p = psolve(N - dc, digit + str(dnum), Ms)
            if p != -1:
                ans = max(ans, int(p))
        else:
            p = psolve(N - dc, str(dnum) + digit,  Ms)
            if p != -1:
                ans = max(ans, int(p))
    return ans

def solve(N, M, As):
    Ms = {num: c for num, c in Matches.items() if num in As}
    return psolve(N, "", Ms)


if __name__ == "__main__":
    N, M = tuple(map(int, input().split(" ")))
    As = list(map(int, input().split(" ")))
    print(solve(N, M, As))

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
values = list(map(int, input().split()))

count_table = [None, 2,5,5,4,5,6,3,7,6]

dp = [{} for _ in range(n + 1)]
dp[0] = {0: 0}

for i in range(m):
    my_value = values[i]
    for j in range(n):
        dic = dp[j]
        if len(dic) > 0:
            my_count = 1
            while j + count_table[my_value] * my_count <= n:
                already = dp[j + count_table[my_value] * my_count]
                new_dic = {my_value: my_count, **dic}




                s = ''
                for value, cnt in reversed(sorted(already.items())):
                    s += str(value) * cnt
                s_already = s
                s = ''
                for value, cnt in reversed(sorted(new_dic.items())):
                    s += str(value) * cnt

                if s_already == '':
                    dp[j + count_table[my_value] * my_count] = new_dic
                elif s == '':
                    pass
                elif int(s_already) < int(s):
                    dp[j + count_table[my_value] * my_count] = new_dic



                my_count += 1

pin_dic = dp[n]

s = ''
for value, cnt in reversed(sorted(pin_dic.items())):
    s += str(value) * cnt
print(s)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
N, _ = map(int, input().split())
A = list(map(int, input().split()))
table = defaultdict(int)
for i, cost in zip(range(1, 10), [2,5,5,4,5,6,3,7,6]):
    if i in A:
        table[cost] = max(table[cost], i)
candy = sorted(table)
res = defaultdict(int)
for k in range(len(candy)):
    bits = 1
    for i in candy[k + 1:]:
        bits = bits | (bits << i)
    for i in range(1, len(format(bits, 'b'))):
        if bits & (1 << i):
            if N - i >= 0 and (N - i) % candy[k] == 0:
                res[table[candy[k]]] = ((N - i) // candy[k])
                N = i
                break
    if N == candy[k]:
        res[table[candy[k]]] = 1
        N = 0
#swap
for _ in range(2):
    for candy1 in candy:
        for candy2 in candy:
            sum1 = candy1 + candy2
            for candy3 in candy:
                for candy4 in candy:
                    sum2 = candy3 + candy4
                    if sum1 == sum2:
                        x = sorted([table[candy1], table[candy2]], reverse=True)
                        y = sorted([table[candy3], table[candy4]], reverse=True)
                        if x < y:
                            a, b = x
                            c, d = y
                            t = min(res[a], res[b])
                            res[a] -= t
                            res[b] -= t
                            res[c] += t
                            res[d] += t
for _ in range(2):
    for candy1 in candy:
        for candy2 in candy:
            for candya in candy:
            sum1 = candy1 + candy2 + candya
                for candy3 in candy:
                    for candy4 in candy:
                        for candyb in candy:
                            sum2 = candy3 + candy4 + candyb
                            if sum1 == sum2:
                                x = sorted([table[candy1], table[candy2], table[candya]], reverse=True)
                                y = sorted([table[candy3], table[candy4], table[candyb]], reverse=True)
                                if x < y:
                                    a, b, ab = x
                                    c, d, cd = y
                                    t = min(res[a], res[b], res[ab])
                                    res[a] -= t
                                    res[b] -= t
                                    res[ab] -= t
                                    res[c] += t
                                    res[d] += t
                                    res[cd] += t
tmp = []
for i, d in res.items():
    tmp += [i] * d
print(''.join(map(str, sorted(tmp, reverse=True))))

Submission status: Runtime Error

Solution code:
n,m=map(int,input().split())
l=list(map(int,input().split()))
if 1 in l:
  if n%2==0:
    ans='1'*(n/2)
  else:
    if 7 in l:
      ans='7'+'1'*(int(n/2)-1)
    elif 5 in l:
      ans='5'+'1'*(int(n/2)-2)
    elif 3 in l:
      ans='3'+'1'*(int(n/2)-2)
    elif 2 in l:
      ans='2'+'1'*(int(n/2)-2)
    elif 8 in l:
      ans='8'+'1'*(int(n/2)-3)
else:
  ans='0'
print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
N, M = map(int, input().split())
A = [int(i) for i in input().split()]
Match = [2, 5, 5, 4, 5, 6, 3, 7, 6]

MM = []
for i in range(0, M):
    MM.append(Match[A[i] - 1])

MMM = np.array(MM)
MMMM = MMM.argsort()


for i in range(0, N):
    if (N - i) % MMM[MMMM[0]] == 0 and i % MMM[MMMM[1]] == 0:
        print(str(A[MMMM[1]]) * (i // MMM[MMMM[1]]) + str(A[MMMM[0]]) * ((N - i) // MMM[MMMM[0]]))
        sys.exit()

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
A = list(map(int, input().split()))
D = {}
if 1 in A:
    D[2] = '1'
if 7 in A:
    D[3] = '7'
if 4 in A:
    D[4] = '4'
if 2 in A:
    D[5] = '2'
if 3 in A:
    D[5] = '3'
if 5 in A:
    D[5] = '5'
if 6 in A:
    D[6] = '6'
if 9 in A:
    D[6] = '9'
if 8 in A:
    D[8] = '8'

def chmax(s, t):
    s, t = sorted(s, reverse=True), sorted(t, reverse=True)
    return ''.join(max(s, t))

dp = [['' for _ in range(N+1)] for _ in range(5002)]
for n, s in D.items():
    dp[1][n] = s

for i in range(1, 5002):
    for j in range(N+1):
        if dp[i][j] == '':
            continue
        for n, s in D.items():
            if j+n > N:
                continue
            dp[i+1][j+n] = chmax(dp[i+1][j+n], dp[i][j]+s)

for a in dp:
    if a[-1] != '':
        tmp = a[-1]
print(int(tmp))

Submission status: Runtime Error

Solution code:
N,M=list(map(int,input().split()))

A=list(map(int,input().split()))

match_num=[2,5,5,4,5,6,3,7,6]
match_num2=[]
for a in A:
    match_num2.append([match_num[a-1],a])
match_num2=sorted(match_num2,key=lambda x:x[1],reverse=True)
match_num2=sorted(match_num2,key=lambda x:x[0])

most=match_num2[0][1]
dig_num=N//match_num2[0][0]
dig_res=N%match_num2[0][0]

if dig_res==0:
    print(str(most)*dig_num)
else:
    match_num3=[]
    for i in range(M):
        if match_num2[i][0]>match_num2[0][0]:
            match_num3.append(match_num2[i])
    match_num3.append([match_num2[0][0],most])
    l=len(match_num3)
    res_pattern=[]
    min_dig=min(dig_res,dig_num)
    for i in range(l**min_dig):
        res=""
        r=0
        for j in range(min_dig):
            res+=str(match_num3[(i//(l**j))%l][1])
            r+=match_num3[(i//(l**j))%l][0]
        if r-min_dig*match_num2[0][0]==dig_res:
            res_pattern.append(res)
    max_res=0
    for res in res_pattern:
        max_res=max(int(res),max_res)
    ans=""
    flag=True
    for i in range(min_dig):
        if int(str(max_res)[i])<=most and flag:
            ans+=str(most)*(dig_num-min_dig)
            flag=False
        ans+=str(max_res)[i]
    if flag:
        ans+=str(most)*(dig_num-min_dig)
    print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np
import sys

Match = [2, 5, 5, 4, 5, 6, 3, 7, 6]
N, M = map(int, input().split())
A = [int(i) for i in input().split()]

MM = []
for i in range(0, M):
    MM.append(Match[A[i] - 1])

MMM = np.array(MM)
MMMM = MMM.argsort()
print(MM,MMM,MMMM)
print(A[MMMM[0]])

for i in range(0, N):
    if (N - i) % MMM[MMMM[0]] == 0 and i % MMM[MMMM[1]] == 0:
        print(str(A[MMMM[1]]) * (i // MMM[MMMM[1]]) + str(A[MMMM[0]]) * ((N - i) // MMM[MMMM[0]]))
        sys.exit()

Submission status: Runtime Error

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

r = [0, 2, 5, 5, 4, 5, 6, 3, 7, 6]
#    -  1  2  3  4  5  6  7  8  9
memo = {} #  N : int

def main():
    N0, _ = [int(x) for x in input().split()]
    A = [int(x) for x in input().split()]
    #print(N0, A, file=sys.stderr)

    if len(A) == 1:
        a = A[0]
        print(
            "".join(
                [str(a)] * (N0 // r[a])
            )
        )
        return

    def greedy(N): # int -> (int or None)
        if N in memo:
            return memo[N]
        M = 0
        result = None
        for a in A:
            if r[a] > N:
                continue
            elif r[a] == N:
                n = a
            else:
                g = greedy(N - r[a])
                if g is None:
                    continue
                n = int(
                        "".join(sorted(list(str(g)) +[str(a)], reverse=True))
                    )
            if M < n:
                result = n
                M = n
        memo[N] = result
        return result

    answer = greedy(N0)
    print(answer)

main()

Submission status: Runtime Error

Solution code:
from sys import stdin

N, M, *A = map(int, stdin.read().split())
req = {1: 2,
       2: 5,
       3: 5,
       4: 4,
       5: 5,
       6: 6,
       7: 3,
       8: 7,
       9: 6}

num = sorted([(a, req[a]) for a in A], key=lambda x: x[1])
k_min, n_min = num[0]
gt = sorted([(k, n-n_min) for k, n in num if k > k_min],
            key=lambda x: x[0], reverse=True)
lt = sorted([(k, n-n_min) for k, n in num if k < k_min],
            key=lambda x: x[0])
order = N // n_min
sum_rem = N - n_min*order

lst = []
for k, n in gt:
    if sum_rem == 0:
        continue
    m = sum_rem // n
    lst.extend([k]*m)
    sum_rem -= n*m
for k, n in lt:
    if sum_rem == 0:
        continue
    m = sum_rem // n
    lst.extend([k]*m)
    sum_rem -= n*m
lst.extend([k_min]*(order-len(lst)))


print(''.join(map(str, sorted(lst, reverse=True))))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

m = {}
m[1] = 2
m[2] = 5
m[3] = 5
m[4] = 4
m[5] = 5
m[6] = 6
m[7] = 3
m[8] = 7
m[9] = 6


N, M = map(int, input().split())
t = list(map(int, input().split()))
if 3 in t and 2 in t:
    t.remove(2)
if 3 in t and 5 in t:
    t.remove(3)
if 2 in t and 5 in t:
    t.remove(2)
if 6 in t and 9 in t:
    t.remove(6)
A = sorted(t, reverse=True)

matches = [m[v] for v in A]
matches = sorted(matches)
mi = 100
mi_num = 0
for a in A:
    if m[a] < mi:
        mi = m[a]
        mi_num = a
matches.remove(mi)
A.remove(mi_num)

nums = N//mi
r = N - nums*mi

Q = []
Q.append(['', r])
while Q:
    add, r = Q.pop(0)
    #print("add->", add, r)
    if r < 0:
        continue
    elif r == 0:
        cand = []
        for c in add:
            cand.append(int(c))
        cand.append(mi_num)
        cand = sorted(cand, reverse=True)
        l = len(cand)-1
        ans = ''
        for c in cand:
            if c == mi_num:
                ans += str(mi_num)*(nums-l)
            else:
                ans += str(c)
        print(ans)
        exit()
    else:
        r += mi
        for a in A:
            if r-m[a] >= 0:
                Q.append([add+str(a), r-m[a]])
print(1/0)

Submission status: Runtime Error

Solution code:
def mina(t, i, L):
  return True

N, M = list(map(int, input().split()))

A = list(map(int, input().split()))

t = [2, 5, 5, 4, 5, 6, 3, 7, 6]

A.sort(reverse = True)
D = {}
L = []
X = []
for i in A:
  if t[i - 1] not in D:
    D[t[i - 1]] = i
    L.append(t[i - 1])
    X.append([i, t[i - 1]])

L.sort()

Lmin = N // L[0]
Lmod = N % L[0]

F = True
if Lmod != 0:
  while F:
    Lmin -= 1
    Lmod += L[0]
    t = Lmod
    for i in L[1:]:
      if mina(t, i, L[1:]) == True:
        F = False
        break
  
  X.sort(reverse = True)
  for i in X:
    if i != L[0]:
      k = t - i[1]
      if k == 0:
        List = [i[0]]
        break
      elif k > 0:
        for j in X:
          if i != L[0]:
            if k - j[1] == 0:
              List = [i[0], j[0]]
              F = True
              break
        if F:
          break

Ans = [str(D[L[0]]) for i in range(Lmin)]
if Lmod != 0:
  if len(List) == 1:
    if L[0] < List[0]:
      Ans = [str(List[0])] + Ans
    else:
      Ans = Ans + [str(List[0])]
  else:
    List.sort(reverse = True)
    if L[0] > List[0]:
      Ans += [str(List[0]), str(List[1])]
    elif L[0] < List[1]:
      Ans = [str(List[0]), str(List[1])] + Ans
    else:
      Ans = [str(List[0])] + Ans + [str(List[1])]

print("".join(Ans))

Submission status: Runtime Error

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

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

import collections
import math
from functools import reduce

#### START
N,M = map(int,input().split())
A = list(map(int,input().split()))

m_dic ={
  1:2,
  2:5,
  3:5,
  4:4,
  5:5,
  6:6,
  7:3,
  8:7,
  9:6
}

# use_dic = {}

# for A_i in A:
#   use_dic[A_i] = m_dic[A_i]

# sl = sorted(use_dic.items(), key=lambda x: x[1])

# print(sl)
# max_len = int(N/sl[0][1])
# amari = N%sl[0][1]
# print(amari)

ans_d = {}
use_dic = {}

for A_i in A:
  use_dic[A_i] = m_dic[A_i]

sl = sorted(use_dic.items(), key=lambda x: x[1])
# print(sl)
use_m = sl[0]
max_len = int(N/use_m[1])
tmp_use_mk = use_m[0]
tmp_use_m = use_m[1]
amari = N%use_m[1]
# ans = ans + str(use_m[0])*max_len
ans_d[use_m[0]] = max_len
del use_dic[sl[0][0]]

while(amari!=0):
  sl = sorted(use_dic.items(), key=lambda x: x[1])[::-1]
  use_m = sl[0]
  if use_m[1]-tmp_use_m>amari:
    del use_dic[use_m[0]]
    continue
  max_len = int(amari/(use_m[1]-tmp_use_m))
  amari -= max_len*(use_m[1]-tmp_use_m)
  ans_d[tmp_use_mk] -= max_len
  ans_d[use_m[0]] = max_len
  del use_dic[use_m[0]]

k = ""
for i, j in sorted(ans_d.items(), key=lambda x: x[0])[::-1]:
  k = k + str(i)*j
print(k)

Submission status: Runtime Error

Solution code:
import sys

N, M = (int(i) for i in input().split())
A = [int(i) for i in input().split()]
A.sort()
A.reverse()

sys.setrecursionlimit(10000)

num = [0,2,5,5,4,5,6,3,7,6]

A_num = [(num[a], -a) for a in A]
A_num.sort()

min_A = -A_num[0][1]
min_num = A_num[0][0]
keta_max = N//min_num

def solve(d, amari):
    if d == 0 and amari > 0:
        return None
    if amari < 0:
        return None
    elif amari == 0:
        if d == 0:
            return ""
        else:
            return None
    if amari < d*min_num:
        return None
    elif amari == d*min_num:
        return str(min_A) * d
    elif amari < d*(min_num+1):
        new_d = amari - d*min_num
        temp1 = str(min_A) * (d-new_d) + solve(new_d, amari-(d-new_d)*min_num)
        temp2 = solve(new_d, amari-(d-new_d)*min_num) + str(min_A) * (d-new_d)
        if temp1 and temp2:
            if int(temp1) >= int(temp2):
                return temp1
            else:
                return temp2
        else:
            return None
    for a in A:
        temp = solve(d-1, amari-num[a])
        if temp != None:
            return str(a) + temp
    return None
    

for keta in range(keta_max, 0, -1):
    ans = solve(keta, N)
    if ans:
        break
print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

m = {}
m[1] = 2
m[2] = 5
m[3] = 5
m[4] = 4
m[5] = 5
m[6] = 6
m[7] = 3
m[8] = 7
m[9] = 6


N, M = map(int, input().split())
t = list(map(int, input().split()))
if 3 in t and 2 in t:
    t.remove(2)
if 3 in t and 5 in t:
    t.remove(3)
if 2 in t and 5 in t:
    t.remove(2)
if 6 in t and 9 in t:
    t.remove(6)
A = sorted(t, reverse=True)

matches = [m[v] for v in A]
matches = sorted(matches)
mi = 100
mi_num = 0
for a in A:
    if m[a] < mi:
        mi = m[a]
        mi_num = a
matches.remove(mi)
A.remove(mi_num)

nums = N//mi
r = N - nums*mi

Q = []
Q.append(['', r])
while Q:
    add, r = Q.pop(0)
    #print("add->", add, r)
    if r < 0:
        continue
    elif r == 0:
        cand = []
        for c in add:
            cand.append(int(c))
        cand.append(mi_num)
        cand = sorted(cand, reverse=True)
        l = len(cand)-1
        ans = ''
        for c in cand:
            if c == mi_num:
                ans += str(mi_num)*(nums-l)
            else:
                ans += str(c)
        print(ans)
        exit()
    else:
        r += mi
        for a in A:
            Q.append([add+str(a), r-m[a]])
print(1/0)

Submission status: Runtime Error

Solution code:
N,M = map(int,input().split())
A = list(map(int,input().split()))
li = [[1,2],[7,3],[4,4],[5,5],[3,5],[2,5],[9,6],[6,6],[8,7]]
use = []
Q = [0]*10
counter = 0
for i in li:
    if i[0] in A:
        Flag = True
        for j in use:
            if j[1] == i[1]:
                Flag = False
        if Flag:
            use.append(i)
Q[use[0][0]] = (int(N//use[0][1]))
R = N%use[0][1]
while R != 0:
    if Q[use[counter][0]] == 0 or counter >= M-1:
        counter -= 1
    else:
        Q[use[counter][0]] -= 1
        R += use[counter][1]
        counter += 1
        Q[use[counter][0]] = int(R//use[counter][1])
        R = R%use[counter][1]
ans = ''
for i in [9,8,7,6,5,4,3,2,1]:
    ans = ans + str(i)*Q[i]
print(ans)

Submission status: Runtime Error

Solution code:
from sys import stdin

N, M, *A = map(int, stdin.read().split())
req = {1: 2,
       2: 5,
       3: 5,
       4: 4,
       5: 5,
       6: 6,
       7: 3,
       8: 7,
       9: 6}

num = sorted([(a, req[a]) for a in A], key=lambda x: x[1])
k_min, n_min = num[0]
gt = sorted([(k, n-n_min) for k, n in num[1:] if k > k_min],
            key=lambda x: x[0], reverse=True)
lt = sorted([(k, n-n_min) for k, n in num[1:] if k < k_min],
            key=lambda x: x[0])
order = N // n_min
sum_rem = N - n_min*order

lst = []
for k, n in gt:
    if sum_rem == 0:
        continue
    m = sum_rem // n
    lst.extend([k]*m)
    sum_rem -= n*m
for k, n in lt:
    if sum_rem == 0:
        continue
    m = sum_rem // n
    lst.extend([k]*m)
    sum_rem -= n*m
lst.extend([k_min]*(order-len(lst)))


print(''.join(map(str, sorted(lst, reverse=True))))

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
A = list(map(int, input().split()))

costs = [2,5,5,4,5,6,3,7,6,1000]

def main():
    min_a = 10-1
    for a in A:
        if costs[a-1] < costs[min_a-1]:
            min_a = a
    rep = N//costs[min_a-1]
    res = N%costs[min_a-1]
    if res==0:
        print(str(min_a)*rep)
        return

    cands = []
    i = 1
    while costs[min_a-1]*i+res <= 7:
        for a in A:
            if (costs[min_a-1]*i+res) % costs[a-1] == 0:
                cands.append(a)
        if len(cands)>0:
            break
        i += 1
    if len(cands)>0:
        a = max(cands)
        rep = (N-costs[a-1]) // costs[min_a-1]
        if a>min_a:
            print(str(a) + str(min_a)*rep)
            return
        else:
            print(str(min_a)*rep + str(a))
            return
    
    cands = []
    i = 1
    while costs[min_a-1]*i+res <= 14:
        for a0 in A:
            for a1 in A:
                if (costs[min_a-1]*i+res) % (costs[a0-1]+costs[a1-1]) == 0:
                    cands.append(a0*10+a1)
        if len(cands)>0:
            break
        i += 1
    if len(cands)>0:
        a = max(cands)
        a0 = a//10
        a1 = a%10
        rep = (N-costs[a0-1]-costs[a1-1]) // costs[min_a-1]
        if min_a < a1:
            print(str(a0) + str(a1) + str(min_a)*rep)
        elif mina < a0:
            print(str(a0) + str(min_a)*rep + str(a1))
        else:
            print(str(min_a)*rep + str(a0) + str(a1))
        return


main()

Submission status: Runtime Error

Solution code:
from sys import stdin

N, M, *A = map(int, stdin.read().split())
req = {1: 2,
       2: 5,
       3: 5,
       4: 4,
       5: 5,
       6: 6,
       7: 3,
       8: 7,
       9: 6}

num = sorted([(a, req[a]) for a in A], key=lambda x: x[1])
k_min, n_min = num[0]
gt = sorted([(k, n-n_min) for k, n in num[1:] if k > k_min],
            key=lambda x: x[0], reverse=True)
lt = sorted([(k, n-n_min) for k, n in num[1:] if k < k_min],
            key=lambda x: x[0])
order = N // n_min
sum_rem = N - n_min*order

lst = []
for k, n in gt:
    m = sum_rem // n
    lst.extend([k]*m)
    sum_rem -= n*m
for k, n in lt:
    m = sum_rem // n
    lst.extend([k]*m)
    sum_rem -= n*m
lst.extend([k_min]*(order-len(lst)))


print(''.join(map(str, sorted(lst, reverse=True))))

Submission status: Runtime Error

Solution code:
import sys

N, M = (int(i) for i in input().split())
A = [int(i) for i in input().split()]
A.sort()
A.reverse()

sys.setrecursionlimit(10000)

num = [0,2,5,5,4,5,6,3,7,6]

A_num = [(num[a], -a) for a in A]
A_num.sort()

min_A = -A_num[0][1]
min_num = A_num[0][0]
keta_max = N//min_num

def solve(d, amari):
    if amari < 0:
        return None
    elif amari == 0:
        if d == 0:
            return ""
        else:
            return None
    if amari < d*min_num:
        return None
    elif amari == d*min_num:
        return str(min_A) * d
    elif amari < d*(min_num+1):
        new_d = amari - d*min_num
        temp1 = str(min_A) * (d-new_d) + solve(new_d, amari-(d-new_d)*min_num)
        temp2 = solve(new_d, amari-(d-new_d)*min_num) + str(min_A) * (d-new_d)
        if temp1 and temp2:
            if int(temp1) >= int(temp2):
                return temp1
            else:
                return temp2
        else:
            return None
    for a in A:
        temp = solve(d-1, amari-num[a])
        if temp != None:
            return str(a) + temp
    return None
    

for keta in range(keta_max, 0, -1):
    ans = solve(keta, N)
    if ans:
        break
print(ans)

Submission status: Runtime Error

Solution code:
from sys import stdin

N, *A = map(int, stdin.read().split())

A_min = min(A)

k = 1
for i in range(int(A_min**0.5))[::-1]:
    if A_min % (i+1) != 0:
        continue
    k1, k2 = i+1, A_min//(i+1)
    if all(a % k2 == 0 for a in A):
        k = max(k, k2)
    elif all(a % k1 == 0 for a in A):
        k = max(k, k1)

print(k)

# D

from sys import stdin

N, M, *A = map(int, stdin.read().split())
req = {1: 2,
       2: 5,
       3: 5,
       4: 4,
       5: 5,
       6: 6,
       7: 3,
       8: 7,
       9: 6}

num = sorted([(a, req[a]) for a in A], key=lambda x: x[1])
k_min, n_min = num[0]
gt = sorted([(k, n-n_min) for k, n in num[1:] if k > k_min],
            key=lambda x: x[0], reverse=True)
lt = sorted([(k, n-n_min) for k, n in num[1:] if k < k_min],
            key=lambda x: x[0])
order = N // n_min
sum_rem = N - n_min*order

lst = []
for k, n in gt:
    m = sum_rem // n
    lst.extend([k]*m)
    sum_rem -= n*m
for k, n in lt:
    m = sum_rem // n
    lst.extend([k]*m)
    sum_rem -= n*m
lst.extend([k_min]*(order-len(lst)))


print(''.join(map(str, sorted(lst, reverse=True))))