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(long long i=0;i<(n);i++)
#define REP1(i,n) for(long long i=1;i<=(n);i++)
#define MAXN 10000
typedef long long ll;
int num[10]={90,20,50,50,40,50,60,30,70,60};
int n,m;
vector<pair<int,int>> vec;
int dp[10][MAXN];
typedef pair<int,int> pii;
bool mysort(const pii& a, const pii& b){
	if(a.second==b.second) return a.first>b.first;
	else return a.second<b.second;
}
vector<pii> inuse;
vector<int> res;
bool found=false;
bool remcal(int rem){
	if(rem<0) {
		return false;
	}
	else if(rem==0) return true;
	REP(i,inuse.size()){
		res.push_back(inuse[i].first);
		if(remcal(rem-inuse[i].second)){
			return true;
		}
		else res.pop_back();
	}
	return false;
}

bool mysort2(int a,int b){
	return a>b;
}

int main(){
	cin>>n>>m;
	REP(i,m){
		int temp;
		cin>>temp;
		num[temp]/=10;
	}
	REP(i,10){
		if(num[i]<10) vec.push_back(pair<int,int>(i,num[i]));
	}
	sort(vec.begin(),vec.end(),mysort);
	
	int lastnum=-1;
	for(auto ite=vec.begin();ite!=vec.end();ite++){
		if(ite->second != lastnum){
			inuse.push_back(*ite);
			lastnum=ite->second;
		}
	}
	
	int remain=n;
	
	if(!remain%inuse[0].second){
		REP(i,remain/inuse[0].second) cout<<inuse[0].first;
		cout<<endl;
		return 0;
	}else{
		REP(i,remain/inuse[0].second) res.push_back(inuse[0].first); 		remain=remain%inuse[0].second;
		int popn=res.back();
		res.pop_back();
		remain+=num[popn];
		while(!remcal(remain)){
				int popnum=res.back();
				res.pop_back();
				remain+=num[popnum];
			
		}
	}
	sort(res.begin(),res.end(),mysort2);
	REP(i,res.size()) cout<<res[i];
	cout<<endl;

	
    return 0;

}