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 Rust (1.15.1) (judge verdict: Runtime Error)

#![allow(unused)]

use std::{cell, cmp, collections, fmt, ops};

use cell::{Cell, RefCell};
use cmp::Ordering::{self, Equal, Greater, Less};
use collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
use fmt::{Debug, Display};
use ops::{
    Add, AddAssign, Deref, DerefMut, Div, DivAssign, Mul, MulAssign, Neg, Not, Sub, SubAssign,
};

// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        _input_inner!(iter, $($r)*)
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        _input_inner!(iter, $($r)*)
    };
}

macro_rules! _input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = _read_value!($iter, $t);
        _input_inner!($iter $($r)*)
    };

    ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = _read_value!($iter, $t);
        _input_inner!($iter $($r)*)
    };
}

macro_rules! _read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(_read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| _read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        _read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        _read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

#[cfg(feature = "debug")]
macro_rules! d {
    ($val:expr) => {
        match $val {
            tmp => {
                eprintln!("[{}] {} = {:#?}", line!(), stringify!($val), &tmp);
                tmp
            }
        }
    };
}

#[cfg(not(feature = "debug"))]
macro_rules! d {
    ($val:expr) => {
        $val
    };
}

mod num {
    //
}

macro_rules! vmin {
    ($x: expr, $y: expr) => { cmp::min($x, $y) };
    ($x: expr, $($args: expr),*) => { cmp::min($x, vmin!($($args),*)) };
}

macro_rules! vmax {
    ($x: expr, $y: expr) => { cmp::max($x, $y) };
    ($x: expr, $($args: expr),*) => { cmp::max($x, vmax!($($args),*)) };
}

mod bits {
    pub fn is_high(bits: u64, pos: u64) -> bool {
        bits & (1 << pos) != 0
    }

    /// len(0b1010) = 4
    /// len(0b1) = 1
    /// len(0b0) = 0
    pub fn len(bits: u64) -> usize {
        for b in 0..64 {
            if is_high(bits, 63 - b) {
                return (64 - b) as usize;
            }
        }

        return 0;
    }
}

fn main() {
    input!(
        matchstick_num: usize,
        numbers_num: usize,
        numbers: [i32; numbers_num]
    );

    let digits_num_max = matchstick_num / 2;

    // dp[n][d]: the max number that can be created with n matchsticks, and whose #digit is d.
    let mut dp = init_dp_table(matchstick_num, digits_num_max, &numbers);

    // dp[n][d] = max { max( concat(dp[n - i][d - 1], dp[i][1]), concat(dp[n - i][1], dp[i][d - 1]) ) | 2 <= i < n }
    for d in 2..(digits_num_max + 1) {
        for n in 2..(matchstick_num + 1) {
            let mut number_max: Option<Digits> = None;

            for i in 2..n {
                if let (&Some(ref n1), &Some(ref n2)) = (&dp[n - i][d - 1], &dp[i][1]) {
                    let m = cmp::max(n1.concat(&n2), n2.concat(&n1));
                    number_max = number_max.map(|n| cmp::max(n, m.clone())).or(Some(m));
                }

                if let (&Some(ref n1), &Some(ref n2)) = (&dp[n - i][1], &dp[i][d - 1]) {
                    let m = cmp::max(n1.concat(&n2), n2.concat(&n1));
                    number_max = number_max.map(|n| cmp::max(n, m.clone())).or(Some(m));
                }
            }

            dp[n][d] = number_max;
        }
    }

    let mut ans: Option<Digits> = None;
    for d in 1..(digits_num_max + 1) {
        if let &Some(ref n) = &dp[matchstick_num][d] {
            ans = ans.map(|a| cmp::max(a, n.clone())).or(Some(n.clone()));
        }
    }

    println!("{}", ans.expect("no answer"));
}

fn init_dp_table(
    matchstick_num: usize,
    digits_num_max: usize,
    numbers: &[i32],
) -> Vec<Vec<Option<Digits>>> {
    let numbers = numbers.iter().collect::<HashSet<_>>();
    let mut dp = vec![vec![None; digits_num_max + 1]; matchstick_num + 1];

    if numbers.contains(&1) {
        dp[2][1] = Some(Digits(vec![1]));
    }
    if numbers.contains(&7) {
        dp[3][1] = Some(Digits(vec![7]));
    }
    if numbers.contains(&4) {
        dp[4][1] = Some(Digits(vec![4]));
    }
    dp[5][1] = if numbers.contains(&5) {
        Some(Digits(vec![5]))
    } else if numbers.contains(&3) {
        Some(Digits(vec![3]))
    } else if numbers.contains(&2) {
        Some(Digits(vec![2]))
    } else {
        None
    };
    dp[6][1] = if numbers.contains(&9) {
        Some(Digits(vec![9]))
    } else if numbers.contains(&6) {
        Some(Digits(vec![6]))
    } else {
        None
    };
    if numbers.contains(&8) {
        dp[7][1] = Some(Digits(vec![8]));
    }

    dp
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct Digits(Vec<i32>);

impl Digits {
    fn concat(&self, rhs: &Self) -> Self {
        let mut n = self.clone();
        n.0.append(&mut rhs.0.clone());
        n
    }
}

impl Deref for Digits {
    type Target = Vec<i32>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl PartialOrd for Digits {
    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
        Some(self.cmp(rhs))
    }
}

impl Ord for Digits {
    fn cmp(&self, rhs: &Self) -> Ordering {
        let len_self = self.len();
        let len_rhs = rhs.len();

        if len_self == len_rhs {
            for (s, r) in self.iter().zip(rhs.iter()) {
                if s == r {
                    continue;
                } else {
                    return s.cmp(&r);
                }
            }

            Equal
        } else {
            len_self.cmp(&len_rhs)
        }
    }
}

impl Display for Digits {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for d in self.iter() {
            write!(f, "{}", d).unwrap();
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test() {
        //
    }
}