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:
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(5001)]
for n, s in D.items():
    dp[1][n] = s

for i in range(1, 5001):
    for j in range(0, 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:
from operator import itemgetter
N, M = map(int, input().split())
A = list(map(int, input().split()))
B = [None, 2, 5, 5, 4, 5, 6, 3, 7, 6]
D = []
set_D = set()
A.sort(reverse=True)
for a in A:
    if B[a] in set_D:
        continue
    else:
        set_D.add(B[a])
        D.append([a, B[a]])

D.sort(key=itemgetter(0), reverse=True)
dp = [-10**10]*(N+1)
dp[0] = 0
for i in range(1, N+1):
    for elem in set_D:
        if i < elem or dp[i-elem] is None:
            continue
        dp[i] = max(dp[i], dp[i-elem]+1)
ans = ''
while N > 0:
    for i in range(len(D)):
        if dp[N-D[i][1]] == dp[N]-1:
            ans += str(D[i][0])
            N -= D[i][1]
            break
print(ans)

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
Costs = {1: 2, 2: 5, 3: 5, 4: 4, 5: 5, 6: 6, 7: 3, 8: 7, 9: 6}
A = sorted(list(map(int, input().split())), reverse=True)  # 大きい順に


# dp[i]:= マッチ棒をn本使って得られる最大桁数(-infはマッチ棒が使いきれないことを表す)
dp = [-float('inf')] * (N + 1)
dp[0] = 0

# 蟻本P.60みたいなことをします
for i in range(M):
    cost = Costs[A[i]]
    for j in range(N + 1):
        if cost > j:
            continue
        dp[j] = max(dp[j], dp[j - cost] + 1)


# dpの復元
ans = ""
marker = N  # いま何本残っているか
while dp[marker] > 0:  # 0本になるまで回す
    for a in A:  # 大きな数字から見ていく
        cost = Costs[a]
        # marker本ある状態から、マッチ棒をcost本使う数字aを使わなければ、marker本使った場合の桁数-1になる場合、
        # 数字aを使ったことがわかる
        if dp[marker - cost] == dp[marker] - 1:
            ans += str(a)
            marker = marker - cost
            break

print(ans)

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
Costs = {1: 2, 2: 5, 3: 5, 4: 4, 5: 5, 6: 6, 7: 3, 8: 7, 9: 6}
A = sorted(list(map(int, input().split())), reverse=True)  # 大きい順に


# dp[i]:= マッチ棒をn本使って得られる最大桁数(-infはマッチ棒が使いきれないことを表す)
dp = [-float('inf')] * (N + 1)
dp[0] = 0

# 蟻本P.60みたいなことをします
for i in range(M):
    cost = Costs[A[i]]
    for j in range(N + 1):
        if cost > j:
            continue
        dp[j] = max(dp[j], dp[j - cost] + 1)


# dpの復元
ans = ""
marker = N  # いま何本残っているか
while dp[marker]:  # 0本になるまで回す
    for a in A:  # 大きな数字から見ていく
        cost = Costs[a]
        # marker本ある状態から、マッチ棒をcost本使う数字aを使わなければ、marker本使った場合の桁数-1になる場合、
        # 数字aを使ったことがわかる
        if dp[marker - cost] == dp[marker] - 1:
            ans += str(a)
            marker = marker - cost
            break

print(ans)

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

mini = min(D.keys())
maxi = max(D.keys())

for i in range(1, 5002):
    for j in range(mini*(i+1), N+1):
        if dp[i][j] == '':
            break
        for n, s in D.items():
            if j+n > N or j+n > mini*(i+1) + maxi:
                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:
L = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]

N, M = map(int, input().split())
A = [int(a) for a in input().split()]
B = [(A[i], L[A[i]]) for i in range(M)]

X = [0] + ([-1] * N)
for i in range(1, N+1):
  for b in B:
    X[i] = max(X[i], X[i-b[1]] * 10 + b[0])

print(X[N])

Submission status: Runtime Error

