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

Solution in C++14 (GCC 5.4.1) (judge verdict: Wrong Answer)

#include <bits/stdc++.h>
using namespace std;
#define REP(i, n) for(int i = 0; i < n; i++)
#define REPR(i, n) for(int i = n - 1; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i <= n; i++)
#define FORR(i, m, n) for(int i = m; i >= n; i--)
#define SORT(v, n) sort(v, v+n);
#define VSORT(v) sort(v.begin(), v.end());
#define ll long long
#define pb(a) push_back(a)

ll mod = 1e9 + 7;
using pii = pair<int, int>;

ll dp[10001];

int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);

  ll n, m;
  cin >> n >> m;

  ll ms[9] = {2, 5, 5, 4, 5, 6, 3, 7, 6};
  ll use[8] = {}, used[10] = {};

  ll a[m];
  REP(i, m){
    cin >> a[i];
    use[ms[a[i] - 1]]++;
    used[a[i]]++;
  }

  vector<int> numst;
  REP(i, 8){
    if(use[i]) numst.pb(i);
  }
  
  REP(i, n + 1) dp[i] = -1;
  dp[0] = 0;
  REP(i, numst.size()) dp[numst[i]] = 1;

  for(int i = 2; i <= n; i++){
    REP(j, numst.size()){
      if(i - numst[j] >= 0){
        if(dp[i - numst[j]] + 1 > dp[i]){
          dp[i] = dp[i - numst[j]] + 1;
        }
      }
    }
  }
  ll tmp = n;
  vector<int> anss;
  REP(i, dp[n]){
    REP(j, numst.size()){
      if(dp[tmp - numst[j]] == dp[tmp] - 1){
        anss.pb(numst[j]);
        tmp -= numst[j];
        break;
      }
    }
  }

  int num[8] = {0, 0, 1, 7, 4, 2, 6, 8};
  if(used[3]) num[5] = 3;
  if(used[5]) num[5] = 5;
  if(used[9]) num[6] = 9;

  ll lan = anss.size();
  int ansset[10] = {};
  REP(i, lan){
    ansset[num[anss[i]]]++;
  }

  vector<char> ccc;

  REP(i, 10){
    REP(j, ansset[i]){
      ccc.pb(i + '0');
    }
  }

  ll cll = ccc.size();
  REP(i, cll){
    cout << ccc[cll - 1 - i];
  }
  return 0;
}