module mod_stack
  implicit none
  type t_node
    private
    integer :: item
    type(t_node), pointer :: prev => null()
    type(t_node), pointer :: next => null()
  end type
  type t_stack
    private
    integer :: num = 0
    type(t_node), pointer :: head => null()
    type(t_node), pointer :: tail => null()
  contains
    procedure :: push => push
    procedure :: pop => pop
    procedure :: peek => peek
    procedure :: clear => clear
    procedure :: size => size_of
  end type
contains
  function new_node(item) result(node)
    integer, intent(in) :: item
    type(t_node), pointer :: node
    allocate(node)
    node%item = item
  end
  subroutine push(this,item)
    class(t_stack), intent(inout) :: this
    integer, intent(in) :: item
    type(t_node), pointer :: node
    node => new_node(item)
    if (associated(this%head)) then
      node%prev => this%tail
      this%tail%next => node
    else
      this%head => node
    end if
    this%tail => node
    this%num = this%num+1
  end
  function pop(this) result(item)
    class(t_stack), intent(inout) :: this
    integer :: item
    type(t_node), pointer :: node
    item = this%tail%item
    node => this%tail%prev
    deallocate(this%tail)
    this%tail => node
    if (associated(node)) then
      node%next => null()
    else
      this%head => null()
    end if
    this%num = this%num-1
  end
  function peek(this) result(item)
    class(t_stack), intent(in) :: this
    integer :: item
    item = this%tail%item
  end
  subroutine clear(this)
    class(t_stack), intent(inout) :: this
    type(t_node), pointer :: node, prev
    if (.not.associated(this%tail)) return
    node => this%tail
    do while (associated(node%prev))
      prev => node%prev
      deallocate(node)
      node => prev
    end do
    this%head => null()
    this%tail => null()
    this%num = 0
  end
  integer function size_of(this)
    class(t_stack), intent(in) :: this
    size_of = this%num
  end
end module mod_stack
program match_matching
  use mod_stack
  implicit none
  type(t_stack) :: stack
  integer :: n, m, i, j, dp(0:10000) = -1
  integer, dimension(9) :: a = 0, x = 0, p = (/2,5,5,4,5,6,3,7,6/)
  read(*,*) n, m
  read(*,*) a(1:m)
  do i = 1, m
    x(a(i)) = x(a(i))+1
  end do
  m = 0
  do i = 9, 1, -1
    if (x(i) == 0) cycle
    m = m+1
    a(m) = i
  end do
  dp(0) = 0
  do i = 1, n
    do j = 1, m
      if (i < p(a(j))) cycle
      dp(i) = max(dp(i),dp(i-p(a(j))))
    end do
    if (dp(i) >= 0) dp(i) = dp(i)+1
  end do
  i = n
  do while (i > 0)
    do j = 1, m
      if (i-p(a(j)) < 0 .or. dp(i-p(a(j))) /= dp(i)-1) cycle
      i = i-p(a(j))
      call stack%push(a(j))
      exit
    end do
  end do
  x = 0
  do while (stack%size() > 0)
    i = stack%pop()
    x(i) = x(i)+1
  end do
  do i = 9, 1, -1
    do j = 1, x(i)
      write(*,'(i0)',advance='no') i
    end do
  end do
  write(*,*)
end program match_matching