Solution code:
INF = 10**10
arr = [10,2,5,5,4,5,6,3,7,6]
N,M = map(int,input().split())
src = sorted(list(map(int,input().split())))

dp = [-INF]*(N+1)
dp[0] = 0
for i in range(N):
    for j in src:
        if i + arr[j] <= N:
            dp[i+arr[j]] = max(dp[i+arr[j]],dp[i] + 1)
dim = dp[N]
ans  = ''
while(dim > 0):
    for i in src[::-1]:
        if dp[N-arr[i]] + 1 == dp[N]:
            ans += str(i)
            N -= arr[i]
            dim -= 1
            break
print(ans)

Submission status: Runtime Error

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

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

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

for a in A:
  _dict[num_matches[a]]=_dict.get(num_matches[a],[]) + [a]

#print(_dict)

memo = [None for _ in range(N+1)] # return memo[N]
# Nほんのマッチを使って作れる整数の最大値．（作れなければ0）

def max_int_with_match(n):
  if memo[n]:
    return memo[n]
  
  if n < min(_dict.keys()):
    memo[n] = 0
    return memo[n]
  
  memo[n] = max(max(_dict.get(n, [0])),
                max(list(map(lambda x: max(_dict[x]) + 10 * max_int_with_match(n-x),
                        list(filter(lambda x: x<n, _dict.keys()))
                       ))+[0]
                   )
               )
  return memo[n]


print(max_int_with_match(N))
#print(memo)

Submission status: Runtime Error

Solution code:
#!/mnt/c/Users/moiki/bash/env/bin/python
from itertools import permutations
N,M = map(int, input().split())
cost = [0,2,5,5,4,5,6,3,7,6]
A = list(map(int, input().split()))

p = []
for a in A:
    p.append( (cost[a], a) )
costp = sorted(p)


costX = [ z[0] for z in costp]
A = [ z[1] for z in costp]

dp = [""] * (N+1)

for c,a in zip(costX,A):
    i =N 
    dp[i-c] = str(a)

for i in range(N-1, 1, -1):
    if len(dp[i]) == 0:
        continue
    
    for c,a in zip(costX,A):
        for p in permutations( [dp[i], str(a)]):
            if i-c >= 0:
                if dp[i-c] == "":
                    dp[i-c] = str(int( "".join(p)))
                else:
                    dp[i-c] = str(max(int(dp[i-c]), int( "".join(p))))
    
print(dp[0])

Submission status: Runtime Error

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

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

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

for a in A:
  _dict[num_matches[a]]=_dict.get(num_matches[a],[]) + [a]

#print(_dict)

memo = [None for _ in range(N+1)] # return memo[N]
# Nほんのマッチを使って作れる整数の最大値．（作れなければ0）

def max_int_with_match(n):
  if memo[n]:
    return memo[n]
  
  if n < min(_dict.keys()):
    memo[n] = 0
    return memo[n]
  
  memo[n] = max(max(_dict.get(n, [0])),
                max(map(lambda x: max(_dict[x]) + 10 * max_int_with_match(n-x),
                        list(filter(lambda x: x<n, _dict.keys()))
                       )
                   )
               )
  return memo[n]


print(max_int_with_match(N))
#print(memo)

Submission status: Runtime Error

Solution code:
INF = 10**10
arr = [10,2,5,5,4,5,6,3,7,6]
N,M = map(int,input().split())
src = sorted(list(map(int,input().split())),key = lambda x:arr[x])

dp = [-INF]*(N+1)
dp[0] = 0
for i in range(N+1):
    for j in src:
        if i + arr[j] <= N:
            dp[i+arr[j]] = max(dp[i+arr[j]],dp[i] + 1)
dim = dp[N]
ans  = ''
while(dim > 0):
    for i in src[::-1]:
        if dp[N-arr[i]] + 1 == dp[N]:
            ans += str(i)
            N -= arr[i]
            dim -= 1
            break
print(ans)

Submission status: Runtime Error

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

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

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

