We need to find the largest integer that can be formed using exactly N matchsticks, where each digit must be from a given set of allowed digits A_i. Each digit consumes a certain number of matchsticks as given (like typical 7-segment display, but the counts are provided: digit -> matchsticks: 1:2,2:5,3:5,4:4,5:5,6:6,7:3,8:7,9:6). So it's like the classic matchstick problem: given a set of allowed digits, form the largest number using exactly N matchsticks.
We have constraints: N up to 10000, so DP/greedy is possible. M up to 9 (digits 1-9, but may not include all). There is guaranteed at least one number.
Goal: largest integer. Typically we want as many digits as possible? Actually largest integer lexicographically, which means more digits is not always better because a higher digit in the most significant position matters more. Usually we want to maximize the number of digits because any positive digit >0? But careful: digits are 1-9, no zero? The allowed digits are from 1 to 9, so they are non-zero. So the number's length (number of digits) is important: longer number > shorter number if we compare integers, because all digits are positive and non-zero, so a longer number is always larger? Actually compare two positive integers: the one with more digits is larger regardless of the digits (unless there is leading zeros, but we don't have zeros). So we must maximize the length (number of digits) first, then among numbers of the same maximal length, we want lexicographically largest (i.e., maximize the most significant digit, then next, etc.). This is the typical approach.
But careful: Could there be a scenario where using a digit that consumes more matchsticks reduces length but yields a higher digit at the front making the overall number larger? No, because if we have two numbers with different lengths, say length L1 > L2, then number with length L1 is larger than any number with length L2, regardless of digits, as long as the leading digit is non-zero. For example, L1=3 digits: smallest possible 111 (if 1 allowed) vs L2=4 digits: 1111, the 4-digit is larger (1111 > 111). Since allowed digits are at least 1, the smallest L1-digit number is 1 followed by L1-1 ones, which is 10^{L1-1} + ... Actually 10^{L1-1} > 10^{L2-1} if L1 > L2. So maximizing length is the primary objective.
Thus, we need to find the maximum number of digits we can form using exactly N matchsticks with allowed digits. Then, among those solutions with that maximal length, we want the lexicographically largest number.
This is a classic DP: We can treat each digit's cost (matchsticks). We want to maximize the number of digits: that's a knapsack: maximize count subject to total cost N. Since costs are positive integers, we can solve via DP (or greedy if we can prove certain properties). Because N is large (10^4) but digit costs are small (max 7), we can do DP for max length.
But careful: we need to ensure that we use only allowed digits. So the set of costs is from the allowed digits. Let allowedDigits be A, with costs c[d] for d=1..9 (as given). So allowed costs: possible match counts: for each digit d in A, cost = c[d].
Goal: maximize number of digits: Let dp[i] = maximum number of digits we can achieve using exactly i matchsticks (or -inf if impossible). Since we want exactly N, we compute dp[N].
But we also need to construct the largest number. Typically we do: first compute dp[i] for i from 0 to N: dp[0] = 0 (0 digits, 0 matches). For i >0, dp[i] = max_{d in A} (1 + dp[i - c[d]]) if i - c[d] >=0 and dp[i - c[d]] defined. That's a simple DP O(N * M) which is up to 10^4 * 9 = 90k, fine.
But note: N can be up to 10000, M up to 9, so it's fine. But careful: dp table size 10001.
Now, once we have dp array, we know maxLength = dp[N]. Then we need to construct the lexicographically largest number with that length. Approach: iterate from leftmost digit to rightmost, at each position we try the largest allowed digit d (descending order) such that we can still complete the remaining positions with exactly the remaining matchsticks. That is: for remaining matches left (starting with N), and we need to fill remaining positions (remaining length = maxLength initially). For each position, we try digits from largest to smallest (9 down to 1 but only those allowed). For a candidate digit d, cost = c[d]. After using it, we have remaining matches = N - cost, and we need to achieve a total length of maxLength - 1. That is possible if dp[remaining matches] == maxLength - 1. If yes, we choose that digit and move on. This greedy works because we are building the largest lexicographically number: at each step we choose the largest digit that doesn't preclude achieving the maximum length.
Proof: Since we want the maximum number, we want the most significant digit as large as possible, as long as we can still fill the rest with some combination that uses exactly the remaining matches and yields the max length -1. Since dp[remaining] gives the max possible length for that remaining matches, if it equals needed length, then there exists some combination to fill the rest, possibly with some digits; and because we always check existence, we can commit to this digit. This is typical.
Thus algorithm:
Preprocess cost for digits 1-9.
Read N, M, array A.
Create allowed set.
Compute dp array: dp[0] = 0, for i from 1..N: dp[i] = -inf (or -1). For i from 0..N, if dp[i] != -1, then for each d in allowed: if i + c[d] <= N, dp[i + c[d]] = max(dp[i + c[d]], dp[i] + 1). This is forward DP. Alternatively, backward DP: dp[i] = max_{d} (1 + dp[i - c[d]]) if i>=c[d] and dp[i - c[d]] >=0.
Then maxLength = dp[N].
Then construct string: remaining = N, for pos from 1 to maxLength: for d in sorted(allowedDigits descending): if remaining >= c[d] and dp[remaining - c[d]] == maxLength - pos: then choose d, append to ans, remaining -= c[d], break.
Output ans.
This should work.
But careful: The digits allowed are from 1 to 9, but note that digit 0 is not allowed (since A_i between 1 and 9). So we can't have zero. That's fine.
Potential pitfalls: The DP must be careful to handle -infinity. Use a large negative sentinel. Since N up to 10000, max length is at most floor(N / min_cost). Min cost among allowed digits? Could be 2 (digit 1) if allowed, or 3 (digit 7) if 1 not allowed, etc. So max length up to 5000, which fits in int.
But is there any nuance? The problem statement says "Find the largest integer that can be formed with exactly N matchsticks". Since the integer could be huge (with up to 5000 digits), we must output it as a string, not as numeric type. That's fine.
We need to ensure that dp table is computed correctly. Since we only care about dp[N], we can compute dp with a simple loop.
But note: there could be multiple ways to achieve max length, but we want the largest integer. The greedy approach described will yield the largest.
Now confirm with examples:
Example1: N=20, M=4, A=[3,7,8,4]. Costs: 3:5, 7:3, 8:7, 4:4. Allowed costs: 5,3,7,4.
We need max length for 20. Let's compute dp. min cost 3 (digit 7). max length? Possibly: using digit 7 (cost3) many times: 20/3=6 remainder2, but we need exact. Let's find combos: 7+7+3+3? Actually digit 7 cost3, digit 8 cost7, digit 3 cost5, digit4 cost4. So we need sum 20. Max digits: maybe 6 digits: 3+3+3+3+3+5? that sums to 35=15 +5=20? Actually 5 times cost3=15, plus cost5=20 => 6 digits. Or 3+3+3+3+4+4 = 3+3+3+3+4+4 = 20? 3+3+3+3=12, +4+4=20 => 6 digits. Could there be 7 digits? min cost=3, 73=21 >20, so max length <=6. So dp[20]=6. Now we need lexicographically largest 6-digit number using allowed digits {3,7,8,4}. We construct: remaining=20, length left=6. Try digits from largest: 8 (cost7). Check: remaining-cost=13, dp[13] must be 5. Is dp[13]=5? Let's see if we can get 5 digits with 13 matches. min cost 3 => 53=15 >13, so max length maybe 4? Actually 43=12 leaves 1, impossible; other combos? Could we have 5 digits? 13: try combos: 3+3+3+4=13? That's 4 digits. 3+5+5=13? Not allowed? 5 is not allowed. 7+3+3=13? That's 3 digits. 4+4+? 4+4+? 4+4+? 4+4+? Actually 4+4+3=11, need 2 more no. 8+? cost7+? need 6 => maybe 6? not allowed. So likely dp[13]=4? Let's compute properly: allowed digits costs {3,4,5,7}. 13 can be: 3+3+7=13 => 3 digits. 4+4+5=13 => 3 digits. 3+3+3+4=13 => 4 digits (3+3+3+4=13) yes! 3+3+3+4=13, 4 digits. Could there be 5 digits? 5 digits minimal cost 35=15>13, so no. So dp[13]=4. But we need 5, so digit 8 not possible. Next largest digit: 7 (cost3). Check: remaining-cost=17, dp[17] need 5. Can we get 5 digits with 17? 53=15, 17-15=2 can't. But maybe other combos: 3+3+3+4+4=17? 3+3+3+4+4=17 -> 5 digits? 3+3+3+4+4 = 17 indeed 5 digits. So dp[17]=5 possible. So choose digit 7. Now ans="7", remaining=17, length left=5. Next digit: try 8 (cost7): remaining-cost=10, need dp[10]=4? 10 can be 3+3+4=10? that's 3 digits; 4+? Actually 3+7=10 -> 2 digits; 5+5=10 but 5 allowed? 5 is not in allowed digits? Allowed digits: 3,7,8,4. 5 not allowed. So 10 could be 3+3+4=10 (3 digits) or 4+? 4+? 4+? 4+? need 6 not allowed. Could we get 4 digits? 3+3+? 3+3+? 3+3+? 3+3+? 2+? No. Minimum cost 3, 4*3=12>10. So dp[10]<=3. So 8 not possible. Next digit 7 (cost3): remaining-cost=14, need dp[14]=4. Can we get 4 digits with 14? 3+3+4+4=14 -> 4 digits. Yes. So choose 7. ans="77", remaining=14, left=4. Next digit: try 8: cost7, remaining-cost=7, need dp[7]=3? 7 matches: can we have 3 digits? Minimum 3 digits with cost 3 each =9 >7, so max digits? Actually 7 can be formed as digit 7 itself (cost3) +? Wait dp[7] = max number of digits from allowed that sum to 7. Allowed: 3,4,5,7. 7 can be digit 8? 8 cost7 -> 1 digit, so dp[7] can be 1 (just digit 8). But we need 3 digits, so not possible. So 8 fails. Next digit 7: cost3, remaining-cost=11, need dp[11]=3. Can we get 3 digits from 11? 3+3+5=11 but 5 not allowed. 3+4+4=11 -> 3 digits, allowed: 3,4,4. Yes. So choose 7. ans="777", remaining=11, left=3. Next digit: try 8: cost7, remaining-cost=4, need dp[4]=2. Can we get 2 digits from 4? 4 matches can be digit 4 (cost4) only, which is 1 digit. Or digit 1 cost2? not allowed. So dp[4] =? 4 can be 4 itself (1 digit). Could be 2+2? not allowed. So dp[4]=1. Not 2. So fail. Next digit 7: cost3, remaining-cost=8, need dp[8]=2. 8 matches: can we get 2 digits? 4+4=8 -> 2 digits, allowed. So choose 7. ans="7777", remaining=8, left=2. Next digit: try 8: cost7, remaining-cost=1, need dp[1]=1? impossible (no cost1). fail. Next 7: cost3, remaining-cost=5, need dp[5]=1? 5 matches: digit 3 cost5? digit 3 cost5, allowed? A includes 3, so digit 3 uses 5 matches -> 1 digit. So dp[5]=1. But wait we need dp[5]=1? Actually left=2, after picking a digit we need 1 digit left, so dp[remaining-cost] must equal 1. So if we pick digit 7 cost3, remaining-cost=5, dp[5]=1 is true (since digit 3 uses 5 matches). So that works. But we also could try larger digits? After 7, next allowed digit is 4 (cost4) maybe? But we are trying digits descending: 8,7,4,3? Actually allowed digits sorted descending: 8,7,4,3. After 7, we have 4. So we must check if 7 is chosen? Actually we try from largest to smallest, and we take the first that works. So for this step, we check 8 (fail), then 7 (works). So we pick 7. ans="77777"? Wait we had 4 digits already, and now left=2, we pick digit 7? That would give 5th digit as 7, leaving remaining=5, left=1. Then final digit: we need one digit from remaining=5, allowed digits descending: try 8? cost7>5; 7 cost3 <=5, but we need exactly 5 matches. After picking a digit, remaining-cost must be 0 and length left 0. For last digit, we need to pick a digit with cost exactly remaining, and dp[0]=0. So we need to check: for last digit, we try descending: 8 fail, 7 cost3, remaining-cost=2, but dp[2]? dp[2]? We need dp[2]=0, but is dp[2] possible? digit 1 cost2, but 1 not allowed. So dp[2] is -inf. So 7 fails. Next 4 cost4, remaining-cost=1, fail. Next 3 cost5, but cost5 <=5? Actually cost5 equals remaining, remaining-cost=0, dp[0]=0, so digit 3 works. So final digit would be 3. So number becomes 777773. That matches example output: "777773". In our greedy step, for the 5th digit we chose 7, which leads to final digit 3. But maybe we could have chosen 4 for the 5th digit? Let's simulate alternative: at step with remaining=8, left=2, if we pick digit 4 (cost4), then remaining becomes 4, left=1. Then final digit: need digit with cost 4, which is digit 4, allowed. That would give 77774? Actually we have so far: after 4 digits we had "7777". Then digit 4 -> "77774", then final digit 4 -> "777744". That's number 777744, which is smaller than 777773? Compare: 777773 vs 777744: 777773 > 777744 because at first differing position (5th digit? Actually both have length 6. Compare: positions: 1:7 both, 2:7 both, 3:7 both, 4:7 both, 5: for first number: 7, for second: 4, so 7 > 4. So greedy selecting 7 is better. So the algorithm works.
Example2: N=101, M=9, all digits 1-9 allowed. We need max length. Min cost =2 (digit1). So max length = floor(101/2)=50? Actually 250=100, leaving 1, but we need exactly 101. So we must use a combination. The DP will find max length L. Let's compute: If we want max length, we want to use as many low-cost digits as possible. The minimum cost is 2, so maximum length would be as high as possible but we need to sum to 101. The maximum length achievable is: If we use many 2s, we get even sum. To get odd sum, we need at least one odd cost digit. The cost values: 2,3,4,5,6,7. The parity matters. The maximum number of digits is when we use as many 2s as possible, but if we need to adjust parity, we replace one 2 with a digit of cost 3 (or 5,7) to change parity while keeping length same? Actually replacing a 2 with a 3 increases cost by 1 and keeps same length. So if N is odd, we can't have all 2s (even sum). So we need at least one odd-cost digit. So we can have 49 digits of cost2 =98, plus need 3 more matches to reach 101, so replace one 2 (cost2) with a digit of cost? Actually we need total 101. If we start with 50 digits of cost2, sum=100, need 1 more, but we can't add a digit because that would increase length; we could replace a 2 with a digit of higher cost, increasing sum by delta. For 50 digits, we can have 49 digits of cost2 =98, and one digit of cost3 =3, sum=101. That's 50 digits. Could we have 51 digits? 512=102 >101, so too many. So max length =50. So dp[101]=50. Now to construct largest number: allowed digits all, descending order: 9,8,7,6,5,4,3,2,1. We need to produce 50 digits sum 101. Greedy: start remaining=101, length left=50. Try 9 cost6? Wait costs: digit9 cost6. Check: remaining-cost=95, need dp[95]=49. Is it possible? 49 digits, each at least cost2 gives min sum 98, but 95 is less than 98, so impossible. So 9 fails. Try 8 cost7 -> remaining 94, need 49 digits min 98 >94, impossible. 7 cost3 -> remaining 98, need 49 digits. 49 digits min sum 249=98, exactly, so possible if we can use 49 digits all cost2. But are all digits 1 allowed? yes. So dp[98] must be 49 (using 49 ones). So digit 7 works. So first digit 7. Then ans="7", remaining=98, left=49. Next digit: try 9 cost6 -> remaining-cost=92, need 48 digits. 48 digits min 248=96 >92, impossible. 8 cost7 -> 91 need 48 digits, min 96>91. 7 cost3 -> 95 need 48 digits, min 96>95? 96>95, so impossible. 6 cost6 -> 92 need 48 digits, min 96>92, impossible. 5 cost5 -> 93 need 48 digits, min 96>93, impossible. 4 cost4 -> 94 need 48 digits, min 96>94, impossible. 3 cost5? Wait 3 cost5? Actually digit3 cost5, yes. So cost5 -> 93 need 48 digits, min 96>93, impossible. 2 cost5? digit2 cost5, same. 1 cost2 -> 96 need 48 digits, min 96, exactly. So digit1 works (cost2). So second digit 1. Then remaining=96, left=48. Next: try 9 cost6 -> 90 need 47 digits min 94>90, no. 8 cost7 -> 89 need 47 min94>89. 7 cost3 -> 93 need 47 min94>93? 94>93, no. 6 cost6 -> 90 need 47 min94>90. 5 cost5 -> 91 need 47 min94>91. 4 cost4 -> 92 need 47 min94>92. 3 cost5 -> 91 need 47 min94>91. 2 cost5 -> 91 need 47 min94>91. 1 cost2 -> 94 need 47, min 94 exactly, so digit1 works. So third digit 1. Actually we see pattern: after first digit 7 cost3, we used up 3 matches, remaining 98. To achieve length 49 left, we need all ones (cost2) because 22=102>101, impossible. So L max = 50 or maybe 50 not possible? Let's test: 50 digits, sum of costs must be 101. Since each cost is integer at least 2, the sum of costs >= 100. To reach 101, we need exactly one extra match over 100. So we need total sum = 101 = 50*2 + 1. But increasing a digit's cost from 2 to something else adds a non-negative integer delta. If we start with 50 digits of cost 2 (total 100), we need to add 1. But we can't add 1 without changing a digit's cost: changing a digit from cost2 to cost3 adds 1, cost4 adds 2, etc. So we could change one digit from 2 to 3, giving total 101. That is allowed if digit 7 (cost3) is allowed. Yes, 7 is allowed. So that yields length 50. Could we achieve length 50 with a different composition? Possibly. So L=50 is achievable. So the number has 50 digits. So we expect total digits =50. So if first digit is 7, then there are 49 remaining digits. So we should have 7 followed by 49 ones. So the output should be "7" + "1"*49. That would be a string of length 50. The sample shows "7" + 50 ones? That would be 51. Perhaps the sample actually has 49 ones but the representation is ambiguous. Let's count more accurately: The sample: "71111111111111111111111111111111111111111111111111". I can count the ones: after the 7, I see 50 characters? Let's count each character: I'll write them out:
Index: 1:7
2:1
3:1
4:1
5:1
6:1
7:1
8:1
9:1
10:1
11:1
12:1
13:1
14:1
15:1
16:1
17:1
18:1
19:1
20:1
21:1
22:1
23:1
24:1
25:1
26:1
27:1
28:1
29:1
30:1
31:1
32:1
33:1
34:1
35:1
36:1
37:1
38:1
39:1
40:1
41:1
42:1
43:1
44:1
45:1
46:1
47:1
48:1
49:1
50:1
51:1 ?
I'm not sure. Actually it's easier: In many editorial solutions, for N=101 and all digits allowed, answer is '7' + '1'*49. I recall from AtCoder problem that the output in the sample is indeed "7" + 49 ones. The provided sample may have 49 ones but due to formatting it might appear as 50. Let's actually count by copying the exact string: "71111111111111111111111111111111111111111111111111". Count characters: Remove the first '7', we get "1111111111111111111111111111111111111111111111111"? Actually the string after 7: I see double quotes before and after. Let's manually: The text: 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1? That's 49? If I try to count: I'll count groups of 5: 11111 (5), another 11111 (10), 11111 (15), 11111 (20), 11111 (25), 11111 (30), 11111 (35), 11111 (40), 11111 (45), 11111 (50) => 50 ones. Hmm maybe the sample is indeed 50 ones? That would be length 51. But that would imply L=51, which seems impossible. Let's double-check min cost: digit 1 uses 2 matchsticks, digit 7 uses 3. So the absolute minimum matchsticks per digit is 2. So for 51 digits, the minimum total matchsticks is 102. Since N=101 <102, impossible. So L cannot be 51. Therefore the sample output must have 49 ones. So likely the printed string has 49 ones, but I miscounted. Actually, in the string "71111111111111111111111111111111111111111111111111", if you count the characters:
The length of that string as given is 50? Let's calculate: I can copy it into an environment. But I can do: The sample output from AtCoder ABC 118 D is:
777773
71111111111111111111111111111111111111111111111111
654
Yes. I remember that the second output is indeed "7" followed by 49 ones. The number of ones is 49, making total length 50. How many characters in that part? Possibly the string has 50 characters total: '7' + 49 ones = 50 characters. So the string length is 50. In the printed representation, there are 49 ones. So maybe the string as shown has exactly 49 ones. Let's count using Python mental: "1111111111111111111111111111111111111111111111111" would be 49 ones? Let's count by grouping 10: "1111111111" is 10, four such groups would be 40, plus one more group of 9? Actually 49 ones would be 4 groups of 10 (40) plus 9 ones = 49. The sample shows "11111111111111111111111111111111111111111111111111". That appears to have two sets of 10 at the end? Actually the ending "11" suggests maybe 2 ones. Hard to tell. Anyway, trust that the answer is correct.
Our algorithm will produce that.
Example3: N=15, M=3, A=[5,4,6]. Costs: 5:5, 4:4, 6:6. Allowed costs: 5,4,6. Need max length. Minimum cost =4 (digit4). Max length floor(15/4)=3, remainder 3. Can we get 3 digits? 34=12, need 3 more, can adjust. For 3 digits, we need sum 15. Possibilities: 4+5+6=15 -> digits 4,5,6 -> length3. Could we get 4 digits? 44=16>15, so max length=3. Now construct largest number: digits allowed: 6 (largest), 5,4. Greedy: remaining=15, left=3. Try digit6 cost6 -> remaining=9, need dp[9]=2. Can we get 2 digits sum 9? Allowed costs 4,5,6. 5+4=9 -> 2 digits, yes. So digit6 works. ans="6", remaining=9, left=2. Next digit: try 6 cost6 -> remaining=3, need dp[3]=1? dp[3]? Allowed costs: min 4, so 3 can't be achieved (no digit costs 3). So fail. Try 5 cost5 -> remaining=4, need dp[4]=1. digit4 cost4 works. So choose 5? Wait descending order: allowed digits sorted: 6,5,4. So after 6, we try 6 fails, then try 5: cost5, remaining=4, dp[4] should be 1. dp[4] = max digits for 4 matches: digit4 uses 4, so dp[4]=1. So choose 5. ans="65", remaining=4, left=1. Last digit: need a digit that costs exactly 4 -> digit4. So ans="654". Matches example.
Thus algorithm works.
Now complexity: DP O(N * M) = 90000 max, fine. Construction O(L * M) where L up to 5000, also fine.
Edge Cases:
N small, maybe 2. If allowed digits include 1 (cost2), then answer "1". Or if allowed digits only larger costs, but problem guarantees there exists a number.
When dp[i] computed with -inf, need to initialize dp[0]=0, others -1e9.
But careful: In DP, we need to consider that each digit can be used unlimited times (unbounded knapsack). Our DP recurrence dp[i] = max_{d in A} (1 + dp[i - c[d]]) works as long as we compute i from 0 to N (or from smallest cost up) to ensure unbounded combinations. Actually that's like a complete knapsack. We can fill dp array by iterating i from 1 to N and for each i compute max over allowed digits. Since dp[i] depends on smaller indices, and we are not restricting the number of times we use a digit, it's fine because dp[i-c[d]] already considers any number of digits. So we can compute: for i from 1..N: dp[i] = max_{d in A, i>=c[d]} (dp[i - c[d]] + 1), using dp[0]=0, others initially -inf. This is O(N*M). That's correct.
But we must ensure that dp[i] is defined only if there is at least one combination. We'll use -1 to indicate impossible.
Alternatively, we could use a greedy approach: Since we want max length, it's essentially minimizing matchsticks per digit. But because we have a limited set of allowed digits, we may need to adjust for parity or specific sums. So DP is safer.
Now one nuance: The largest integer - we are constructing as string. But note that integer comparison is based on numeric value, not lexicographic if lengths differ, but we already maximize length. So for equal lengths, we maximize lexicographically. Since digits are all positive and from 1-9, lexicographic order (most significant digit first) matches numeric order. So fine.
But note: Could there be a scenario where the maximum length is not unique? Actually dp[N] gives the maximum length. So we always use that length. Then we construct lexicographically largest among those with that length.
Implementation details:
Store cost per digit: int cost[10] = {0,2,5,5,4,5,6,3,7,6}; // index 1-9.
Read N, M.
Read list A. Possibly we sort descending for construction, but also need for DP? Not needed.
For i from 1 to N:
for each digit d in A:
if i >= cost[d] and dp[i - cost[d]] != -INF:
dp[i] = max(dp[i], dp[i - cost[d]] + 1);
After DP, length L = dp[N].
Now construct: string ans = "";
int remaining = N;
for pos from 1 to L:
for d in sorted_A_descending:
if remaining >= cost[d] and dp[remaining - cost[d]] == L - pos:
ans += char('0' + d);
remaining -= cost[d];
break;
Print ans.
Make sure dp[remaining - cost[d]] is not -INF; if it equals the needed length, it's fine.
Edge Cases: dp[remaining - cost[d]] might be -INF; we check equality only if it's exactly L-pos, but if it's -INF it won't match.
Now we should test on given examples.
But there's an important nuance: The DP approach above might be O(N*M) which is okay. However, N can be up to 10000, but M up to 9, so 90k operations. That's trivial.
But we have to ensure that dp[N] is indeed the maximum length. Yes.
Now we can produce final answer.
But there is another nuance: In the problem, it's possible that the number can be huge, but printing as string is fine.
Now I'll produce a solution in Python or C++? The problem statement does not specify language, but we can produce answer in any. Usually on AtCoder, solutions are in Python or C++. I'll produce a solution in Python for readability. But careful with recursion limit? Not needed.
Let's implement in Python.
Implementation steps in Python:
def solve():
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
A = list(map(int, input().split()))
cost = [0,2,5,5,4,5,6,3,7,6] # index 0 unused, 1-9
allowed = set(A)
# DP
INF_NEG = -10**9
dp = [INF_NEG] * (N+1)
dp[0] = 0
for i in range(1, N+1):
for d in allowed:
c = cost[d]
if i >= c and dp[i-c] != INF_NEG:
if dp[i] < dp[i-c] + 1:
dp[i] = dp[i-c] + 1
# dp[N] should be >= 0
L = dp[N]
# Sort allowed digits descending
allowed_sorted = sorted(allowed, reverse=True)
ans = []
rem = N
for i in range(L):
for d in allowed_sorted:
c = cost[d]
if rem >= c and dp[rem - c] == L - i - 1:
ans.append(str(d))
rem -= c
break
print(''.join(ans))
But we need to ensure dp is computed correctly. For dp[20] we get 6. Then construction yields "777773".
Now for N=101, M=9, A includes all digits 1-9. allowed_sorted = [9,8,7,6,5,4,3,2,1]. dp[101] should be 50. Construction yields "7" + 49 ones? Let's test quickly in mind: The first step will pick 7 as we reasoned, because 9,8 fail, 7 works (since dp[98]=49). Then rem=98, left=49. Next digits: try 9 (cost6) -> rem92, need dp[92]=48? Is dp[92] 48? 48 digits min 96, so no. 8->91 need 48 min96>91. 7->95 need 48 min96>95? Actually 96>95, so no. 6->92 need 48 min96>92. 5->93 need48 min96>93. 4->94 need48 min96>94. 3->95 need48 min96>95. 2->95 need48 min96>95. 1->96 need48, min96 exactly. So dp[96] must be 48? 96 matches using 48 ones works, so dp[96]=48. So digit1 works. So ans becomes "71". Then rem=96, left=48. Then similar for each subsequent step: the only digit that works will be 1 because others would require dp less than needed. So we get "7"+"1"*49? Actually after the first 1, we have left 48 more digits, and remaining=96. Next, try 9->90 need 47, min94>90. So only 1 works: cost2 -> 94 need 47, min 94 exactly, so 1 works. So indeed we get all ones. So total digits: first 7, then 49 ones = 50 digits. So ans length 50. Good.
Third example: works.
Now check potential pitfalls: The DP table values might be negative. Ensure we use INF_NEG sufficiently small. Since N max 10000, max length <= 5000, so using -10**9 is safe.
Now, there is also a possibility that we could do DP using a different approach: like prioritize greedy based on cost per digit? But DP is safe.
Now we must output the largest integer, not leading zeros because no zeros.
Now final code.
But wait: There is a subtle point: In the construction step, we check if dp[rem - cost[d]] == L - i - 1. However, dp[rem - cost[d]] might be larger than L - i - 1? Actually if dp[rem - cost[d]] > L - i - 1, that would imply we could form more digits than needed, but since we are using exactly N matches, the total digits would exceed L if we use that? Actually careful: After we choose a digit d, the remaining matches are rem - cost[d]. The maximum number of digits we can form from those matches is dp[rem - cost[d]]. If dp[rem - cost[d]] > L - i - 1, that means we can make more digits than we have slots left. But we cannot use more digits because the total digits would become i + something > L. However, maybe we could combine with our earlier digits to still have total length L? Actually, if we already used i digits, we need exactly L total digits. So we need to fill the remaining slots with exactly L-i digits. dp[rem - cost[d]] is the maximum possible digits we can form with those remaining matches. If the maximum is larger than L-i-1, we might still be able to form exactly L-i-1 digits? Not necessarily; we need existence of a combination of exactly L-i-1 digits that sums to rem - cost[d]. The dp value only tells us the maximum length; it doesn't guarantee that any specific lower length is achievable. However, if the maximum length is greater than required, there might be a way to reduce length by using higher-cost digits, but we need to check if a combination of exactly L-i-1 digits exists. So checking dp[rem - cost[d]] == L-i-1 is not sufficient: we need to ensure that there exists some combination of exactly L-i-1 digits summing to rem - cost[d]. It is possible that dp[rem - cost[d]] > L-i-1 but no combination with exactly L-i-1 digits exists because the maximum length is larger but maybe you cannot achieve exactly that lower length due to parity constraints? In such unbounded knapsack with positive integer costs, if you can achieve a certain maximum length Lmax, can you achieve any length between 0 and Lmax? Not necessarily. For example, allowed digits with costs that are all even? Suppose only digit 2 (cost 2) and digit 4 (cost 4). Then with total matches = 6, you can have: 3 digits of 2 (3 digits, cost6). Maximum length = 3. Can you make 2 digits? 2 digits sum to 6? 2 digits: could be 2+4=6, that's 2 digits. So yes. What about only digit 3 (cost3)? Then with total matches = 6, max length =2 (3+3). Can you make 1 digit? 1 digit cost 6? Not allowed, so no. So dp[6] = 2 (max). If we need exactly 1 digit, we can't. So it's possible that for a given remaining matches, the maximum length is say 5, but we need length 4, but there might be no combination of exactly 4 digits. For instance, allowed digits: only digit 2 (cost2). With total matches = 10, max length =5. Can we get exactly 4 digits? 4 digits need sum 8? Actually 4 digits each cost2 would be 8, but total matches is 10, we need exactly 4 digits summing to 10. Is that possible? 4 digits with cost2 each sum to 8; we could replace one 2 with a higher cost digit, but if only 2 is allowed, then impossible. But if we have only digit2, the only sums are even, but length is variable: for a given length L, the sum must be 2L. So for total matches =10, L=5 gives sum10. L=4 would require sum 8, not 10. So no. So dp[10] =5, but there is no combination of exactly 4 digits that sum to 10. So we need a more precise condition.
Thus, our greedy check using dp[rem - cost[d]] == L - i - 1 may be insufficient if dp[rem - cost[d]] could be greater than required, but we need exactly the required length. However, we are constructing the lexicographically largest number of exactly L digits. At each step, we need to know if there exists a combination of exactly L - i - 1 digits that sums to rem - cost[d]. The condition dp[rem - cost[d]] >= L - i - 1 is necessary, but not sufficient. Moreover, we need that the remaining matches can be partitioned into exactly L - i - 1 digits (not more). Since we are maximizing length, we know that overall L is the maximum length for N. So for any prefix chosen, the remaining matches must be such that the maximum length achievable is exactly the remaining slots? Actually, if we have chosen a prefix and remaining matches = R, and we need to fill exactly K digits (K = L - i), we need to know if there exists a K-digit combination. Since L is the maximum for N, for the prefix we have used some matches, and we have remaining matches R. The total digits we can still get is at most dp[R]. But we need exactly K digits. Note that K is the maximum possible for the original N minus i. However, is it true that if we have a prefix that is part of some optimal solution (max length), then for the remaining R matches, the maximum possible digits is exactly K? Let's think: Suppose we have a full solution with L digits and total matches N. If we take the first i digits of that solution, the remaining part is a combination of L - i digits that sum to R = N - sum(prefix). The maximum number of digits you can form from R is at least L - i (since we have a specific combination). Could it be greater than L - i? If it is greater, that would mean that with R matches, you could form more than L - i digits. Then by combining the prefix i digits with that longer combination, you would get a total of more than L digits using N matches, contradicting that L is the maximum length. Because the prefix i digits plus a longer suffix of length > L-i would give total > L. But note: The longer suffix would also need to sum to R. If there exists a combination of, say, (L-i+1) digits that sum to R, then we could replace the original suffix with that, resulting in total digits i + (L-i+1) = L+1, using the same total matches N, contradicting maximality of L. Therefore, for any prefix that can be extended to an optimal solution (max length), the maximum number of digits achievable from the remaining matches must be exactly the number of remaining slots, not more. Because if it were more, we could increase total length. So in the construction, when we are building greedily, we only consider digits that could be part of some optimal solution. For such digits, we must have dp[rem - cost[d]] == L - i - 1. Conversely, if dp[rem - cost[d]] > L - i - 1, then that digit cannot be part of any optimal solution, because using it would leave a remainder that can produce more digits than needed, but that would allow a longer total length? Actually careful: Suppose we have chosen a digit d, and dp[rem - cost[d]] > L - i - 1. Could there still exist some combination of exactly L - i - 1 digits that sums to rem - cost[d]? Possibly yes, even if the maximum is higher. For example, consider allowed digits: costs {2,3}. N=5, maximum length? Let's compute: allowed digits with costs 2 and 3. For N=5, possible combinations: 2+3 -> 2 digits, length 2; 2+2+? 2+2+? 2+2+? need 1, impossible; 3+? need 2 -> 3+2=5 also 2 digits; so max length =2. But also possibility: use digit 2 only: 2+2+? only 4, can't. So L=2. Now consider constructing the largest number: allowed digits descending: digit with cost3 (maybe digit7? but whatever), digit with cost2 (digit1). Largest digit is the one with cost3, say digit 7. Let's assign: suppose allowed digits are 7(cost3) and 1(cost2). The largest digit is 7. Try greedy: i=0, rem=5, L=2. Try digit7 cost3: rem-cost=2, dp[2] = maximum length from 2 matches: we can form digit1 (cost2) -> 1 digit, so dp[2]=1. That equals L-1=1. So condition holds. So choose 7, then last digit 1, number "71". Works. No problem.
Now consider a scenario where dp[rem - cost[d]] > L - i - 1 but still there is a combination of exactly L - i - 1 digits. For example, suppose allowed costs {2,4}. N=6. Max length? Min cost 2, so 3 digits of 2 =6 -> length 3. Could we have length 2? 2+4=6 -> length 2 as well. So L =3? Wait 3 digits of 2 =6 gives length 3, but length 2 also possible. Which is larger as integer? Longer length is larger, so max length is 3 (since 3 digits > 2 digits). So L=3. Now consider constructing largest number: allowed digits descending: digit with cost4 (say digit4) and digit with cost2 (digit1). Largest digit is 4. Try i=0, rem=6, L=3. Check digit4 cost4: rem-cost=2, dp[2] = maximum from 2 matches: using digit1 (cost2) -> 1 digit. So dp[2]=1. But we need L-1=2. dp[2]=1 !=2, so digit4 fails. Then try digit1 cost2: rem-cost=4, dp[4]? Maximum from 4 matches: can do two digit1s (2+2) -> 2 digits; or one digit4 (4) -> 1 digit. So dp[4]=2. That equals L-1=2. So we pick 1. Then remaining construction yields something like "1??". Actually we get "1" then from rem=4, left=2. Then try digit4 cost4: rem-cost=0, need dp[0]=0? Actually L-i-1=1? Wait we have used 1 digit, left=2, so at next step i=1, left=2? Actually total L=3, after first digit we need 2 digits. For the second digit, we check from descending: digit4 cost4: rem=4, cost4, rem-cost=0, need dp[0] to be 1? Actually we need after picking this digit, remaining digits = L - i -1 = 3-1-1=1. So we need dp[0] =1? No, we need dp[rem-cost] = dp[0] =? dp[0] is defined as 0 (0 digits). But we need exactly 1 digit left, so we need dp[0] ==1? That's impossible. So digit4 fails because after using it we have used 2 digits and left matches 0, but we need exactly 1 more digit? Wait we need total L=3 digits. If we choose digit4 as second digit, we would have used digits: first digit1 (cost2), second digit4 (cost4), total cost 6, matches used = 2+4=6, but that's already total matches N=6, and we have used 2 digits, but we need total 3 digits. So cannot because we would exceed matches if we try to add another digit. So indeed, after second digit, we need exactly one more digit but no matches left, so it's invalid. So dp[0] =0, but we need 1, so condition fails. So we must pick digit1 again: cost2, rem-cost=2, need dp[2] =1. dp[2]=1 (digit1). Works. Then last digit: rem=2, need one digit with cost2, digit1. So number is "111". That's the lexicographically largest? Actually could there be "21"? Not allowed. So "111" is correct.
Now can we have a scenario where dp[rem - cost[d]] > L - i - 1 but there exists a combination of exactly L - i - 1 digits? Let's try to construct such a case. Suppose allowed digits: costs 2 and 3. N=8. Max length? Min cost 2: 4 digits of 2 =8 => length 4. Also 3+2+3? 3+3+2=8 => 3 digits. So L=4. Now consider prefix: i=0, rem=8, L=4. Try digit with cost3 (largest). rem-cost=5. dp[5] =? With costs 2 and3, we can form: 2+3=5 => 2 digits, also maybe 2+2+? 2+2+? need 1, so only 2 digits. So dp[5]=2. L-1=3. Not equal, so digit3 fails. Try digit2 cost2: rem-cost=6, dp[6] =? 2+2+2=6 => 3 digits; also 3+3=6 => 2 digits. So dp[6]=3. That equals L-1=3, so digit2 works. So condition holds. No case where dp > needed.
We need to find a case where dp[rem-cost] > needed but there is still a combination of exactly needed length. That would require that the maximum length is larger than needed, but also that you can achieve the needed length. But if maximum length > needed, then you can possibly achieve needed length, but not always? For unbounded knapsack, if you can achieve a length Lmax, can you always achieve any length between some minimum and Lmax? Not necessarily; it depends on the set of costs. For example, allowed digits: only digit with cost 3 and digit with cost 4. Let's consider: costs {3,4}. What lengths can we achieve for a given total? For total matches T, we want to represent T as sum of L numbers each either 3 or 4. This is a coin change problem but with number of coins variable. The set of achievable (T, L) pairs is not necessarily all L between min and max. But for a fixed T, the achievable lengths are those L such that there exists nonnegative integers a,b with a+b=L and 3a+4b=T. So for given T, L is determined by a = 4L - T? Actually from equations: a+b = L, 3a+4b = T => 3a+4(L-a)= T => 3a +4L -4a = T => 4L - a = T => a = 4L - T. Since a>=0 integer, b = L - a >=0. So L is achievable iff 4L - T >=0 and <= L, i.e., T between 3L and 4L inclusive, and also 4L - T must be integer (always integer). So for a given T, achievable lengths L satisfy 3L <= T <= 4L. So not every L between min and max may be possible; but the maximum L for given T is floor(T/3) perhaps? Actually max L is when using all 3's: Lmax = floor(T/3)? But also need to check if combination exists. For T=10, possible L: from min using 4's: ceil(T/4)=3, max using 3's: floor(T/3)=3. So only L=3? Let's see: 3+3+4=10 -> L=3, works. L=2? 4+4=8, need 2 more; 3+4=7 need 3; 3+3=6 need 4; none sum to 10, so L=2 not possible. So for T=10, only L=3. So maximum L =3, and it's the only one. So in this case, for any T, if there is a combination, the maximum length is often the only length? Not necessarily. Let's try T=12: possibilities: 3+3+3+3=12 L=4; 4+4+4=12 L=3. So both L=3 and L=4 possible. So for T=12, max L=4. Now consider constructing for overall N such that L is max. Suppose allowed digits {3,4} (only two digits). Let N=12, max L=4. Greedy: we want largest number. Suppose digits mapping: cost3 corresponds to some digit, say 7? Actually cost3 is digit7, cost4 is digit4. So allowed digits 7 (cost3) and 4 (cost4). Largest digit is 7. Check if we can start with 7: rem=12, cost3 -> rem=9, need dp[9] =? For 9 matches, with costs 3,4: 3+3+3=9 gives L=3; can we get 3? Yes, dp[9] = max length? Using 3's, we can get 3 digits. So dp[9]=3. Needed after first digit: L-1=3. So dp[9]=3, works. So choose 7. So construction works.
Now consider a case where dp[rem-cost] > needed. For that, we need a T where maximum length > needed and there also exists a combination of needed length. Let's try allowed digits costs {2,5}. For T=10, combinations: 2+2+2+2+2=10 -> L=5; 5+5=10 -> L=2. So max L=5, but also L=2 is possible. So dp[10]=5. Now consider a larger N where max L = L_total. Suppose N=12? Let's find N where L_total is max, and see if a prefix can lead to remainder where dp > needed. Use costs {2,5}. Find N such that max L is some number. For N=12, combos: 2*6=12 L=6; 5+5+2=12 L=3; 5+2+2+? 5+2+2+2=11 need 1; not. So max L=6. Is there a combination with length 5? Need to solve 2a+5b=12, a+b=5 => a=5-b, so 2(5-b)+5b =10+3b =12 => 3b=2 -> b not integer. So L=5 not possible. So for T=12, max L=6, and only L=6? Also L=3? 5+5+2=12 gives L=3, so L=3 possible as well. So lengths possible: 3 and 6. So dp[12]=6.
Now suppose overall N=12, L_total=6. Consider constructing. Allowed digits: say digit1 cost2, digit5 cost5. Largest digit is 5 (cost5). Try prefix digit5: rem=7, need dp[7] =? For 7 matches, combos: 2+5=7 L=2; 2+2+2+? 2+2+2=6 need 1, not; so dp[7]=2. Needed L-1=5. So dp[7]=2 !=5, fails. So digit5 not chosen. Next digit1 cost2: rem=10, need dp[10]=5? dp[10]=5? Actually dp[10]=5 (since 2*5=10). So dp[10]=5 equals L-1=5, works. So we pick 1. So no problem.
Now we need a scenario where dp[rem-cost] > needed. For that, we need remainder R such that the maximum length for R is greater than K (needed), but also there is a combination of exactly K digits. For that, there must be at least two achievable lengths for R: one equal to K and one larger. So dp[R] > K, and also there exists a combination of exactly K digits. For example, with costs {2,5}, R=10, dp[10]=5, and also K=2 is possible? Actually K=2 is possible (5+5). So dp[10]=5 >2, and a combination of exactly 2 digits exists. So if we needed K=2, then dp[10]=5 >2, but there is a combination of 2 digits. So in a greedy step, we might be at a state where we need to fill K digits, and for a candidate digit d, R = rem - cost[d], we have dp[R] > K, but there exists some combination of exactly K digits for R. The question is: would such a digit d ever be part of an optimal solution? Possibly yes, if we can then combine with the prefix to get total L digits? Let's try to construct a full example where overall N has max L, and at the first step, a digit d leads to remainder R with dp[R] > L-1, but there is also a combination of exactly L-1 digits for R. Could that digit d be part of an optimal solution? If so, our check dp[R] == L-1 would reject it incorrectly, while a larger digit might be valid and yield a lexicographically larger number. So we need to verify if such a situation can occur.
There exists a combination of exactly L-1 digits that sum to R.
And the combination of d plus that L-1 digits yields total digits L, i.e., total N.
If such d exists, then it's a valid optimal solution with first digit d (and not necessarily using the maximum length for R). Since dp[R] > L-1, it means there exists a combination of length > L-1 for R, but we are not forced to use that; we can use a shorter combination of exactly L-1 digits if it exists. So d can be part of an optimal solution. In our greedy algorithm, when we check dp[R] == L-1, we would reject d because dp[R] != L-1, even though a combination of exactly L-1 digits exists. That would cause us to choose a smaller digit instead, possibly missing a larger first digit. So we need to determine if such scenario can happen under the given cost constraints and allowed digits.
We need to examine the nature of the DP: dp[i] is the maximum number of digits for i. The existence of a combination of exactly k digits for i is not directly given by dp. We might need to check for existence of exactly k digits. But can we guarantee that if dp[i] >= k, then there exists a combination of exactly k digits? Not necessarily. For instance, with costs {2,5}, for i=10, dp[10]=5 (max). But does there exist a combination of exactly 4 digits? Let's check: need a+b=4, 2a+5b=10 => a=4-b, 2(4-b)+5b=8+3b=10 => 3b=2 -> b not integer. So no combination of exactly 4 digits. So dp[10] =5, but length 4 is not achievable. So dp[i] >= k does not imply existence of exactly k digits. So we need to be careful.
Now could there be a case where for the remainder R, dp[R] > L-1, but exactly L-1 digits is achievable? That would require that R has at least two achievable lengths: one equal to L-1 and one larger. So dp[R] >= L-1+1 = L. But if exactly L-1 is achievable, then dp[R] is at least L-1. It could be strictly greater if there is also a combination with more digits. For example, R=10, L-1=4? No, L-1=4 not achievable. Let's find an R where both lengths exist: For costs {2,5}, lengths achievable for R=10: 2 and 5. So lengths 2 and 5. So if L-1=2, then dp[10]=5 >2, and exactly 2 digits is achievable. So scenario: N such that L total is something, and after using a digit d, we need K = L-1 = 2, and R=10. That means N = cost[d] + 10, and total L = 1 + 2 = 3. So N = cost[d] + 10, and max length for N is 3. But can max length for N be 3? If N is cost[d] + 10, we need to check that there is no longer combination for N. For example, let d be a digit with cost, say, 3 (digit7) allowed? But in {2,5} set we only have digits cost2 and 5. Let's use allowed digits set that includes both 2 and 5, and maybe also a digit with cost something else? To get a larger first digit, we need a digit with cost maybe higher than 2. In our scenario, we need d to be a large digit (so that we want to pick it). Suppose allowed digits include a digit with cost 3 (like 7) and also 2 and 5. But then the set of costs is {2,3,5}. That might produce different possibilities.
Let's design a concrete potential counterexample.
We need N such that:
L = max digits for N.
There exists digit d (with large value) such that:
R = N - cost[d]
K = L - 1
There exists combination of exactly K digits summing to R.
But dp[R] > K (so max length for R is > K).
Also, any solution with first digit d is valid and yields total L digits.
Additionally, the greedy algorithm that checks dp[R] == K would reject d because dp[R] != K.
Would d still be part of some optimal solution? Yes, if there exists a combination of K digits for R. So we need to check if such a scenario can actually occur given that L is the maximum length for N.
If dp[R] > K, then from R we can get more than K digits. So we could form a combination of length dp[R] from R. Then total digits would be 1 + dp[R] > 1 + K = L. That would contradict that L is the maximum for N, because we would have a longer total length: using digit d and then the maximum-length suffix yields total > L. However, is it guaranteed that the combination achieving dp[R] uses exactly dp[R] digits and sums to R? Yes, by definition. So if dp[R] > K, then we can construct a number with 1 + dp[R] digits that uses exactly N matches. That would mean there exists a number with length > L, contradicting L being maximum. Therefore, for any digit d that can be part of some optimal solution (i.e., there exists a suffix of length K summing to R), we must have that the maximum length for R is exactly K. Because if there was a longer suffix, we could extend to a longer total length, contradicting maximality. Wait, careful: Could it be that the longer suffix from R uses digits that are not allowed together with d due to digit set constraints? No, the digits are the same set. So if dp[R] > K, then there is some combination of digits for R with length dp[R] > K. That combination uses only allowed digits. Then prefix d + that combination yields a valid number with length 1+dp[R] > L, and total matches = cost[d] + R = N. So that would be a number with more digits than L, contradicting that L is the maximum possible length for N. Therefore, L cannot be the maximum if such d exists. But here d is part of an optimal solution; that means there exists at least one suffix of length K that works. However, the existence of a longer suffix (dp[R] > K) does not negate the existence of a suffix of length K, but it does imply that there is a way to get a longer total length, thus L would not be the maximum. Hence, if L is truly the maximum, then for any R = N - cost[d] where there exists a suffix of length K (i.e., d can be part of some optimal solution), we must have that dp[R] = K. Because if dp[R] > K, then there is a better total length. Therefore, the condition dp[rem - cost[d]] == L - i - 1 is necessary for d to be extendable to an optimal solution, given that we have already determined L as the maximum length. In other words, any prefix that can be completed to an optimal solution must satisfy that the remainder's maximum length equals the remaining number of digits. Because otherwise you could get a longer overall number.
Thus, our greedy check using equality is correct.
We can also argue: Suppose we have a partial prefix using matches P, remaining matches R, and we have already used i digits. Let K = L - i be the number of digits still to be placed. If there exists a way to complete to L digits, then any optimal completion uses exactly K digits. The maximum digits achievable from R is at least K (since we have a specific completion). If it were greater than K, then we could produce a completion with more than K digits, giving total > L, contradicting maximality of L. Therefore, dp[R] must equal K. So the condition is necessary. Conversely, if dp[R] == K, then there exists some completion achieving K digits (since dp[R] is defined as the maximum; but wait, dp[R]==K means the maximum achievable digits from R is K. But does it guarantee existence of a combination of exactly K digits? Yes, because dp[R] is defined as the maximum number; by definition there is at least one combination achieving that maximum, i.e., exactly K digits. So it's sufficient. So indeed the equality condition is both necessary and sufficient for existence of a completion that yields total length L. Therefore, our greedy algorithm using dp[rem - cost[d]] == L - i - 1 is correct.
Thus we can stick with that.
Now the DP we used gives us the maximum length. However, there is a nuance: In DP we used dp[i] = max number of digits for i matches. That's fine. But we must be careful that dp[i] is indeed the maximum; we compute it correctly.
Now we can finalize.
But the problem constraints: N up to 10000, M up to 9. So DP with O(N*M) works.
But we need to be careful about integer overflow? Not in Python.
Now produce final answer.
However, there is another approach: Since we are to output the largest integer, we can also use a greedy algorithm based on cost per digit, but because of allowed set, DP is safe.
Now, let's implement in Python. We'll read input, compute cost list, allowed set, DP, then construct.
But note: The problem input may have A_i in any order; we need to sort descending for construction. Also, DP: Since we are using unlimited digits, we need to ensure we consider all allowed digits.
Potential optimization: Instead of DP table of size N+1, we could compute dp from 0 to N. Use list of -1 for impossible.
Implementation details:
def solve():
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
A = list(map(int, input().split()))
cost = [0,2,5,5,4,5,6,3,7,6]
# DP
dp = [-1] * (N+1)
dp[0] = 0
for i in range(1, N+1):
max_digits = -1
for d in A:
c = cost[d]
if i >= c and dp[i-c] != -1:
if dp[i-c] + 1 > max_digits:
max_digits = dp[i-c] + 1
dp[i] = max_digits
# Now dp[N] is max length
L = dp[N]
# Sort allowed digits descending for greedy
A_sorted = sorted(A, reverse=True)
ans = []
rem = N
for i in range(L):
for d in A_sorted:
c = cost[d]
if rem >= c and dp[rem - c] == L - i - 1:
ans.append(str(d))
rem -= c
break
print(''.join(ans))
But we must be cautious: In DP we used dp[i] = -1 for impossible. But we need to ensure that dp[N] is not -1 (guaranteed). This should work.
Testing with examples.
Now, check performance: For each i we iterate over M digits, that's fine.
But note: This DP may be suboptimal if we use Python loops, but N=10000, M=9, so 90k iterations, trivial.
Now final answer.
Wait, there is a nuance: The input says: "Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 ≤ A_i ≤ 9)." That means we can only use those digits. So correct.
Now, we should think about the case where there are multiple digits with same cost. For example, digit 2 and 3 both cost 5. In that case, when constructing, we try larger digit first. That's fine.
Now, final code ready.
But I want to double-check the DP for unbounded knapsack: In the recurrence as written (for i from 1 to N, for each d, if i>=c and dp[i-c] != -1, compute candidate), we may not consider the order of d; but we take max over d. That's fine. However, there is a subtlety: Because we are iterating i from 1..N, we might compute dp[i] based on earlier dp values that themselves were computed using unlimited digits, so it's correct for unbounded knapsack.
Alternatively, we could use a BFS or DP from 0 outward: for i from 0..N-1, if dp[i]!=-1, then for each d, if i+c <= N, dp[i+c] = max(dp[i+c], dp[i]+1). That may be simpler. But both are fine.
Now, one more check: The problem guarantees that there exists an integer. So dp[N] >= 0.
Now, the output might be huge (up to 5000 digits), but printing string is fine.
Case 2: N=2, M=1, A=[2]? But 2 cost5 >2, impossible. Not allowed by guarantee.
Case 3: N=5, M=2, A=[1,7]. cost1=2, cost7=3. Max length? 2+3=5 => 2 digits. Could also 2+2+? 2+2+? 2+2=4 need1 impossible; 3+? need2 => 3+2=5 2 digits. So L=2. Now construct: allowed sorted descending: [7,1]. Try digit7 cost3: rem=2, dp[2]=? dp[2] with allowed digits: can use digit1 cost2 => dp[2]=1. Needed L-1=1. So works. So ans="71". That is largest? Alternative "17" is smaller. Good.
Case 4: N=8, M=2, A=[1,4]? cost1=2, cost4=4. Max length? 4 digits: 2+2+2+2=8 => L=4. Could there be 3 digits? 4+2+2=8 => 3 digits also. But max length is 4. So L=4. Sorted descending: [4,1]. Try digit4 cost4: rem=4, dp[4] =? allowed: digit4 cost4 => 1 digit; digit1 cost2 => can make 2+2=4 => 2 digits? Actually 2+2=4 => two digit1's, but each digit1 cost2, so 2 digits; so dp[4] = max(1,2) = 2. Needed L-1=3. dp[4]=2 !=3, so digit4 fails. Try digit1 cost2: rem=6, dp[6] =? For 6: using 1's: 2+2+2=6 => 3 digits; using 4+2=6 => 2 digits; so dp[6]=3. Needed L-1=3. So works. So first digit 1. Then rem=6, left=3. Now try digit4 cost4: rem-cost=2, dp[2]=1? dp[2] = 1 (digit1). Needed L-i-1 = 2? Actually i=1, L=4, so left after this digit = 3? Wait we've used 1 digit, need total 4, so remaining digits to place = 3. If we pick digit4 now, then after that we would have used 2 digits, need 2 more. So we need dp[rem - cost] == 2? Let's compute: after first digit 1, rem=6. For next digit, we try 4: cost4 => new rem = 2, need dp[2] = 2? Actually we need remaining digits after this choice = L - i -1 = 4 -1 -1 = 2. So we need dp[2] = 2. But dp[2] = 1, not 2. So digit4 fails. Try digit1 cost2: rem-cost=4, need dp[4] = 2? Wait after picking second digit (i=2), remaining digits needed = 4-2 =2. So we need dp[4] =2. dp[4] = 2 (two ones). So digit1 works. So second digit 1. Then rem=4, left=2. Next: try digit4 cost4: rem-cost=0, need dp[0] = 0? Wait after picking third digit, we would have used 3 digits, need 1 more. So we need dp[0] =1? No, we need dp[0] = 1? Let's step: currently i=2 (we have ans "11"), rem=4, left=2 (need 2 more digits). For third digit, we try digit4: cost4, rem-cost=0, after picking, used digits =3, need remaining digits = 1. So we need dp[0] = 1? But dp[0] is 0. So digit4 fails because we cannot place a digit with zero matches left and still have one more digit to place. So digit1: cost2, rem-cost=2, need dp[2] = 1 (since after picking third digit, we need 1 more). dp[2]=1 works. So third digit 1. Then rem=2, left=1: pick digit1 cost2, works. So number is "1111". That is indeed the largest? Could there be "211"? Not allowed. So "1111" is correct.
Now consider scenario where the greedy picks the largest digit possible but we need to ensure that dp[rem-cost] equals L - i - 1. That is fine.
Thus the solution is correct.
Now we should produce final answer.
But note: In the DP, using dp as list of ints, initializing with -1 is fine because max length cannot be negative.
Now time complexity: O(NM) = 90k, plus construction O(LM) <= 5000*9 = 45k. So very fast.
Now we should also consider memory: dp array size 10001, fine.
Now let's think about possible pitfalls: Input may have multiple test cases? No, single test case.
Now let's provide the solution in Python.
But there is one more nuance: The problem may require handling large output efficiently. Using string concatenation via list and join is good.
Now final code.
I will also add a note: We could pre-sort allowed digits descending once.
Now I'll write the solution.
But wait, there might be an alternative: Instead of DP, we could use BFS or Dijkstra? Not needed.
Now final answer.
Now I will produce the final message with explanation and code.
Given the format: The assistant should output final answer with code in Python.
Thus, final output.
```python
import sys
def solve() -> None:
input = sys.stdin.readline
N, M = map(int, input().split())
A = list(map(int, input().split()))
code
# matchstick cost for digits 1..9
cost = [0, 2, 5, 5, 4, 5, 6, 3, 7, 6]
# ---------- DP: maximum number of digits for exact matchstick count ----------
dp = [-1] * (N + 1)
dp[0] = 0 # 0 matches -> 0 digits
for i in range(1, N + 1):
best = -1
for d in A:
c = cost[d]
if i >= c and dp[i - c] != -1:
cand = dp[i - c] + 1
if cand > best:
best = cand
dp[i] = best
max_len = dp[N] # guaranteed to be >= 0
# ---------- Greedy construction of the largest number ----------
# sort allowed digits in descending order (largest digit first)
A_sorted = sorted(A, reverse=True)
ans = []
remaining = N
for pos in range(max_len):
for d in A_sorted:
c = cost[d]
if remaining >= c and dp[remaining - c] == max_len - pos - 1:
ans.append(str(d))
remaining -= c
break
print(''.join(ans))
49=98. So the rest must be all ones. So the greedy algorithm will pick 7 then all ones. But example output shows: "71111111111111111111111111111111111111111111111111". That is 1 after 7, then 48 ones? Actually total digits 50: first digit 7, then 49 digits? Wait count: after first digit, length left 49, we should have 49 digits after it. But example output shows: 7 followed by 49 ones? Let's count: "7" then "1" repeated? The output: "71111111111111111111111111111111111111111111111111". How many ones? Let's count: The string length seems long. Write: 7 then 49 ones? Let's compute: N=101 -> max length 50. So total digits = 50. So after 7, there are 49 digits. The output shows a 7 then 49 ones? But they printed "71111111111111111111111111111111111111111111111111". That appears to be 7 then 50 ones? Actually let's count the ones in that string: The string is "7" + "111...". The length given: maybe they have 50 digits total? Let's check manually: The output example:
777773 (first example) is length 6. Second: "71111111111111111111111111111111111111111111111111". I could count: I see "7" then a bunch of 1s. How many 1s? The pattern: "71111111111111111111111111111111111111111111111111". After 7, there are likely 50 ones? Actually if we have 50 digits total, and first is 7, then 49 ones would yield a string of length 50. But the printed string appears to have maybe 50 ones? Let's count from the text: "71111111111111111111111111111111111111111111111111". I see "7" then 50? Actually the text: after 7, there is "1" repeated many times. The length of the ones part: The string is represented with 52 characters? Might be easier to note that they might have output exactly 50 digits. Since they wrote "71111111111111111111111111111111111111111111111111". Counting: The ones part from the sample: I see "1111111111111111111111111111111111111111111111111"? Actually let's copy: "71111111111111111111111111111111111111111111111111". If we count manually: after the 7, we have "1" repeated. I'll count: break into groups: "1111111111" (10), "1111111111" (10) ->20, "1111111111" ->30, "1111111111"->40, "1111111111"->50, plus maybe extra? Actually there are 5 groups of 10 = 50 ones? But we have a leading 7, so total 51 digits. But that would be weird. Let's check precisely: In the problem statement on AtCoder (I suspect this is from AtCoder ABC 054 C? Actually similar to AtCoder ABC 113? Wait it's from AtCoder "Matchsticks" problem? Probably from AtCoder "ABC 054 C"? I recall a problem "ABC 054 C - One-stroke Path"? Not that. There is a known problem "ABC 118 D - Match Matching" which is exactly this. Yes, it's AtCoder ABC 118 D - Match Matching. In that problem, N is up to 10000, M up to 9, digits have match counts: 1:2,2:5,3:5,4:4,5:5,6:6,7:3,8:7,9:6. The examples match exactly. Let's check the second example from ABC 118 D: Input: 101 9 1 2 3 4 5 6 7 8 9, Output: 71111111111111111111111111111111111111111111111111. I recall that output indeed has 50 ones? Actually I think it has 49 ones after 7? Let's verify: In the editorial, they used DP and greedy. Typically the answer for that case is: first digit 7, then 49 ones? But I think the output length is 50 digits: 7 + 49 ones = 50 digits. However the sample output may show 7 followed by 49 ones, but the string representation might be ambiguous. If you count characters in the sample: "71111111111111111111111111111111111111111111111111". That looks like 7 then 50 ones because there are 50 '1's? Actually count: I'll copy into a text editor mentally: The string after 7: there is "1" repeated. In the given text: "11111111111111111111111111111111111111111111111111". That's 50 characters? Let's count: group by 10: "1111111111" =10, then "1111111111"=10 (20), then "1111111111"=10 (30), then "1111111111"=10 (40), then "1111111111"=10 (50). So yes 50 ones after the 7, making total 51 digits. But that contradicts our reasoning. Let's recalc: N=101. Min cost digit is 1 (cost 2). Max length? Let's compute using DP: We want maximum number of digits L such that we can find a combination of L digits with total cost 101. The maximum L cannot exceed floor(101/2)=50 because min cost is 2. So L <= 50. Could L be 51? 51