#![allow(unused_imports)] use std::cmp::*; use std::collections::*; use std::io::Write; use std::ops::Bound::*; #[allow(unused_macros)] macro_rules! debug { ($($e:expr),*) => { #[cfg(debug_assertions)] $({ let (e, mut err) = (stringify!($e), std::io::stderr()); writeln!(err, "{} = {:?}", e, $e).unwrap() })* }; } fn main() { let v = read_vec::(); let (n, k) = (v[0].parse::().unwrap(), v[1].clone()); let mut c = read_vec::(); if k.len() > n { println!("-1"); return; } if k.len() < n { for i in 0..n { for _ in 0..c[i] { print!("{}", i + 1); } } println!(""); return; } let mut k = k .chars() .map(|x| x.to_digit(10).unwrap() as usize) .collect::>(); k.reverse(); let mut kp1 = vec![]; let mut carry = k[0] == 9; if carry { kp1.push(0); } else { kp1.push(k[0] + 1); } for i in 1..n { carry = k[i] == 9 && carry; if carry { kp1.push(0); } else { kp1.push(k[i]); } } if carry { println!("-1"); return; } kp1.reverse(); let mut kp1_count = vec![0; 10]; for &num in &kp1 { kp1_count[num] += 1; } if (0..9).all(|i| kp1_count[i + 1] == c[i]) { for num in kp1 { print!("{}", num); } println!(""); return; } let mut answers = vec![]; let mut overed = false; 'outer: for (i, &num) in kp1.iter().enumerate() { if overed { for j in 0..9 { if c[j] >= 1 { c[j] -= 1; answers.push(j + 1); continue 'outer; } } } else { let left = if num > 0 { num - 1 } else { 0 }; for j in left..9 { if c[j] >= 1 { c[j] -= 1; answers.push(j + 1); if j + 1 > num { overed = true; } continue 'outer; } } // unreachable!(); for j in (0..i).rev() { c[answers[j] - 1] += 1; answers.pop(); for k in kp1[j]..9 { if c[k] > 0 { answers.push(k + 1); c[k] -= 1; while c.iter().any(|&x| x > 0) { for jj in 0..9 { if c[jj] >= 1 { c[jj] -= 1; answers.push(jj + 1); break; } } } for ans in answers { print!("{}", ans); } println!(""); return; } } } println!("-1"); return; } } for ans in answers { print!("{}", ans); } println!(""); } fn read() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn read_vec() -> Vec { read::() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect() }