for a in A:
  _dict[num_matches[a]]=_dict.get(num_matches[a],[]) + [a]

#print(_dict)

memo = [None for _ in range(N+1)] # return memo[N]
# Nほんのマッチを使って作れる整数の最大値．（作れなければ0）

def max_int_with_match(n):
  if memo[n]:
    return memo[n]
  
  if n < min(_dict.keys()):
    memo[n] = 0
    return memo[n]
  
  memo[n] = max(max(_dict.get(n, [0])),
                max(map(lambda x: max(_dict[x]) + 10 * max_int_with_match(n-x),
                        list(filter(lambda x: x<=n, _dict.keys()))
                       )
                   )
               )
  return memo[n]


print(max_int_with_match(N))
#print(memo)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import itertools


def main():
  r = (99, 2, 5, 5, 4, 5, 6, 3, 7, 6)
  n, _ = list(map(int, input().split()))
  ps = list(map(int, input().split()))

  cs = [(p, r[p]) for p in ps]
  cs.sort(key=lambda x: x[1])
  a = []
  s, b = cs[0]

  while n - b > 0:
    a.append(s)
    n -= b

  cs.sort(key=lambda x:-x[0])
  cs = [(p, c - b) for p, c in cs if c != b]
  ds = None

  for i in range(1, len(cs) + 1):
    for ps in itertools.product(range(len(cs)), repeat=i):
      if sum(cs[p][1] for p in ps) == n:
        ds = [cs[p][0] for p in ps]
        break

    if ds is not None:
      break

  uds = [d for d in ds if d >= s]
  lds = [d for d in ds if d < s][::-1]

  # if len(uds) > 0:
  #  a = uds + a[len(uds):]
  # if len(lds) > 0:
  #  a = a[:-len(lds)] + lds

  print(''.join(str(v) for v in a), flush=True)


if __name__ == '__main__':
  main()

Submission status: Runtime Error

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

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

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

for a in A:
  _dict[num_matches[a]]=_dict.get(num_matches[a],[]) + [a]

#print(_dict)

memo = [None for _ in range(N+1)] # return memo[N]
# Nほんのマッチを使って作れる整数の最大値．（作れなければ0）

def max_int_with_match(n):
  if memo[n]:
    return memo[n]
  
  if n < min(_dict.keys()):
    memo[n] = 0
    return memo[n]
  
  memo[n] = max(max(_dict.get(n, [])),
                max(map(lambda x: max(_dict[x]) + 10 * max_int_with_match(n-x),
                        list(filter(lambda x: x<=n, _dict.keys()))
                       )
                   )
               )
  return memo[n]


print(max_int_with_match(N))
#print(memo)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import itertools


def main():
  r = (99, 2, 5, 5, 4, 5, 6, 3, 7, 6)
  n, _ = list(map(int, input().split()))
  ps = list(map(int, input().split()))

  cs = [(p, r[p]) for p in ps]
  cs.sort(key=lambda x: x[1])
  a = []
  s, b = cs[0]

  while n - b > 0:
    a.append(s)
    n -= b

  cs.sort(key=lambda x:-x[0])
  cs = [(p, c - b) for p, c in cs if c != b]
  ds = None

  for i in range(1, len(cs) + 1):
    for ps in itertools.product(range(len(cs)), repeat=i):
      if sum(cs[p][1] for p in ps) == n:
        ds = [cs[p][0] for p in ps]
        break

    if ds is not None:
      break

  uds = [d for d in ds if d >= s]
  lds = [d for d in ds if d < s][::-1]

  if len(uds) > 0:
    a = uds + a[len(uds):]
  if len(lds) > 0:
    a = a[:-len(lds)] + lds

  print(''.join(str(v) for v in a), flush=True)


if __name__ == '__main__':
  main()

Submission status: Runtime Error

Solution code:
#!/mnt/c/Users/moiki/bash/env/bin/python
from itertools import permutations
N,M = map(int, input().split())
cost = [0,2,5,5,4,5,6,3,7,6]
A = list(map(int, input().split()))

