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: Wrong Answer

Solution code:
N,M=map(int,input().split())
A=list(map(int,input().split()))
A.sort(reverse=True)
num=[0,2,5,5,4,5,6,3,7,6]
dp=[0]
tmp=0
tmp1=0
for i in range(1,N+1):
    tmp=0
    for j in A:
        tmp1=-100000000000000000000
        if(i-num[j]>=0):
            if(dp[i-num[j]]!=0):
                tmp1=dp[i-num[j]]+j*(10**len(str(dp[i-num[j]])))
            else:
                tmp1=j
            if(tmp1>tmp):
                tmp=tmp1
    dp.append(tmp)
ans=dp[N]
print(ans)

Submission status: Wrong Answer

Solution code:
import sys

match_table = [0, 2, 5, 5, 4, 5, 6, 3, 7, 6]
search_table = [1, 7, 4, 5, 3, 2, 9, 6, 8]

def main():
    sys.setrecursionlimit(100) # recursion limit hack
    buf = input()
    buflist = buf.split()
    N = int(buflist[0])
    M = int(buflist[1])
    buf = input()
    buflist = buf.split()
    A = list(sorted(list(map(int, buflist))))
    # remove unnecessary number
    if 2 in A and (3 in A or 5 in A):
        A.remove(2)
    if 3 in A and 5 in A:
        A.remove(3)
    if 6 in A and 9 in A:
        A.remove(6)
    # main part
    for i in search_table:
        if i in A:
            extra_number, penalty = generate_extra_number(A, i, N % match_table[i], N)
            num_to_print = ""
            for j in range(N // match_table[i] - penalty):
                num_to_print += str(i)
            if int(extra_number[0]) > i:
                num_to_print = extra_number + num_to_print
            else:
                num_to_print = num_to_print + extra_number
            print(num_to_print)
            return

def generate_extra_number(A, main_num, remainder, N):
    if remainder == 0:
        return str(main_num), 1
    d = match_table[main_num]
    best = 0
    penalty = 99
    digit = 0
    while digit < 5:
        digit += 1
        for i in num_generator(A, digit, ""):
            extra_sum = sum([match_table[int(x)] for x in i])
            if (remainder - extra_sum) % d == 0 and extra_sum <= N:
                cand_best = int(i)
                cand_penalty = -(remainder - extra_sum) // d
                #print(best, cand_best, cand_penalty, cand_penalty - len(i), penalty - len(str(best)))
                if cand_penalty - len(i) < penalty - len(str(best)):
                    best = cand_best
                    penalty = cand_penalty
                elif cand_penalty - len(i) == penalty - len(str(best)):
                    if cand_best / exp(len(i)) > best / exp(len(str(best))) :
                        best = cand_best
                        penalty = cand_penalty
    return str(best), penalty

def num_generator(A, digit, num):
    if digit == 0:
        yield num
    else:
        for i in reversed(A):
            yield from num_generator(A, digit-1, num + str(i))

def exp(x):
    n = 1
    for i in range(x):
        n *= 10
    return n

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
a,b=list(map(int,input().split()))
X={1:2,2:5,3:5,4:4,5:5,6:6,7:3,8:7,9:6}
A=list(map(int,input().split()))
B=[v for k,v in X.items() if k in A]
print(B)
DP=[0]+[[] for i in range(10**4+1)]
L=[[] for i in range(10**4+1)]
for i in range(10):
    if i in B:
        DP[i]=1
        L[i].append(i)
#print(DP)
for i in range(1,10**4+1):
    if [DP[i-j] for j in B if i-j>=0 and not DP[i-j]==[]]==[]:
        DP[i]=[]
    else:
#        print(i,[DP[i-j] for j in B if i-j>=0 and not DP[i-j]==[]])
        M=[DP[i-j] for j in B if i-j>=0 and not DP[i-j]==[]]
        DP[i]=max([DP[i-j] for j in B if i-j>=0 and not DP[i-j]==[]])+1
        l=[0]
        for t in B:
            if not DP[i-t]==[] and DP[i]==DP[i-t]+1:
                l=l+[k for k,v in X.items() if v==t and k in A]
                L[i]=L[i-t]+[max(l)]
L[a].sort(reverse=True)
s='0'
for i in L[a]:
    s+=str(i)
print(int(s))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from itertools import chain
from functools import reduce, lru_cache
from collections import OrderedDict, Counter, deque
import operator

import sys
sys.setrecursionlimit(1024)

N, M = map(int, input().split())
A = [int(x) for x in input().split()]

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

@lru_cache(maxsize=None)
def fit(n, r):
    if n == 0:
        return []
    elif not r:
        return None
    
    c = r[0]
    if c <= n:
        ret = fit(n - c, r)
        if ret is not None:
            return ret + [c]
    return fit(n, r[1:])

def pat(l):
    c = Counter(l)
    mt = sorted([(max(j), i) for i,j in mtoa.items()], reverse=True)
    tmp = []
    for i, j in mt:
        if j in c:
            tmp += [i] * c[j]
    return int(''.join(map(str, tmp)))

atom = {}
mtoa = {}
for a in A:
    m = ntom[a]
    atom[a] = m
    mtoa.setdefault(m, []).append(a)

cands = set()
for a in mtoa.keys():
    s = set(mtoa.keys())
    s -= {a}
    r = tuple(sorted(s))
    d, m = divmod(N, a)
    if m == 0:
        cands.add(pat([a] * d))
    else:
        for i in range(max(d+1, 100)):
            ret = fit(m + i * a, r)
            if ret:
                cands.add(pat(ret + [a] * (d - i)))
                break

print(max(cands))

Submission status: Wrong Answer

Solution code:
def solve():
    N, M = [int(x) for x in input().split()]
    A = [int(x) for x in input().split()]
    A = sorted(A, reverse=True)

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

    dp = [[0] * (N+1) for _ in range(M+1)]
    prev = [[-1] * (N+1) for _ in range(M+1)]

    for i in range(0, M):
        m = digit_to_num[A[i]]  # match
        for n in range(0, N+1):
            if n == m or n - m >= m:
                if dp[i][n] <= dp[i+1][n-m] + 1:
                    dp[i+1][n] = dp[i+1][n-m] + 1
                    prev[i+1][n] = n - m
                else:
                    dp[i+1][n] = dp[i][n]
                    prev[i+1][n] = n
            else:
                dp[i+1][n] = dp[i][n]
                prev[i+1][n] = n

    # hukugen
    n = N
    chosen = []

    i = M-1
    while i >= 0:
        # print(i, n, A[i], m, prev[i+1][n], n-m)
        m = digit_to_num[A[i]]
        if prev[i+1][n] == n-m:
            chosen.append(A[i])
            # print("hit", A[i])
            n = prev[i+1][n]
        else:
            n = prev[i+1][n]
            i -= 1

    # print(A)
    chosen = sorted(chosen, reverse=True)
    # print(len(chosen))
    return "".join(map(str, chosen))


def main():
    print(solve())


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

from collections import defaultdict
import itertools

def solve():
    t = [0, 2, 5, 5, 4, 5, 6, 3, 7, 6]
    dt = {0:0, 1:2, 2:5, 3:5, 4:4, 5:5, 6:6, 7:3, 8:7, 9:6}

    n, m = map(int, input().split())
    al = [int(i) for i in input().split()]
    al.sort(reverse=True)
    d = defaultdict(list)
    for i in al:
        d[dt[i]].append(i)
    k = list(sorted(d.keys()))
    ans = ''
    if n % k[0] == 0:
        ans += str(d[k[0]][0]) * (n // k[0])
    else:
        p = n % k[0]
        s = []
        k1 = k[1:]
        for i in range(9, 0, -1):
            if i > len(k1):
                continue
            for j in list(itertools.combinations(k1, i)):
                l = [dt[w] for w in j]
                if p == sum(l) % k[0]:
                    s.append(list(j))
        mt, ma, mx = 10 ** 20, [0] * 5, 0
        tans = [None] * len(s)
        for idx, i in enumerate(s):
            i.sort(reverse=True)
            _tans = ''.join([str(d[w][0]) for w in i])
            _tans += str(d[k[0]][0]) * ((n - sum(i)) // k[0])
            _tans = list(_tans)
            _tans.sort(reverse=True)
            tans[idx] = (''.join(_tans))
        ans = 0
        for i in tans:
            ans = max(ans, int(i))
        ans = str(ans)
    ans = list(ans)
    ans.sort(reverse=True)
    print(''.join(ans))


if __name__=="__main__":
    solve()

Submission status: Wrong Answer

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

def comp(S,T):
	for s,t in zip(S,T):
		if s < t:
			return True
		if s > t :
			return False
	return True

A.sort()
dic = {i:[] for i in c_all}
cost = []
for n in A:
	dic[c_all[n-1]].append(n)
	if not n in cost:
		cost.append(c_all[n-1])

cost = cost[::-1]
nc = len(cost)

dp = [[-1,[0]*nc] for i in [0]*(N+1)]

dp[0] = [0,[0]*nc]

for i in range(1,N+1):
	for j, c in enumerate(cost):
		if i - c < 0:
			continue
		#dp[i] = max(dp[i],dp[i-c]+1)
		if dp[i][0] <= dp[i-c][0] + 1:
			temp = [x for x in dp[i-c][1]]
			temp[j] += 1
			if (dp[i][0] < dp[i-c][0]+1):
				dp[i] = (dp[i-c][0] + 1, temp)
			elif comp(dp[i][1], temp):
				dp[i] = (dp[i-c][0],temp)

c_ans = dp[N][1]
cand = {}
for i,j in zip(cost,c_ans):
	if j != 0:
		cand[max(dic[i])]=j
ans = ''
for i in range(9,0,-1):
	if i in cand:
		ans += str(i)*cand[i]
print(ans)

Submission status: Wrong Answer

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

from collections import defaultdict
import itertools

def solve():
    t = [0, 2, 5, 5, 4, 5, 6, 3, 7, 6]
    dt = {0:0, 1:2, 2:5, 3:5, 4:4, 5:5, 6:6, 7:3, 8:7, 9:6}

    n, m = map(int, input().split())
    al = [int(i) for i in input().split()]
    al.sort(reverse=True)
    d = defaultdict(list)
    for i in al:
        d[dt[i]].append(i)
    k = list(sorted(d.keys()))
    ans = ''
    if n % k[0] == 0:
        ans += str(d[k[0]][0]) * (n // k[0])
    else:
        p = n % k[0]
        s = []
        k1 = k[1:]
        for i in range(5, 0, -1):
            if i > len(k1):
                continue
            for j in list(itertools.combinations(k1, i)):
                l = [dt[w] for w in j]
                if p == sum(l) % k[0]:
                    s.append(list(j))
        mt, ma, mx = 10 ** 20, [0] * 5, 0
        tans = [None] * len(s)
        for idx, i in enumerate(s):
            i.sort(reverse=True)
            _tans = ''.join([str(d[w][0]) for w in i])
            _tans += str(d[k[0]][0]) * ((n - sum(i)) // k[0])
            _tans = list(_tans)
            _tans.sort(reverse=True)
            tans[idx] = (''.join(_tans))
        ans = 0
        for i in tans:
            ans = max(ans, int(i))
        ans = str(ans)
    ans = list(ans)
    ans.sort(reverse=True)
    print(''.join(ans))


if __name__=="__main__":
    solve()

Submission status: Wrong Answer

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

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)


for i in range(1,10):
    for j in range(i+1,10):
        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 max(k,l)>max(i,j) and counter[str(i)]>0 and counter[str(j)]>0 and M[i]+M[j]==M[k]+M[l]:
                    x=min(counter[str(i)],counter[str(j)])
                    counter[str(i)]-=x
                    counter[str(j)]-=x
                    counter[str(k)]+=x
                    counter[str(l)]+=x

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

print(ANS)

Submission status: Wrong Answer

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 = []
  rep = 1

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

    rep += 1

  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: Wrong Answer

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

def comp(S,T):
	for s,t in zip(S,T):
		if s < t:
			return True
		if s > t :
			return False
	return True

A.sort()
dic = {i:[] for i in c_all}
cost = []
for n in A:
	dic[c_all[n-1]].append(n)
	if not n in cost:
		cost.append(c_all[n-1])

cost = cost[::-1]
nc = len(cost)

dp = [[-1,[0]*nc] for i in [0]*(N+1)]

dp[0] = [0,[0]*nc]

print(cost)
for i in range(1,N+1):
	for j, c in enumerate(cost):
		if i - c < 0:
			continue
		#dp[i] = max(dp[i],dp[i-c]+1)
		if dp[i][0] <= dp[i-c][0] + 1:
			temp = [x for x in dp[i-c][1]]
			temp[j] += 1
			if (dp[i][0] < dp[i-c][0]+1):
				dp[i] = (dp[i-c][0] + 1, temp)
			elif comp(dp[i][1], temp):
				dp[i] = (dp[i-c][0],temp)

c_ans = dp[N][1]
cand = {}
for i,j in zip(cost,c_ans):
	if j != 0:
		cand[max(dic[i])]=j
ans = ''
for i in range(9,0,-1):
	if i in cand:
		ans += str(i)*cand[i]
print(ans)

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
a = list(map(int, input().split()))
dic = {1:2, 2:5, 3:5, 4:4, 5:5, 6:6, 7:3, 8:7, 9:6} # 2, 3, 6 は意味なし. 数値：使用本数
a.sort()
li = []
def fun(x, h):
    if h == 0:
        li.append(x)
        return
    for k in a:
        if h - dic[k] >= 0:
            if x == 0:
                y = int(str(k))
            else:
                y = int(str(x) + str(k))
            fun(y, h - dic[k])
        else:
            return
b = [dic[k] for k in a]
d = min(b)
kazu1 = max(int(n/d) - 7, 0)
kazu2 = max([k for k in a if dic[k] == d])
li = []
if kazu1 !=0:
    x = int(str(kazu2) * kazu1)
    fun(x, n - kazu1 * d)
else:
    for k in a:
        fun(k, n - dic[k])
ma = max(li)
li2 = list(str(ma))
li2.sort()
li2.reverse()
ans = int(''.join(li2))
print(ans)

Submission status: Wrong Answer

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 = []

  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: Wrong Answer

Solution code:
n, m = map(int, input().split())
a = list(map(int, input().split()))
dic = {1:2, 2:5, 3:5, 4:4, 5:5, 6:6, 7:3, 8:7, 9:6} # 2, 3, 6 は意味なし. 数値：使用本数
a.sort()
li = []
def fun(x, h):
    if h == 0:
        li.append(x)
        return
    for k in a:
        if h - dic[k] >= 0:
            if x == 0:
                y = int(str(k))
            else:
                y = int(str(x) + str(k))
            fun(y, h - dic[k])
        else:
            return
b = [dic[k] for k in a]
d = min(b)
kazu1 = max(int(n/d) - 9, 0)
kazu2 = max([k for k in a if dic[k] == d])
li = []
if kazu1 !=0:
    x = int(str(kazu2) * kazu1)
    fun(x, n - kazu1 * d)
else:
    for k in a:
        fun(k, n - dic[k])
ma = max(li)
li2 = list(str(ma))
li2.sort()
li2.reverse()
ans = int(''.join(li2))
print(ans)

Submission status: Wrong Answer

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

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

Num=[]
A=[]

if 1 in L:
    Num.append(1)
    A.append(2)
if 7 in L:
    Num.append(7)
    A.append(3)
if 4 in L:
    Num.append(4)
    A.append(4)
if 5 in L:
    Num.append(5)
    A.append(5)
elif 3 in L:
    Num.append(3)
    A.append(5)
elif 2 in L:
    Num.append(2)
    A.append(5)
if 9 in L:
    Num.append(9)
    A.append(6)
elif 6 in L:
    Num.append(6)
    A.append(6)
if 8 in L:
    Num.append(8)
    A.append(7)


for i in range(N):
    if N%A[0]==0:
        print(str(A[0])*(N//A[0]))
        exit()
    else:
        LI=[[0,[]] for x in range(N%A[0]+A[0]*i+1)]
        LI[0][0]=1
        for x in range(len(A)):
            for y in range(len(LI)):
                if LI[y][0]==1 and y+A[x]<len(LI) and LI[y+A[x]][0]==0:
                    LI[y+A[x]][0]=1
                    LI[y+A[x]][1]=copy.deepcopy(LI[y][1])
                    LI[y+A[x]][1].append(Num[x])
        if LI[len(LI)-1][0]==1:
            break
X=LI[len(LI)-1][1]

X.sort(reverse=True)
for i in range(len(X)):
    X[i]=str(X[i])
X.append(str(Num[0])*(N//A[0]-i-1))
X.sort(reverse=True)
ans=""
if len(X)!=0:
    for i in range(len(X)):
        ans+=str(X[i])
else:
    ans=""
print(ans)
#print(A[0])
#print(X)
#print(LI)

Submission status: Wrong Answer

Solution code:
def mina(t, i, L, miL):
  t -= i
  miL.append(D[i])
  if t == 0:
    return miL
  elif t < 0:
    del miL[-1]
    return []
  else:
    for i in L:
      Lis = mina(t, i, L, miL)
      if Lis != []:
        return Lis
    del miL[-1]
    return []

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 = []
for i in A:
  if t[i - 1] not in D:
    D[t[i - 1]] = i
    L.append(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:]:
      miL = mina(t, i, L[1:], [])
      if miL != []:
        F = False
        break
  
Ans = [str(D[L[0]]) for i in range(Lmin)]
if Lmod != 0:
  miL.sort(reverse = True)
  top = []
  und = []
  for i in miL:
    if L[0] < i:
      top.append(str(i))
    else:
      und.append(str(i))
  Ans = top + Ans + und

print("".join(Ans))

Submission status: Wrong Answer

Solution code:
mat = [2, 5, 5, 4, 5, 6, 3, 7, 6]
n, m = map(int, input().split())
a = list(map(int, input().split()))

yuanzu = []
for i in a:
    yuanzu.append((mat[i-1], i))
yuanzu.sort()

d = []
for i in range(len(yuanzu)-1):
    if yuanzu[i][0] == yuanzu[i+1][0]:
        d.append(yuanzu[i])
for i in d:
    yuanzu.remove(i)
# print(yuanzu)

ans = []
num = [0] * len(yuanzu)

def dfs(depth, s):
    # print(num, s)
    global ans
    if ans:
        return
    if s == 0:
        # print(num)
        ans = num.copy()
        return
    if depth >= len(yuanzu):
        return
    for num[depth] in range(s // yuanzu[depth][0], -1, -1):
        # print(num)
        dfs(depth + 1, s - num[depth] * yuanzu[depth][0])
        if ans:
            return
    return


dfs(0, n)
res = []
for i in range(len(ans)):
    res.append((yuanzu[i][1], ans[i]))
res.sort(reverse=True)
print(''.join([str(res[i][0])*res[i][1] for i in range(len(res))]))

Submission status: Wrong Answer

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: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from itertools import chain
from functools import reduce, lru_cache
from collections import OrderedDict, Counter, deque
import operator

import sys
sys.setrecursionlimit(1024)

N, M = map(int, input().split())
A = [int(x) for x in input().split()]

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

@lru_cache(maxsize=None)
def fit(n, r):
    if n == 0:
        return []
    elif not r:
        return None
    
    c = r[0]
    if c <= n:
        ret = fit(n - c, r)
        if ret is not None:
            return ret + [c]
    return fit(n, r[1:])

def pat(l):
    c = Counter(l)
    mt = sorted([(max(j), i) for i,j in mtoa.items()], reverse=True)
    tmp = []
    for i, j in mt:
        if j in c:
            tmp += [i] * c[j]
    return int(''.join(map(str, tmp)))

atom = {}
mtoa = {}
for a in A:
    m = ntom[a]
    atom[a] = m
    mtoa.setdefault(m, []).append(a)

cands = set()
for a in mtoa.keys():
    s = set(mtoa.keys())
    s -= {a}
    r = tuple(sorted(s))
    d, m = divmod(N, a)
    if m == 0:
        cands.add(pat([a] * d))
    else:
        for i in range(max(d+1, 20)):
            ret = fit(m + i * a, r)
            if ret:
                cands.add(pat(ret + [a] * (d - i)))
                break

print(max(cands))

Submission status: Wrong Answer

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: Wrong Answer

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: Wrong Answer

Solution code:
from sys import stdin

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

n,m = list(map(int, stdin.readline().rstrip().split()))
a = list(map(int, stdin.readline().rstrip().split()))
sorted_a = sorted(a, reverse=True)

uses = [USE[i-1] for i in sorted_a]
reverse_uses = sorted(uses, reverse=True)
min_use = min(uses)
min_use_idx = uses.index(min_use)

uses_left = uses[:min_use_idx]
uses_right = sorted(uses[min_use_idx+1:], reverse=True)

q, mod = divmod(n,min_use)

itr = 0
while (True):
	change = []
	q = q - itr
	mod = mod + min_use*itr
	for i in uses_left:
		if i-min_use == 0:
			continue
		while (True):
			if mod - (i - min_use) >= 0:
				mod -= i - min_use
				change.append(sorted_a[uses.index(i)])
			else:
				break
	if mod == 0:
		break
	for i in uses_right:
		if i-min_use == 0:
			continue
		while (True):	
			if mod - (i - min_use) >= 0:
				mod -= i - min_use
				change.append(a[reverse_uses.index(i)])
			else:
				break
	if mod == 0:
		break
	itr += 1

ans = [sorted_a[min_use_idx]]*(q - len(change))
ans.extend(change)
ans = sorted(ans, reverse=True)
print(''.join([ str(x) for x in ans]))

Submission status: Wrong Answer

Solution code:
NUMs = [0,2,5,5,4,5,6,3,7,6]

N, M = map(int, raw_input().split())
As = map(int, raw_input().split())

num_dict = {}
for a in As:
    num = NUMs[a]
    if a not in num_dict.items():
        num_dict[str(num)] = a
    elif num_dict[str(num)] < a:
        num_dict[str(num)] = a
nums = sorted(map(int, num_dict))

#print nums, num_dict

remove = []
for i in nums:
    for j in nums:
        if i + j in nums:
            remove.append(i + j)
        if j > i and j % i == 0:
            remove.append(j)
nums = sorted(list(set(nums) - set(remove)))

def divide(n, l):
    if len(l) == 1:
        if n % l[0] == 0:
            return True, [ n / l[0]]
        else:
            return False, []
    own_num = n // l[0]
    while own_num >= 0:
        pos, rest = divide(n - l[0] * own_num, l[1:])
        if pos:
            return True, [own_num] + rest
        own_num -= 1
    return False, []

dummy, int_nums = divide(N, nums)

i = ''
for m, n in zip(nums, int_nums):
    i += str(num_dict[str(m)]) * n

print ''.join(sorted(i, reverse=True))

Submission status: Wrong Answer

Solution code:
import math


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

MAX_N = int(1e4)
dp = [-1 for i in range(MAX_N + 20)]
dp[0] = 0

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

for i in range(N + 1):
    for j in A:
        tmp = dp[i]
        if tmp == -1:
            continue
        if tmp == 0:
            dp[i + mc[j - 1]] = max(dp[i + mc[j - 1]], j)
        else:
            dp[i + mc[j - 1]] = max(dp[i + mc[j - 1]], tmp * 10 + j, j * 10 ** (int(math.log10(tmp)) + 1) + tmp)

ans = dp[N]
print(ans)

Submission status: Wrong Answer

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: Wrong Answer

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

a = -1
cnt = 100

def check(n,r,S):
	if n==0:
		if r==0:
			return(S)
		else:
			return("no")
	for i in range(len(A)):
		if r-num[A[i]]>=0:
			s = check(n-1,r-num[A[i]],S+str(A[i]))
			if s!="no":
				return(s)
	return("no")

for i in range(len(A)):
	if cnt>=num[A[i]]:
		a = A[i]
		cnt = num[A[i]]
ans = ""
while N-cnt>=0:
	ans = ans+str(a)
	N -= cnt
A.sort()
A.reverse()
for i in range(len(A)):
	if N==num[A[i]]:
		if(a<A[i]):
			ans = str(A[i])+ans
		else:
			ans = ans+str(A[i])
		N = 0

if N==0:
	print(ans)
else:
	s = ""
	judge = False
	c = 0
	while judge==False:
		b = ans[-1:]
		ans = ans[:-1]
		now = ans
		c += 1
		N += num[int(b)]
		s = b+s
		for i in range(c+7):
			res = check(c+7-i,N,"")
			if res!="no":
				s1 = now+res
				s2 = res+now
				if s1<s2:
					ans = s2
				else:
					ans = s1
				judge = True
				break;
print(ans)

Submission status: Wrong Answer

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

from collections import defaultdict
import itertools

def solve():
    t = [0, 2, 5, 5, 4, 5, 6, 3, 7, 6]
    dt = {0:None, 1:2, 2:5, 3:5, 4:4, 5:5, 6:6, 7:3, 8:7, 9:6}

    n, m = map(int, input().split())
    al = [int(i) for i in input().split()]
    al.sort(reverse=True)
    d = defaultdict(list)
    for i in al:
        d[dt[i]].append(i)
    k = sorted(d.keys())
    ans = ''
    if n % k[0] == 0:
        ans += str(d[k[0]][0]) * (n // k[0])
    else:
        p = n % k[0]
        s = []
        k1 = k[1:]
        for i in range(5, 0, -1):
            if i > len(k1):
                continue
            for j in list(itertools.combinations(k1, i)):
                l = [dt[k] for k in j]
                if p == sum(l) % k[0]:
                    s.append(list(j))
        mt, ma, mx = 10 ** 20, [0] * 5, 0
        for i in s:
            i.sort(reverse=True)
            a = int(''.join([str(d[k][0]) for k in i]))
            if len(ma) > len(i):
                mt = a
                mx = sum([dt[k] for k in i])
                ma = i
            elif ma > i:
                mt = a
                mx = sum([dt[k] for k in i])
                ma = i
        ans += str(mt)
        ans += str(d[k[0]][0]) * ((n - sum(ma)) // k[0])
    ans = list(ans)
    ans.sort(reverse=True)
    print(''.join(ans))


if __name__=="__main__":
    solve()