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()))
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+1 > len(use)-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: Wrong Answer

Solution code:
N,M=map(int,input().split())
A=list(input().split())
if "1" in A:
    if N%2==0:
        print("1"*(N//2))
    else:
        if "7" in A:
            print("7"+"1"*(N//2-1))
        else:
            print("1"*(N//2))
else:
    if "7" in A:
        if N%3==0:
            print("7"*(N//3))
        elif N%3==1:
            if "4" in A:
                print("7"*(N//3-1)+"4")
            elif "8" in A:
                print("8"+"7"*(N//3-2))
        elif N%3==2:
            if "5" in A:
                print("7"*(N//3-1)+"5")
            elif "3" in A:
                print("7"*(N//3-1)+"3")
            elif "2" in A:
                print("7"*(N//3-1)+"2")
    elif "4" in A:
        if N%3==3:
            if N>=11 and "9" in A and "5" in A:
                print("95"+"4"*(N//4-2))
            elif N>=11 and "9" in A and "3" in A:
                print("9"+"4"*(N//4-2)+"3")
            elif N>=11 and "9" in A and "2" in A:
                print("9"+"4"*(N//4-2)+"2")
            elif "8" in A:
                print("8"+"4"*(N//4-1))
            elif N>=11 and "6" in A and "5" in A:
                print("65"+"4"*(N//4-2)) 
            elif N>=11 and "6" in A and "3" in A:
                print("6"+"4"*(N//4-2)+"3")
            elif N>=11 and "6" in A and "2" in A:
                print("6"+"4"*(N//4-2)+"2")
        elif N%4==2 and "9" in A:
            print("9"+"4"*(N//4-1))
        elif N%4==2 and "6" in A:
            print("6"+"4"*(N//4-1)) 
        elif N%4!=0 and "5" in A:
            print("5"*min(N%4,N//5)+"4"*(N//4-min(N%4,N//5)))
        elif N%4!=0 and "3" in A:
            print("4"*(N//4-min(N%4,N//5))+"3"*min(N%4,N//5))
        elif N%4!=0 and "5" in A:
            print("4"*(N//4-min(N%4,N//5))+"2"*min(N%4,N//5))
        else:
            print("4"*(N//4))
    elif "5" in A:
        if N%5!=0 and "9" in A:
            print("9"*min(N%5,N//6)+"5"*(N//5-min(N%5,N//6)))
        elif N%5==2 and "8" in A:
            print("8"+"5"*(N//5-1))
        elif N%5!=0 and "6" in A:
            print("6"*min(N%5,N//6)+"5"*(N//5-min(N%5,N//6)))
        else:
            print("5"*(N//5))
    elif "3" in A:
        if N%5!=0 and "9" in A:
            print("9"*min(N%5,N//6)+"3"*(N//5-min(N%5,N//6)))
        elif N%5==2 and "8" in A:
            print("8"+"3"*(N//5-1))
        elif N%5!=0 and "6" in A:
            print("6"*min(N%5,N//6)+"3"*(N//5-min(N%5,N//6)))
        else:
            print("3"*(N//5))
    elif "2" in A:
        if N%5!=0 and "9" in A:
            print("9"*min(N%5,N//6)+"2"*(N//5-min(N%5,N//6)))
        elif N%5==2 and "8" in A:
            print("8"+"2"*(N//5-1))
        elif N%5!=0 and "6" in A:
            print("6"*min(N%5,N//6)+"2"*(N//5-min(N%5,N//6)))
        else:
            print("2"*(N//5))
    elif "9" in A:
        print("9"*(N//6))
    elif "6" in A:
        if N%6!=0 and "8" in A:
            print("8"*min(N%6,N//7)+"6"*(N//6-min(N%6,N//7)))
        else:
            print("6"*(N//6))
    else:
        if "8" in A:
            print("8"*(N//7))

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+4):
			res = check(c-i,N,"")
			if res!="no":
				s1 = now+res
				s2 = res+now
				if s1<s2:
					ans = s2
				else:
					ans = s1
#				if s[0:c-i]<res:
#					ans = res+ans
#				else:
#					ans = ans+res
				judge = True
				break;
print(ans)

Submission status: Wrong Answer

Solution code:
from operator import itemgetter
tik = [[1,2],[7,3],[4,4],[5,5],[3,5],[2,5],[9,6],[8,7],[6,6]]
dic = {"1":2,"7":3,"4":4,"5":5,"3":5,"2":5,"9":6,"8":7,"6":6}

n,k = map(int, input().split())
x = list(map(int, input().split()))
dp = [0]+[-1]*(n+10)
q = []
for i in range(k):
    q.append([x[i],dic[str(x[i])]])

q = sorted(q, key=itemgetter(1), reverse=False)

s = []
p=0
t = 0
for i in range(n):
    for j in range(k):
        if i+q[j][1] <=n:
            if dp[i]!=-1:
            
                if  dp[i]==0:
                    dp[i+q[j][1]] = str(q[j][0])
                else:dp[i+q[j][1]] = str(dp[i])+str(q[j][0])
        #if i+q[j][1] ==n:
            #print(dp[20])
s = list(dp[n])
s.sort()
s = s[::-1]
print(''.join(s))

Submission status: Wrong Answer

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(len(str(max_res))):
        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: 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 = [(0,[0]*nc) for i in [0]*(N+1)]

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]) or comp(dp[i][1], temp):
				dp[i] = (dp[i-c][0]+1,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()))
cost = [-1, 2, 5, 5, 4, 5, 6, 3, 7, 6]
can_cost = sorted([cost[a] for a in A])
D = {}
for a in A:
    c = cost[a]
    D[c] = max(a, D.setdefault(c, -1))

min_cost = can_cost[0]
min_cost_num = D[min_cost]
K = N // min_cost
r = N - K * min_cost
temp = int("".join([str(min_cost_num)] * K))

dp = [[-1 for _ in range(min(r, K) + 1)] for __ in range(r + 1)]
dp[0][0] = temp


def f2(v, l, num):
    L = list(str(v))
    min_cost = cost[int(num)]
    num = D.setdefault(min_cost + l, -1)
    if num == -1:
        return -1

    min_cost_num = D[min_cost]
    L[L.index(str(min_cost_num))] = str(num)
    L.sort(reverse=True)
    return int("".join(L))



def f(v, l):
    L = list(str(v))
    set_L = set(L)
    L2 = [f2(v, l, num) for num in set_L]
    return max(L2)


for k in range(min(r, K)):
    for n in range(r):
        v = dp[n][k]
        if v == -1:
            continue
        for l in range(1, r - n + 1):
            dp[n + l][k + 1] = max(dp[n + l][k + 1], f(v, l))

print(max(dp[r]))

Submission status: Wrong Answer

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

max_vs = [''] * 10001
n, m = [int(v) for v in input().split()]
a = [int(v) for v in input().split()]
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(5)
if 6 in a and 9 in a:
        a.remove(6)
a.sort()
for i in range(1, n + 1):
        for v in a:
                if M[v] > i:
                        continue
                elif M[v] == i:
                        if max_vs[i] == '' or int(max_vs[i]) < v:
                                max_vs[i] = str(v)
                else:
                        if max_vs[i - M[v]] != '':
                                if max_vs[i] == '' or int(max_vs[i]) < int(str(v) + max_vs[i - M[v]]):
                                        max_vs[i] = str(v) + max_vs[i - M[v]]
print(max_vs[n])

Submission status: Wrong Answer

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

A.sort()
B = [0 for j in range(M)]
for i in range(M):
    if A[i] == 1:
        B[i] = 2
    if A[i] == 2:
        B[i] = 5
    if A[i] == 3:
        B[i] = 5
    if A[i] == 4:
        B[i] = 4
    if A[i] == 5:
        B[i] = 5
    if A[i] == 6:
        B[i] = 6
    if A[i] == 7:
        B[i] = 3
    if A[i] == 8:
        B[i] = 7
    if A[i] == 9:
        B[i] = 6
print(B)
B.sort()

def judge(n):
    if n == 7:
        return 8
    if n == 5:
        if A.count(5) == 1:
            return 5
        if A.count(3) == 1:
            return 3
        if A.count(2) == 1:
            return 2
    if n == 6:
        if A.count(9) == 1:
            return 9
        if A.count(6) == 1:
            return 6
    if n == 4:
        return 4
    if n == 3:
        return 7
    if n == 2:
        return 1
    return 0

def judge2(n):
    if n == 1:
        return 2
    if n == 2:
        return 5
    if n == 3:
        return 5
    if n == 4:
        return 4
    if n == 5:
        return 5
    if n == 6:
        return 6
    if n == 7:
        return 3
    if n == 8:
        return 7
    if n == 9:
        return 6


res = N % B[0]

C = ""
D = ""
flag1 = 0
flag2 = 0
while res != 0:
    pre_max = judge(B[0])
    for i in range(1, M+1):
        if pre_max < A[-i]:
            num = judge2(A[-i])
            if res - num >= 0:
                C[0]=(A[-i])
                res -= num
                flag1 = 1
        if pre_max > A[-i]:
            num = judge2(A[-i])
            if res - num >= 0:
                D[0]=(A[-i])
                res -= num
                flag2 = 1


max = judge(B[0])
pre_moji = str(C)
moji = str(max) * (int(N / B[0]) - flag1 - flag2)
post_moji = str(D)
print(pre_moji + moji + post_moji)

Submission status: Wrong Answer

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

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

n,m = li()
a = list(li())

use = {}
for ai in a:
    if dic[ai] not in use.keys():
        use.update({dic[ai]: ai})
    else:
        dic[ai] = max(dic[ai], ai)
        
# 最大順
desc = {}
edge = {}
for idx, num in enumerate(sorted(use.values(), reverse=True)):
    desc.update({idx: num})
    edge.update({idx: dic[num]})
    
        
# 遷移
INF = float('inf')
dp = [[-INF]*len(use) for _ in range(n+1)]
dp[0] = [0]*len(use)
for i in range(1, n+1):
    cand = dp[i].copy()
    for idx in range(len(use)):
        if i - edge[idx] < 0:
            continue

        if sum(cand) < sum(dp[i-edge[idx]])+1:
            tmp = dp[i-edge[idx]].copy()
            tmp[idx] += 1
            cand = tmp.copy()
            

        elif sum(cand) == sum(dp[i-edge[idx]])+1:
            tmp = dp[i-edge[idx]].copy()
            tmp[idx] += 1
            
            for orgi, tmpi in zip(cand, tmp):
                if orgi == tmpi:
                    continue
                
                elif orgi > tmpi:
                    break
                
                else:
                    cand = tmp.copy()
                    break
                
    dp[i] = cand
                

ans = ""
for num, cnt in zip(desc.values(), dp[-1]):
    ans = ans + str(num)*cnt
    
print(ans)

Submission status: Wrong Answer

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

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

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

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

max = [[]]*M


As_mattis = list(map(lambda x: mattis[x-1], As))
print(As_mattis)
for i in range(0,M):
    A = As[i]
    matti = As_mattis[i]
    num = int(N/matti)
    while(True):
        rem = N - num * matti
        if num < 0:
            break
        elif rem ==0 or rem in As_mattis:
            max[i] = [A] * num 
            if rem in As_mattis:
                max[i].append(sorted([As[i] for i in range(0,len(As_mattis)) if As_mattis[i] == rem],reverse=True)[0])
            
        else:
            num -= 1
            
max_str = ""
for max_list in max:
    if len(max_list) > len(max_str):
        print(max_list)
        max_str = "".join(map(lambda x: str(x),sorted(max_list,reverse=True)))
    
print(max_str)

Submission status: Wrong Answer

Solution code:
import math
import copy
import bisect







def nCast(number):
    if type(number)==str:
        return int(number)
    for idx in range(0,len(number)):
        if type(number[idx])==str:

            number[idx]=int(number[idx])
        else:
            nCast(number[idx])
    return number
    
def inputArr(w):
    l=list()
    for idx in range(0,w):
        l.append(input())
    return l
def inputArr1(w):
    l=list()
    for idx in range(0,w):
        l.append(input().split())
    return l

n=nCast(input().split())
m=nCast(input().split())

def cmp(l1,l2):

    if len(l1)!=len(l2):
        return len(l1)-len(l2)
#     for idx in range(0,len(l1)):
#         if l1[idx]!=l2[idx]:
#             return l1[idx]-l2[idx]
    return sum(l1)-sum(l2)
    return 0
def func():
    l=list()
    nn=[1,2,3,4,5,6,7,8,9]
    s=set(m)
    mm=[2,5,5,4,5,6,3,7,6]
    d=dict()
    for idx in nn:
        if idx in s:
            if idx==2 and 5 in s:
                continue
            if idx==3 and 5 in s:
                continue
            if idx==2 and 3 in s:
                continue
            if idx==6 and 9 in s:
                continue
            d[nn[idx-1]]=mm[idx-1]
    for idx in range(0,n[0]+1):
        l.append(list())
    for idx in range(1,n[0]+1):
        for idy in d:
            if idx-d[idy]>0:
                tmp=l[idx-d[idy]][:]
                if len(tmp)==0:
                    continue
                tmp.append(idy)
                tmp.sort(reverse=True)
                if cmp(tmp,l[idx])>0:
                    l[idx]=tmp
            elif idx-d[idy]==0:
                max=0
                for dd in d:
                    if d[dd]==idx and dd>max:
                        max=dd
                if cmp([max],l[idx])>0:
                    l[idx]=[max]

    result=""
    l[-1].sort(reverse=True)
    for idx in range(0,len(l[-1])):
        result=result+str(l[-1][idx])
    return result



print(func())

Submission status: Wrong Answer

Solution code:
necessary_matches = [0, 2, 5, 5, 4, 5, 6, 3, 7, 6]
num_of_matches, target_nums = map(int, input().split(' '))
nums = sorted(list(map(int, input().split(' '))))
nums.reverse()

# 使うマッチが少ないものからやっていく
least_matches = 10
recommended_num = 0
for i in nums:
  if necessary_matches[i] < least_matches:
    least_matches = necessary_matches[i]
    recommended_num = i
  elif necessary_matches[i] == least_matches:
    if i > recommended_num:
      recommended_num = i

digits = int(num_of_matches / least_matches)
rest = num_of_matches - (least_matches * digits)
max_numbers = [str(recommended_num)] * digits
# 左の数から大きくできるかチェック
max_replaced = False
min_replaced = True
def change(max_numbers, recommended_num, rest, least_matches):
  for i in range(len(max_numbers)):
    for j in nums:
      if j == recommended_num:
        continue
      replacing = str(j)
      if (rest + least_matches) >= necessary_matches[j]:
        if (j > recommended_num):
          max_numbers[i] = replacing
        else:
          max_numbers[len(max_numbers)-1] = replacing
        rest = (rest + least_matches - necessary_matches[j])
    if rest:
      break
  return rest
while rest != 0:
  rest = change(max_numbers, recommended_num, rest, least_matches)

#出力用
res = ""
for i in max_numbers:
  res += i
print(res)

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
dic = {1:2,2:5,3:5,4:4,5:5,6:6,7:3,8:7,9:6}
a = list(map(int,input().split()))
l=[]
for a_ in a:
    l.append([a_,dic[a_]])
l = sorted(l,key=lambda x:x[1])
print(l)
k = n//l[0][1]
mod = n%l[0][1]
if mod==0:
    ans = [l[0][0] for i in range(k)]
else:
    ans = [l[0][0] for i in range(k-1)]
    for i in range(len(l)):
        if mod+l[0][1]==l[i][1]:
            ans.append(l[i][0])
for i in ans:
    print(i,end='')
print()

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
A_list = list(map(int, input().split()))
cost_Dict = {1:2, 2:5, 3:5, 4:4, 5:5, 6:6, 7:3, 8:7, 9:6}
A_Dict = {}
for x in A_list:
  A_Dict[x] = cost_Dict[x]
min_digit = min(A_Dict, key=A_Dict.get)
min_cost = min(A_Dict.values())
min_num = min_cost
low_digit_num = (N // min_num)-1
res_matches = N - min_num*low_digit_num
X = list(A_Dict.keys())
X.sort()
X = X[::-1]
for x in X:
  if A_Dict[x] <= res_matches:
    max_digit = x
    break
ans = str(max_digit)
for i in range(low_digit_num):
  ans += str(min_digit)
print(ans)

Submission status: Wrong Answer

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

Alist = [int(x) for x in input().split()]

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

items = {}
for a in Alist:
    items[a] = matchDict[a]

# 必要マッチ数の少ない順にソート
items = sorted(items.items(), key=lambda x: (x[1], -x[0]))

cache = 0
delList = []
for k, v in items:
    if cache == v:
        delList.append((k,v))
    else:
        cache = v
for x in delList:
    items.remove(x)

# 何桁作る？
mininum, mini = items[0]
keta = N // mini
amari = N % mini

result = str(mininum) * keta
modcount = 0
delcountList = []
for x in items:
    delcountList.append(x[1]-mini)
# 余りに応じて数値調整
if amari != 0:
    items = sorted(items, key=lambda x: (-x[0]))

    for k,v in items:
        if mininum == k:
            continue
        if v <= mini+amari:
            if k > mininum:
                while True:
                    c = amari - (v - mini)
                    if c in delcountList:
                        moded = result[0:modcount]
                        result = result[modcount:]
                        result = moded + str(k) + result
                        result = result[:-1]
                        modcount += 1
                        amari = amari - (v - mini)
                        if v > mini+amari:
                            break
                    else:
                        break
            elif mininum > k:
                if amari > (v-mini):
                    c = amari // (v-mini)
                    c = c-1
                    for x in range(c):
                        result = result[:-1] + str(k)
                        amari = amari - (v - mini)
                if (amari - v + mini) == 0:
                    result = result[:-1] + str(k)
                    amari = amari - (v - mini)

        if amari == 0:
            break

print(result)

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
limits = [int(i) for i in input().split()]
necessary = [2, 5, 5, 4, 5, 6, 3, 7, 6]

mapped = [necessary[i-1] for i in limits]

if sum(mapped) == N:
    print(''.join(map(str, sorted(mapped)[::-1])))
    exit()

min_val = min(mapped)
many_num = 0
many_num_needs = 0
for i in range(M):
    if mapped[i] == min_val:
        many_num = limits[i]
        many_num_needs = mapped[i]
        break

many_count = int(N / many_num_needs)
amari = N % many_num_needs

while True:
    if amari not in mapped:
        many_count -= 1
        amari = N - (many_num_needs * many_count)
    else:
        break

low_num = 0
for i in range(M):
    if mapped[i] == amari:
        low_num = limits[i]
        break

if many_num < low_num:
    print(low_num, end='')

[print(many_num, end='') for i in range(many_count)]

if low_num <= many_num:
    print(low_num)
else:
    print('')

Submission status: Wrong Answer

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

import copy

def main():
    n, m = list(map(int, input().split()))
    num = [0, 2, 5, 5, 4, 5, 6, 3, 7, 6]
    la = list(map(int, input().split()))
    use = sorted(list(set(num[a] for a in la)))
    convert = {}
    for d in sorted(la):
        convert[num[d]] = d
    dp = [[0, 0, 0, 0, 0, 0, 0] for _ in range(n+10)]
    dp[0][0] = 1
    for i in range(n):
        if dp[i][0] == 0:
            continue
        s1 = sum(dp[i][1:]) + 1
        for d in use:
            tmp = dp[i+d][1:]
            s2 = sum(tmp)
            if s1 >= s2:
                dp[i+d] = copy.deepcopy(dp[i])
                dp[i+d][d-1] += 1
                dp[i+d][0] = 1
    ans = ""
    anss = []
    for i, cnt in enumerate(dp[n][1:]):
        d = i+2
        if cnt == 0:
            continue
        anss.append((convert[d], cnt))
    for d, cnt in sorted(anss, reverse=True):
        ans += str(d) *cnt
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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



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

if(m == 1):
    for i in range(n // a_dict[a[0]]):
        print(a[0], end="")
    print()
    exit()

b = []
for i in a:
    b.append([a_dict[i], -i])

b = sorted(b, key=lambda x:(x[0],x[1]))

def search(b, ans, n, deep, depth):
    count = 0
    for i in range(len(ans)):
        count += ans[i] * b[i][0]

    if(count == n): return ans
    if(deep == depth): return ans


    for i in range((n-count) // b[deep][0], -1, -1):
        ans[deep] = i
        ans = search(b, ans, n, deep+1, depth)
        count = 0
        for i in range(len(ans)):
            count += ans[i] * b[i][0]
        if(count == n): return ans
    
    return ans
        

ans = search(b, m*[0], n, 0, m)

c = []
for i in range(m):
    c.append([b[i][1]*-1, ans[i]])
c = sorted(c, reverse=True)

for i in range(m):
    for j in range(c[i][1]):
        print(c[i][0], end="")

print()

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(10)] for i in range(MAX_N + 20)]
for j in A:
    dp[0][j] = 0

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

for i in range(N + 1):
    for j in A:

        if i < mc[j - 1]:
            continue

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

ans = 0
for j in range(1, 9 + 1):
    ans = max(ans, dp[N][j])
print(ans)

Submission status: Wrong Answer

Solution code:
def can_make(remain, enable_digits):
    
    candidates = [(remain, "")]
    
    best_answer = ""
    while candidates:
        
        current_remain, digits = candidates.pop(0)
        if current_remain == 0:
            if not best_answer:
                best_answer = digits
            else:
                if len(digits) <= len(best_answer):
                    if digits > best_answer:
                        best_answer = digits
        if best_answer != "" and len(digits) >= len(best_answer):
            continue
        for (cost, neg, digit) in enable_digits:
            if cost <= current_remain:
                candidates.append( (current_remain - cost, digits + str(digit)))
        
    return list(best_answer)


def main():
    n, m = [int(x) for x in input().rstrip("\n").split(" ")]
    
    costs = (0,2,5,5,4,5,6,3,7,6)
    enable_digits = [(costs[int(x)],int(x) * -1 , int(x))  for x in input().rstrip("\n").split(" ")]
    
    enable_digits.sort()
    
    #最大桁数を決める
    min_cost, min_cost_max_digit_neg, min_cost_max_digit =enable_digits.pop(0)
    
    num_of_digits, remain = divmod(n , min_cost)
    
    if remain == 0:
        anwer = [str(min_cost_max_digit)] * num_of_digits
        print("".join(anwer))
    else:
        answer = can_make(remain, enable_digits)
        while not answer:
            remain += min_cost
            num_of_digits -= 1
            answer = can_make(remain, enable_digits)

        answer.sort()
        answer.reverse()
        greater = [digit for digit in answer if digit > str(min_cost_max_digit)]
        lesser = [digit for digit in answer if digit < str(min_cost_max_digit)]
        
        print("".join(greater) + (str(min_cost_max_digit) * num_of_digits) + "".join(lesser) )

if __name__ == '__main__':
	main()

Submission status: Wrong Answer

Solution code:
import copy

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

cost = (2,5,5,4,5,6,3,7,6)
A_cost = {a:cost[a-1] for a in A}
A_min = min(A_cost, key=A_cost.get)
A_min_cost = A_cost[A_min]

count = {a:0 for a in A}
count[A_min] = N // A_cost[A_min]
N %= A_cost[A_min]
A.pop(A.index(A_min))
A_cost.pop(A_min)

while N!=0:
  count[A_min] -= 1
  N += A_min_cost
  if N in A_cost.values():
    index = max((a for a in A if A_cost[a] == N))
    count[index] += 1
    N -= A_cost[index]
  if N >= min(A_cost.values()):
    index = max((a for a in A if A_cost[a] == min(A_cost.values())))
    count[index] += 1
    N -= A_cost[index]

for a in sorted(A_org, reverse=True):
  for _ in range(count[a]):
    print(a, end="")
print()

Submission status: Wrong Answer

Solution code:
s = list(map(int, input().split()))
t = list(map(int, input().split()))


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


lista=[]
minm=[8,7]
minflag=0;
for i in range(len(t)):
    if(t[i]==1):
        lista.append([1,2])
        aru[1]=1
        if(minflag==0):
            minm=[1,2]
            minflag=1
for i in range(len(t)):
    if(t[i]==7):
        lista.append([7,3])
        aru[7]=1
        if(minflag==0):
            minm=[7,3]
            minflag=1
        
for i in range(len(t)):
    if(t[i]==4):
        lista.append([4,4])
        aru[4]=1
        if(minflag==0):
            minm=[4,4]
            minflag=1
        
flag=[0,0,0]
for i in range(len(t)):
    if(t[i]==5):
        flag[0]=1
        aru[5]=1
    if(t[i]==3):
        flag[1]=1
        aru[3]=1
    if(t[i]==2):
        flag[2]=1
        aru[2]=1
if(flag[0]==1):
    lista.append([5,5])
    if(minflag==0):
        minm=[5,5]
        minflag=1
elif(flag[1]==1):
    lista.append([3,5])
    if(minflag==0):
        minm=[3,5]
        minflag=1
elif(flag[1]==1):
    lista.append([2,5])
    if(minflag==0):
        minm=[2,5]
        minflag=1

flag=[0,0]
for i in range(len(t)):
    if(t[i]==9):
        flag[0]=1
        aru[9]=1
    if(t[i]==6):
        flag[1]=1
        aru[6]=1
if(flag[0]==1):
    lista.append([9,6])
    if(minflag==0):
        minm=[9,6]
        minflag=1
elif(flag[1]==1):
    lista.append([6,6])
    if(minflag==0):
        minm=[6,6]
        minflag=1

for i in range(len(t)):
    if(t[i]==8):
        aru[8]=1
        lista.append([8,7])

nn=n
d=0
while(nn>=minm[1]):
    nn-=minm[1]
    d+=1

sch=minm[1]
saigo=minm[0]
while(nn>=1):
    sch+=1
    if(sch==3):
        if(saigo<7):
            saigo=7
    elif(sch==4):
        if(saigo<4):
            saigo=4
    elif(sch==5):
        if(saigo<5):
            saigo=5
    elif(sch==6):
        saigo=9
    elif(sch==7):
        if(saigo<8):
            saigo=8
    
    nn-=1;
    
ans=""
for i in range(d-1):
    ans+=str(minm[0])
ans+=str(saigo)
print(ans)



##a