p = []
for a in A:
    p.append( (cost[a], a) )
costp = sorted(p)


costX = [ z[0] for z in costp]
A = [ z[1] for z in costp]

dp = [""] * (N+1)

for c,a in zip(costX,A):
    i = N
    # print("i : ", i , "dp: ", dp[i] , ", [str(a)]: ", str(a))
    for p in permutations( [dp[i], str(a)]):
        dp[i-c] = max( 0 if len(dp[i-c]) == 0 else int(dp[i-c]), int( "".join(p)))
        dp[i-c] = str(dp[i-c])

for i in range(N-1, 1, -1):
    if dp[i] == "":
        continue
    for c,a in zip(costX,A):
        # print("i : ", i , "dp: ", dp[i] , ", [str(a)]: ", str(a))
        for p in permutations( [dp[i], str(a)]):
            dp[i-c] = max( 0 if len(dp[i-c]) == 0 else int(dp[i-c]), int( "".join(p)))
            dp[i-c] = str(dp[i-c])
    
print(dp[0])

Submission status: Runtime Error

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

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

mem = [None]*(N+1)
dst = [None]*(N+1)

def getScore(c):
    if mem[c] is not None:
        return mem[c]
    score = 0
    for a in A:
        if c >= COST[a]:
            tmp_score = getScore(c-COST[a])+1
            if tmp_score >= score:
                score = tmp_score
                dst[c] = a
    if c > 0 and dst[c] is None:
        score = -100
    mem[c] = score
    return score

getScore(N)
c = N
while c > 0:
    print(dst[c], end='')
    c -= COST[dst[c]]

Submission status: Runtime Error

Solution code:
from sys import stdin
n, m = [int(x) for x in stdin.readline().rstrip().split()]
a = [int(x) for x in stdin.readline().rstrip().split()]
if 1 in a:
    minm = 2
elif 7 in a:
    minm = 3
elif 4 in a:
    minm = 4
elif 2 in a:
    minm = 5
elif 3 in a:
    minm = 5
elif 5 in a:
    minm = 5
elif 6 in a:
    minm = 6
elif 9 in a:
    minm = 6
elif 8 in a:
    minm = 7
order = n // minm
amari = n % minm
output = ''
for i in range(order - 1)
    amari += minm
    if amari >= 6 and 9 in a:
        output += '9'
        amari -= 6
    elif amari >= 7 and 8 in a:
        output += '8'
        amari -= 7
    elif amari >= 3 and 7 in a:
        output += '7'
        amari -= 3
    elif amari >= 6 and 6 in a:
        output += '6'
        amari -= 6
    elif amari >= 5 and 5 in a:
        output += '5'
        amari -= 5
    elif amari >= 4 and 4 in a:
        output += '4'
        amari -= 4
    elif amari >= 5 and 3 in a:
        output += '3'
        amari -= 5
    elif amari >= 5 and 2 in a:
        output += '2'
        amari -= 5
    elif amari >= 2 and 1 in a:
        output += '1'
        amari -= 2
amari += minm
if amari == 6 and 9 in a:
    output += '9'
    amari -= 6
elif amari == 7 and 8 in a:
    output += '8'
    amari -= 7
elif amari == 3 and 7 in a:
    output += '7'
    amari -= 3
elif amari == 6 and 6 in a:
    output += '6'
    amari -= 6
elif amari == 5 and 5 in a:
    output += '5'
    amari -= 5
elif amari == 4 and 4 in a:
    output += '4'
    amari -= 4
elif amari == 5 and 3 in a:
    output += '3'
    amari -= 5
elif amari == 5 and 2 in a:
    output += '2'
    amari -= 5
elif amari == 2 and 1 in a:
    output += '1'
    amari -= 2
print(output)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import itertools


def main():
  r = (99, 2, 5, 5, 4, 5, 6, 3, 7, 6)
  n, _ = list(map(int, input().split()))
  ps = list(map(int, input().split()))

  cs = [(p, r[p]) for p in ps]
  cs.sort(key=lambda x: x[1])
  a = []
  s, b = cs[0]

  while n - b > 0:
    a.append(s)
    n -= b

  cs.sort(key=lambda x:-x[0])
  cs = [(p, c - b) for p, c in cs if c != b]
  ds = None

  for i in range(1, len(cs) + 1):
    for ps in itertools.product(range(len(cs)), repeat=i):
      if sum(cs[p][1] for p in ps) == n:
        ds = [cs[p][0] for p in ps]
        break

    if ds is not None:
      break

  uds = [d for d in ds if d >= s]
  lds = [d for d in ds if d < s][::-1]

  a = uds + a[len(uds):]
  a = a[-len(lds):] + lds

  print(''.join(str(v) for v in a), flush=True)


if __name__ == '__main__':
  main()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import itertools


def main():
  r = (99, 2, 5, 5, 4, 5, 6, 3, 7, 6)
  n, _ = list(map(int, input().split()))
  ps = list(map(int, input().split()))

  cs = [(p, r[p]) for p in ps]
  cs.sort(key=lambda x: x[1])
  a = []
  s, b = cs[0]

  while n - b > 0:
    a.append(s)
    n -= b

  cs.sort(key=lambda x:-x[0])
  cs = [(p, c - b) for p, c in cs if c != b]
  ds = None

  for i in range(1, len(cs) + 1):
    for ps in itertools.product(range(len(cs)), repeat=i):
      print(ps)
      if sum(cs[p][1] for p in ps) == n:
        ds = [cs[p][0] for p in ps]
        break

    if ds is not None:
      break

  uds = [d for d in ds if d >= s]
  lds = [d for d in ds if d < s][::-1]

  a = uds + a[len(uds):]
  a = a[-len(lds):] + lds

  print(''.join(str(v) for v in a), flush=True)


if __name__ == '__main__':
  main()

Submission status: Runtime Error

Solution code:
import sys
from collections import deque, defaultdict

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

if __name__ == '__main__':
    n, m = map(int, input().split())
    a = sorted(input().split())
    x = min(a, key=lambda x: mp[int(x)])
    key_x = mp[int(x)]
    quo, rem = divmod(n, key_x)
    buf = deque([x] * quo)

    dp = defaultdict(str)
    dp[0] = ''
    while rem not in dp:
        rem += key_x
        buf.pop()
        for k, v in list(dp.items()):
            for i in a:
                index = mp[int(i)]
                dp[k + index] = max(dp[k + index], i + v)
            del dp[k]

    for c in dp[rem]:
        if c > x:
            sys.stdout.write(c)
        else:
            buf.append(c)
    print(''.join(buf))

Submission status: Runtime Error

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

items = {
    1: 2, 2: 5, 3: 5, 4: 4, 5: 5, 6: 6, 7: 3, 8: 7, 9: 6
}
dp = [0] * (N + 1)

b_list = []
for a in a_list:
    need = items[a]
    if need <= N:
        dp[need] = a
        b_list.append(a)

M = len(b_list)
b_list.sort()
for i in range(N + 1):
    for b in b_list:
        if i - items[b] >= 0:
            if dp[i - items[b]] != 0:
                if dp[i - items[b]][0] < b:
                    cnt = 0
                    num = dp[i - items[b]]
                    while num != 0:
                        cnt += 1
                        num //= 10
                    tmp = max(b * (10 ** cnt) + dp[i - items[b]], dp[i - items[b]] * 10 + b)
                    dp[i] = max(tmp, dp[i])
                else:
                    dp[i] = max(dp[i], dp[i - items[b]] * 10 + b)


print(dp[N])

Submission status: Runtime Error

Solution code:
n,m = (int(i) for i in input().split())
a = list(int(i) for i in input().split())
use = []
t = [0,2,5,5,4,5,6,3,7,6]
for i in range(1,9):
  if i in a:
   use.append([i,t[i]])
use = sorted(use, key=lambda x: x[1])
query = ''
kaisuu = n//use[0][1]
amari = int(n%use[0][1])
#答えのベースを作る
judge = []
for i in range(kaisuu):
 query += str(use[0][0])
if amari == 0: judge =[int(query)]
#あまりに応じて最後尾を変えるか最初を変えるか
else:
  #先頭を変えた後のあまりで後ろを変える
  for j,k in enumerate(use):
     tmp2 = query
     amari = int(n%use[0][1])
     if int(k[0]) > int(use[0][0]) and int(k[1]) <= amari+int(use[0][1]):
      tmp2 = str(k[0])+query[1::]
      amari -=int(k[1])
      amari +=int(use[0][1])
      if amari == 0:       
       judge.append(int(tmp2))
     #後ろ側をあまりが０になるように調整する
     if amari >0:
      for j,k in enumerate(use):
        if int(k[1]) == amari+int(use[0][1]):
          tmp2 =tmp2[:-1]+str(k[0])
          judge.append(int(tmp2))
print(max(judge))

Submission status: Runtime Error

Solution code:
c = [0,2,5,5,4,5,6,3,7,6]
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))

B = [0] * M
for i in range(M):
    B[i] = c[A[i]]

x = min(B)
value = 0
for i in range(M):
    if B[i] == x:
        value = max(A[i], value)
y = N % x
if y == 0:
    print(str(value) * (N / x))
else:
    k = 10
    for i in range(M):
        if B[i] % x == y:
            if k > B[i]:
                k = B[i]
                l = A[i]
            elif k == B[i]:
                l = max(l, A[i])
    if value > l:
        print(str(value) * ((N - k) // x) + str(l))
    else:
        print(str(l) + str(value) * ((N - k) // x))

Submission status: Runtime Error

Solution code:
a,b = map(int,input().split())
k = [2,5,5,4,5,6,3,7,6]
c = list(map(int,input().split()))
cc = [[0,0] for i in range(b)]
ccc = [[0,0] for i in range(b)]
c.sort(reverse = True)
for i in range(b):
	cc[i] = [c[i],k[c[i]-1]]
	ccc[i]= [c[i],k[c[i]-1]]

cc.sort(key = lambda x:x[1])
ccc.sort(reverse = True)
p = a // cc[0][1]
q = a % cc[0][1]
co = [cc[0][0] for i in range(p)]
for i in range(p):
	for j in range(b):
		if ccc[j][0] > cc[0][0] and q >= ccc[j][1] - cc[0][1]:
			co[i] = ccc[j][0]
			q -= ccc[j][1] - cc[0][1]
			break
	if q == 0:
		break

for i in range(p):
	for j in range(b):
		if q >= cc[j][1] - k[co[-(i+1)]-1] and cc[j][1] > k[co[-(i+1)]-1]:
			q -= cc[j][1] - k[co[-(i+1)]-1]
			co[-(i+1)] = cc[j][0]
	if q == 0:
		break
if q != 0:
	for m in range(a):
		if c[0][1] != c[m][1]:
			p = a // cc[m][1]
			q = a % cc[m][1]
			co = [cc[m][0] for j in range(p)]
			for i in range(p):
				for j in range(b):
					if ccc[j][0] > cc[0][0] and q >= ccc[j][1] - cc[0][1]:
						co[i] = ccc[j][0]
						q -= ccc[j][1] - cc[0][1]
					break
				if q == 0:
					break

			for i in range(p):
				for j in range(b):
					if q >= cc[j][1] - k[co[-(i+1)]-1] and cc[j][1] > k[co[-(i+1)]-1]:
						q -= cc[j][1] - k[co[-(i+1)]-1]
						co[-(i+1)] = cc[j][0]
				if q == 0:
					break

			break


co.sort(reverse = True)

co = map(str,co)
aaa = ''.join(co)
print(aaa)

Submission status: Runtime Error

Solution code:
N,M=map(int,input().split())
A=list(map(int,input().split()))
M=[0,2,5,5,4,5,6,3,7,6]

#まず最高何桁の数にできるか考えよう.

USE=[M[a] for a in A]
USE=sorted(set(USE))

ANSLIST=[0]
def dfs(i,NOW):
    if ANSLIST[0]!=0:
        return
    ANS=0
    if NOW==N:
        L=sorted(list(i),reverse=True)
        #print(L)
        
        ANSLIST[0]=int(("".join(L)))
        return

    elif NOW>N:
        return 
    else:
        for a in A:
            dfs(i+str(a),NOW+M[a])


A.sort(reverse=True)
A.sort(key=lambda x:M[x])
dfs("",0)

x=ANSLIST[0]
stx=str(x)
from collections import Counter
counter=Counter(stx)

i=1
j=1
for ij in range(2,19):
    for i in range(1,ij):
        j=ij-i
        for k in range(1,10):
            for l in range(1,10):
                if i in A and j in A and k in A and l in A and counter[i]>0 and counter[j]>0:
                    x=min(counter[i],counter[j])
                    counter[i]-=x
                    counter[j]-=x
                    counter[k]+=x
                    counter[l]+=x

ANS=""
for i in range(9,-1,-1):
    ANS+=str(i)*counter[str(i)]

print(ANS)

Submission status: Runtime Error

Solution code:
import copy

n, m = map(int, input().rstrip().split())
number_list = list(map(int, input().rstrip().split()))
number_list.sort()
match = [2, 5, 5, 4, 5, 6, 3, 7, 6]
new_match = []
answer = []

for i in number_list:
    new_match.append(match[i-1])


for index in range(m):
    value = new_match[index]
    new_match_tmp = copy.copy(new_match)
    new_match_tmp.remove(value)
    maximum = max(new_match_tmp)
    #商と余りを計算
    quotient = int(n / value)
    remainder = n % value
    answer_tmp = [number_list[index]] * quotient
    #余りがあるなら余りをなくすように組み合わせを考える
    if remainder != 0:
        while True:
            quotient -= 1
            remainder += value
            answer_tmp.pop(0)
            if remainder in new_match:
                answer_tmp.append(number_list[new_match.index(remainder)])
                break
            elif remainder > maximum:
                try:
                    minimum = min(new_match_tmp)
                    remainder -= minimum
                    answer_tmp.append(number_list[new_match.index(minimum)])
                except:
                    answer_tmp = []
                    break
            if remainder == n:
                answer_tmp = []
                break

    if len(answer_tmp) != 0:
        answer.append(answer_tmp)

answer.sort(key=lambda x:len(x), reverse=True)
ans = reversed(answer[0])

print(*ans, sep='')
print()

Submission status: Runtime Error

Solution code:
a,b = map(int,input().split())
k = [2,5,5,4,5,6,3,7,6]
c = list(map(int,input().split()))
cc = [[0,0] for i in range(b)]
ccc = [[0,0] for i in range(b)]
c.sort(reverse = True)
for i in range(b):
	cc[i] = [c[i],k[c[i]-1]]
	ccc[i]= [c[i],k[c[i]-1]]

cc.sort(key = lambda x:x[1])
ccc.sort(reverse = True)
p = a // cc[0][1]
q = a % cc[0][1]
co = [cc[0][0] for i in range(p)]
for i in range(p):
	for j in range(b):
		if ccc[j][0] > cc[0][0] and q >= ccc[j][1] - cc[0][1]:
			co[i] = ccc[j][0]
			q -= ccc[j][1] - cc[0][1]
			break
	if q == 0:
		break

for i in range(p):
	for j in range(b):
		if q >= cc[j][1] - k[co[-(i+1)]-1] and cc[j][1] > k[co[-(i+1)]-1]:
			q -= cc[j][1] - k[co[-(i+1)]-1]
			co[-(i+1)] = cc[j][0]
	if q == 0:
		break
if q != 0:
	for i in range(a):
		if c[0][1] != c[i][1]:
			p = a // cc[i][1]
			q = a % cc[i][1]
			co = [cc[i][0] for j in range(p)]
			for i in range(p):
				for j in range(b):
					if ccc[j][0] > cc[0][0] and q >= ccc[j][1] - cc[0][1]:
						co[i] = ccc[j][0]
						q -= ccc[j][1] - cc[0][1]
					break
				if q == 0:
					break

			for i in range(p):
				for j in range(b):
					if q >= cc[j][1] - k[co[-(i+1)]-1] and cc[j][1] > k[co[-(i+1)]-1]:
						q -= cc[j][1] - k[co[-(i+1)]-1]
						co[-(i+1)] = cc[j][0]
				if q == 0:
					break

			break


co.sort(reverse = True)

co = map(str,co)
aaa = ''.join(co)
print(aaa)

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 = [None 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 dic is not None and len(dic) > 0:
            my_count = 1
            while j + count_table[my_value] * my_count <= n:
                already = dp[j + count_table[my_value] * my_count] or {}
                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 sys import stdin
n, m = [int(x) for x in stdin.readline().rstrip().split()]
a = [int(x) for x in stdin.readline().rstrip().split()]
if 1 in a:
    minm = 2
elif 7 in a:
    minm = 3
elif 4 in a:
    minm = 4
elif 2 in a:
    minm = 5
elif 3 in a:
    minm = 5
elif 5 in a:
    minm = 5
elif 6 in a:
    minm = 6
elif 9 in a:
    minm = 6
elif 8 in a:
    minm = 7
order = n // minm
amari = n % minm
output = ''
for i in range(order)
    amari += minm
    if amari >= 6 and 9 in a:
        output += '9'
        amari -= 6
    elif amari >= 7 and 8 in a:
        output += '8'
        amari -= 7
    elif amari >= 3 and 7 in a:
        output += '7'
        amari -= 3
    elif amari >= 6 and 6 in a:
        output += '6'
        amari -= 6
    elif amari >= 5 and 5 in a:
        output += '5'
        amari -= 5
    elif amari >= 4 and 4 in a:
        output += '4'
        amari -= 4
    elif amari >= 5 and 3 in a:
        output += '3'
        amari -= 5
    elif amari >= 5 and 2 in a:
        output += '2'
        amari -= 5
    elif amari >= 2 and 1 in a:
        output += '1'
        amari -= 2
print(output)

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 my_max(arr):
    _max = 0
    arg = -1
    for i,a in enumerate(arr):
        if _max < a:
            _max = a
            arg = i
    return arg, _max


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

    # two chars
    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]*i) // costs[min_a-1]
        if a>min_a:
            print(str(a)*i + str(min_a)*rep)
            return
        else:
            print(str(min_a)*rep + str(a)*d)
            return
    
    # three chars
    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-i*(costs[a0-1]-costs[a1-1])) // costs[min_a-1]
        if min_a < a1:
            print(str(a0)*i + str(a1)*i + str(min_a)*rep)
        elif min_a < a0:
            print(str(a0)*i + str(min_a)*rep + str(a1)*i)
        else:
            print(str(min_a)*rep + str(a0)*i + str(a1)*i)
        return

main()

Submission status: Runtime Error

Solution code:
# D
n, m = map(int, input().split())
a = list(map(int, input().split()))
match_list = [[1,2],[2,5],[3,5],[4,4],[5,5],[6,6],[7,3],[8,7],[9,6]]

use_list = []
# for i in match_list:
#     if i[0] in a:
#         use_list.append(i)
use_list = match_list
use_list.sort(key=lambda x:x[1])
print(use_list)
ans_list = []
num = n // use_list[0][1]
while n > 0:
    if n % use_list[0][1] == n:
        n += use_list[0][1]
        ans_list.pop(0)
        
        for i in use_list:
        break
    elif n >= use_list[0][1]:
        n -= use_list[0][1]
        ans_list.append(str(use_list[0][0]))

ans_list.sort()
ans_list.reverse()
print(''.join(map(str, ans_list)))