Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer. 

The poor boy was very upset because of that. He was so sad that he punched some kind of scoreboard with numbers. The numbers are displayed in the same way as on an electronic clock: each digit position consists of $7$ segments, which can be turned on or off to display different numbers. The picture shows how all $10$ decimal digits are displayed: 

 [Image] 

After the punch, some segments stopped working, that is, some segments might stop glowing if they glowed earlier. But Denis remembered how many sticks were glowing and how many are glowing now. Denis broke exactly $k$ segments and he knows which sticks are working now. Denis came up with the question: what is the maximum possible number that can appear on the board if you turn on exactly $k$ sticks (which are off now)? 

It is allowed that the number includes leading zeros.


-----Input-----

The first line contains integer $n$ $(1 \leq n \leq 2000)$  — the number of digits on scoreboard and $k$ $(0 \leq k \leq 2000)$  — the number of segments that stopped working.

The next $n$ lines contain one binary string of length $7$, the $i$-th of which encodes the $i$-th digit of the scoreboard.

Each digit on the scoreboard consists of $7$ segments. We number them, as in the picture below, and let the $i$-th place of the binary string be $0$ if the $i$-th stick is not glowing and $1$ if it is glowing. Then a binary string of length $7$ will specify which segments are glowing now.

 [Image] 

Thus, the sequences "1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011" encode in sequence all digits from $0$ to $9$ inclusive.


-----Output-----

Output a single number consisting of $n$ digits  — the maximum number that can be obtained if you turn on exactly $k$ sticks or $-1$, if it is impossible to turn on exactly $k$ sticks so that a correct number appears on the scoreboard digits.


-----Examples-----
Input
1 7
0000000

Output
8
Input
2 5
0010010
0010010

Output
97
Input
3 5
0100001
1001001
1010011

Output
-1


-----Note-----

In the first test, we are obliged to include all $7$ sticks and get one $8$ digit on the scoreboard.

In the second test, we have sticks turned on so that units are formed. For $5$ of additionally included sticks, you can get the numbers $07$, $18$, $34$, $43$, $70$, $79$, $81$ and $97$, of which we choose the maximum  — $97$.

In the third test, it is impossible to turn on exactly $5$ sticks so that a sequence of numbers appears on the scoreboard.

Source: codeforces | Difficulty: MEDIUM


Solutions:
def get(s1, s2):
	c = 0
	for i in range(0, 7):
		if s1[i] == '0' and s2[i] == '1':
			return 10000
		if s1[i] == '1' and s2[i] == '0':
			c += 1
	return c
pre = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
(n, k) = map(int, input().split())
L = []
for i in range(n):
	s = input()
	L.append(s)
dp = []
for i in range(n + 1):
	h = []
	for j in range(k + 1):
		h.append(False)
	dp.append(h)
dp[n][0] = True
for i in range(9, -1, -1):
	cost = get(pre[i], L[n - 1])
	if cost <= k:
		dp[n - 1][cost] = True
for i in range(n - 2, -1, -1):
	for e in range(9, -1, -1):
		cost = get(pre[e], L[i])
		for j in range(0, k + 1):
			if j - cost >= 0 and j - cost <= k and (dp[i + 1][j - cost] == True):
				dp[i][j] = True
if dp[0][k] == False:
	print(-1)
else:
	ans = ''
	tot = 0
	for i in range(0, n):
		for j in range(9, -1, -1):
			cost = get(pre[j], L[i])
			if k - (tot + cost) >= 0 and k - (tot + cost) <= k and (dp[i + 1][k - (tot + cost)] == True):
				ans += str(j)
				tot += cost
				break
	print(ans)


import sys
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()

def li():
	return [int(i) for i in input().split()]

def lli(rows):
	return [li() for _ in range(rows)]

def si():
	return input()

def ii():
	return int(input())

def ins():
	return input().split()
val = [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
cnt = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]
(n, k) = MI()
(nums, count) = ([], [])
for i in range(n):
	s = SI()
	(curr, c) = (0, 0)
	for j in range(7):
		if s[j] == '1':
			curr += 1 << 6 - j
			c += 1
	nums.append(curr)
	count.append(c)
req = [[-1 for j in range(10)] for i in range(n)]
for i in range(n):
	for j in range(10):
		if nums[i] | val[j] == val[j]:
			req[i][j] = cnt[j] - count[i]
dp = [[-1 for j in range(k + 1)] for i in range(n + 1)]
dp[n][0] = 0
for i in range(n - 1, -1, -1):
	for j in range(k + 1):
		for d in range(10):
			if req[i][d] != -1 and j >= req[i][d] and (dp[i + 1][j - req[i][d]] != -1):
				dp[i][j] = d
if dp[0][k] == -1:
	print(-1)
else:
	ans = []
	for i in range(n):
		ans.append(str(dp[i][k]))
		k -= req[i][dp[i][k]]
	print(''.join(ans))


def D():
	numdict = {0: '1110111', 1: '0010010', 2: '1011101', 3: '1011011', 4: '0111010', 5: '1101011', 6: '1101111', 7: '1010010', 8: '1111111', 9: '1111011'}
	(n, k) = map(int, input().split())
	sb = list()
	for i in range(0, n):
		sb.append(str(input()))
	covb = list()
	sdict = dict()
	slis = [0] * (k + 1)
	dp = [slis.copy() for i in range(0, n + 1)]
	for i in sb:
		stckarr = list()
		for j in range(0, 10):
			sticks = cov(i, numdict[j], sdict)
			stckarr.append(sticks)
		covb.append(stckarr)
	dp[n][0] = 1
	for i in range(n, 0, -1):
		for j in range(0, k + 1):
			if dp[i][j] == 1:
				for d in range(0, 10):
					if covb[i - 1][d] != -1 and j + covb[i - 1][d] <= k:
						dp[i - 1][j + covb[i - 1][d]] = 1
	if dp[0][k] == 0:
		print(-1)
		return
	for i in range(0, n):
		maxd = -1
		for d in range(9, -1, -1):
			if covb[i][d] != -1 and k >= covb[i][d] and (dp[i + 1][k - covb[i][d]] == 1):
				maxd = d
				k = k - covb[i][d]
				break
		print(maxd, end='')
	print()

def slvr(sb, covb, i, sticks, Ar, Cur):
	if sticks == 0 and i == len(sb):
		x = int(Cur)
		Ar.append(x)
		return
	if i >= len(sb):
		return
	if sticks > 0 and i == len(sb):
		return
	if sticks < 0 and i < len(sb):
		return
	lenc = len(Cur)
	for s in range(0, len(covb[i])):
		if covb[i][s] != -1:
			if covb[i][s] <= sticks:
				Cur = Cur + str(s)
				f = slvr(sb, covb, i + 1, sticks - covb[i][s], Ar, Cur)
				Cur = Cur[:lenc]
	return

def cov(str1, str2, sd):
	stcks = 0
	if (str1, str2) in sd:
		return sd[str1, str2]
	for i in range(0, 7):
		if str1[i] == '1' and str2[i] == '0':
			return -1
		elif str1[i] == '0' and str2[i] == '1':
			stcks += 1
	sd[str1, str2] = stcks
	return stcks
D()


import sys
from array import array
import typing as Tp

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def output(*args):
	sys.stdout.buffer.write(('\n'.join(map(str, args)) + '\n').encode('utf-8'))

def main():
	(n, k) = map(int, input().split())
	a = list(map(lambda x: int(x, 2), (input().rstrip() for _ in range(n))))
	inf = k + 1
	digit_bar = list(map(lambda x: int(x, 2), ('1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011')))
	cost = [[inf if a[i] & bar != a[i] else bin(bar - a[i]).count('1') for bar in digit_bar] for i in range(n)]
	dp = [array('b', [0]) * (k + 1) for _ in range(n + 1)]
	dp[n][k] = 1
	for i in range(n - 1, -1, -1):
		for j in range(k, -1, -1):
			if not dp[i + 1][j]:
				continue
			for digit in range(10):
				if cost[i][digit] <= j:
					dp[i][j - cost[i][digit]] = 1
	if not dp[0][0]:
		print(-1)
		exit()
	ans = []
	val = 0
	for i in range(n):
		for digit in range(9, -1, -1):
			if val + cost[i][digit] <= k and dp[i + 1][val + cost[i][digit]]:
				ans.append(digit)
				val += cost[i][digit]
				break
	print(''.join(map(str, ans)))
main()


import io
import os

def popcount(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	return ((i + (i >> 4) & 252645135) * 16843009 & 4294967295) >> 24
binaryToDecimal = {}
for (i, x) in list(enumerate(['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']))[::-1]:
	binaryToDecimal[int(x, 2)] = i

def solve(N, K, digits):
	digits = [int(d, 2) for d in digits[::-1]]
	costs = [[] for i in range(1 << 7)]
	for d in digits:
		temp = []
		for (b, v) in binaryToDecimal.items():
			if d & b == d:
				cost = popcount(b - d)
				temp.append(cost)
		costs[d] = temp
	possible = [[False for i in range(K + 1)]]
	possible[-1][0] = True
	for d in digits:
		nextPossible = [False for i in range(K + 1)]
		for k in range(K + 1):
			if possible[-1][k]:
				for cost in costs[d]:
					if k + cost <= K:
						nextPossible[k + cost] = True
		possible.append(nextPossible)
	if not possible[N][K]:
		return -1
	ans = []
	for i in range(N - 1, -1, -1):
		d = digits[i]
		for (b, v) in binaryToDecimal.items():
			if d & b == d:
				cost = popcount(b - d)
				if K - cost >= 0 and possible[i][K - cost]:
					ans.append(str(v))
					K -= cost
					break
	return ''.join(ans).rjust(N, '0')
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N, K) = [int(x) for x in input().split()]
digits = [input().decode().rstrip() for i in range(N)]
ans = solve(N, K, digits)
print(ans)


digits_b = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
counts = [s.count('1') for s in digits_b]
digits_num = [int(s, 2) for s in digits_b]
(nn, kk) = map(int, input().split())
poss = [[] for i in range(nn)]
for i in range(nn):
	s = input()
	count = s.count('1')
	num = int(s, 2)
	for d in range(9, -1, -1):
		if num & digits_num[d] == num:
			poss[i].append((d, counts[d] - count))
dp = [[0 for __ in range(kk + 1)] for _ in range(nn + 1)]
dp[0][0] = 1
for n in range(nn):
	for k in range(kk + 1):
		if not dp[n][k]:
			continue
		for (_, c) in poss[nn - n - 1]:
			if c + k > kk:
				continue
			dp[n + 1][k + c] = 1
out = []
if dp[nn][kk]:
	for n in range(nn):
		for (nx, c) in poss[n]:
			if c > kk or not dp[nn - 1 - n][kk - c]:
				continue
			kk -= c
			out.append(nx)
			break
	print(''.join(map(str, out)))
else:
	print(-1)


from sys import stdin, stdout, exit, setrecursionlimit
setrecursionlimit(10000)

def diff(small, large):
	s = 0
	for i in range(7):
		if small[i] == '0' and large[i] == '1':
			s += 1
		elif small[i] == '1' and large[i] == '0':
			return -1
	return s
blast = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']

def collect(small):
	res = [diff(small, i) for i in blast]
	return res
assert collect('1110111') == [0, -1, -1, -1, -1, -1, -1, -1, 1, -1]
p = []
n = 0
INVALID = -1
NONE = -2
T = [2200 * [NONE] for i in range(2200)]

def bt(pi, k):
	global p, n, T
	if k < 0:
		return INVALID
	if T[pi][k] != -2:
		return T[pi][k]
	if pi == n:
		v = INVALID
		if k == 0:
			v = 0
		T[pi][k] = v
		return T[pi][k]
	for j in range(9, -1, -1):
		if p[pi][j] == -1:
			continue
		r = bt(pi + 1, k - p[pi][j])
		if r != INVALID:
			T[pi][k] = j
			return T[pi][k]
	T[pi][k] = INVALID
	return T[pi][k]

def main():
	global p, n, T
	rows = stdin.read().split('\n')
	(n, k) = map(int, rows[0].split(' '))
	for i in range(n):
		p.append(collect(rows[i + 1]))
	v = bt(0, k)
	if v == -1:
		print(-1)
	else:
		pi = 0
		r = []
		while pi < n:
			j = T[pi][k]
			k -= p[pi][j]
			pi += 1
			r.append(str(j))
		print(''.join(r))
main()


from sys import stdin
nums = [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]

def calc(a1, a2):
	if (a1 ^ a2) & a1 == 0:
		d = a1 ^ a2
		return sum([d >> i & 1 for i in range(7)])
	else:
		return -1
(n, k) = list(map(int, input().split()))
number = []
for _ in range(n):
	number.append(int(input(), 2))
number.reverse()
dp = [[-1] * (k + 1) for _ in range(n)]
dp_prev_index = [[-1] * (k + 1) for _ in range(n)]
for i in range(n):
	a = [-1] * 2001
	for r in range(10):
		c = calc(number[i], nums[r])
		if c != -1:
			a[c] = r
	for j in range(min(k + 1, (i + 1) * 7 + 1)):
		if i > 0:
			for u in range(8):
				if j - u < 0 or a[u] == -1 or dp[i - 1][j - u] == -1:
					continue
				if a[u] > dp[i][j]:
					dp[i][j] = a[u]
					dp_prev_index[i][j] = j - u
		elif i == 0:
			dp[i][j] = a[j]
if dp[n - 1][k] == -1:
	print(-1)
else:
	j = k
	for i in range(n - 1, -1, -1):
		print(dp[i][j], end='')
		j = dp_prev_index[i][j]
	print()


from collections import deque
nums = [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
(n, k) = list(map(int, input().split()))
innums = []
for i in range(n):
	innums.append(int(input(), 2))
sdp = [[30000] * 10 for i in range(1 << 7)]
for i in range(1 << 7):
	for j in range(10):
		if i & nums[j] == i:
			raw = nums[j] - i
			count = 0
			while raw:
				count += 1
				raw -= raw & -raw
			sdp[i][j] = count
dp = [[False] * (k + 1) for i in range(n + 1)]
dp[n][0] = True
for (idx, num) in reversed(list(enumerate(innums))):
	for cost in sdp[num]:
		for k_ in range(cost, k + 1):
			dp[idx][k_] |= dp[idx + 1][k_ - cost]
if not dp[0][k]:
	print(-1)
else:
	cur_k = k
	ans = []
	for (idx, num) in enumerate(innums):
		for (i, cost) in reversed(list(enumerate(sdp[num]))):
			if cost > cur_k:
				continue
			if dp[idx + 1][cur_k - cost]:
				cur_k -= cost
				ans.append(i)
				break
	print(''.join(map(str, ans)))


import sys
input = sys.stdin.readline
d = {1: [3, 6], 0: [1, 2, 3, 5, 6, 7], 2: [1, 3, 5, 4, 7], 3: [1, 3, 4, 6, 7], 4: [2, 3, 4, 6], 5: [1, 2, 4, 6, 7], 6: [1, 2, 4, 5, 6, 7], 7: [1, 3, 6], 8: [1, 2, 3, 4, 5, 6, 7], 9: [1, 2, 3, 4, 6, 7]}
(n, k) = map(int, input().split())
p = [[] for i in range(n + 1)]
f = [[-1 for i in range(10)] for j in range(n + 1)]
g = [[-1 for i in range(10)] for j in range(n + 1)]
for i in range(n):
	s = list(input().rstrip())
	for j in range(len(s)):
		if s[j] == '1':
			p[i].append(j + 1)
	for j in range(10):
		if len(set(p[i]) - set(d[j])) != 0:
			continue
		else:
			z = len(set(d[j]) - set(p[i]))
			f[i][z] = max(f[i][z], j)
			g[i][j] = z
count = [[0 for i in range((k + 1) * 8)] for j in range(n + 1)]
for i in range(n - 1, -1, -1):
	if i == n - 1:
		for j in range(8):
			if f[i][j] != -1:
				count[i][j] = 1
	else:
		for u in range(k + 1):
			if count[i + 1][u] == 1:
				for y in range(8):
					if f[i][y] != -1:
						count[i][y + u] = 1
s = ''
for i in range(n - 1):
	for j in range(9, -1, -1):
		if g[i][j] != -1 and count[i + 1][k - g[i][j]] == 1 and (k >= g[i][j]):
			k -= g[i][j]
			s += str(j)
			break
if k >= 0 and k <= 8 and (f[n - 1][k] != -1):
	s += str(f[n - 1][k])
print(s if len(s) == n else -1)


class Solution:

	def __init__(self):
		(self.n, self.k) = list(map(int, input().split()))
		self.s = [input() for i in range(0, self.n)]
		self.state = [(119, 6), (36, 2), (93, 5), (109, 5), (46, 4), (107, 5), (123, 6), (37, 3), (127, 7), (111, 6)]
		self.p = []
		self.dp = [[False for j in range(0, self.k + 1)] for i in range(0, self.n)]

	def solve(self):
		for a in self.s:
			state = int(a[::-1], 2)
			stick = a.count('1')
			v = []
			for (i, (dState, dStick)) in enumerate(self.state):
				if dState & state == state:
					v.append((i, dStick - stick))
			self.p.append(v)
		for i in range(self.n - 1, -1, -1):
			for (j, stick) in self.p[i]:
				if i == self.n - 1:
					if stick <= self.k:
						self.dp[i][stick] = True
				else:
					for d in range(stick, self.k + 1):
						self.dp[i][d] |= self.dp[i + 1][d - stick]
		if not self.dp[0][self.k]:
			return '-1'
		result = ''
		for (i, v) in enumerate(self.p):
			for (j, stick) in v[::-1]:
				ok = self.k == stick if i == self.n - 1 else self.k >= stick and self.dp[i + 1][self.k - stick]
				if ok:
					self.k -= stick
					result += str(j)
					break
		return result
print(Solution().solve())


(N, K) = map(int, input().split())
arr = [list(input()) for _ in range(N)]
dp = [[False] * (K + 1) for _ in range(N + 1)]
dp[0][0] = True
costs = [[] for _ in range(2 ** 7)]
digits = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
for i in range(2 ** 7):
	bits = format(i, 'b')
	if len(bits) != 7:
		bits = '0' * (7 - len(bits)) + bits
	for digit in digits:
		tmp = 0
		for j in range(7):
			if bits[j] == '0' and digit[j] == '1':
				tmp += 1
			elif bits[j] == '1' and digit[j] == '0':
				break
		else:
			costs[i].append(tmp)
for i in range(2 ** 7):
	costs[i] = list(set(costs[i]))
for i in range(N):
	tmp = 0
	for k in range(7):
		if arr[N - i - 1][k] == '1':
			tmp += 2 ** (6 - k)
	for j in range(K, -1, -1):
		for c in costs[tmp]:
			if j - c >= 0 and dp[i][j - c] == True:
				dp[i + 1][j] = True
ans = ''
for i in range(N):
	for j in range(9, -1, -1):
		cost = 0
		for k in range(7):
			if arr[i][k] == '0' and digits[j][k] == '1':
				cost += 1
			elif arr[i][k] == '1' and digits[j][k] == '0':
				break
		else:
			if K - cost >= 0 and dp[N - i - 1][K - cost] == True:
				ans += str(j)
				K -= cost
				break
	else:
		print(-1)
		break
else:
	print(ans)


maxk = 2005

def xcost(s, d):
	price = 0
	for i in range(7):
		if s[i] == '1' and d[i] == '0':
			price = maxk
			break
		elif s[i] == '0' and d[i] == '1':
			price += 1
	return price
s = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
p = []
cost = [[0 for j in range(10)] for i in range(128)]
for i in range(128):
	x = bin(i)[2:].zfill(7)
	p.append(x)
for i in range(128):
	for j in range(10):
		v = xcost(p[i], s[j])
		cost[i][j] = v
(n, k) = map(int, input().split(' '))
scoreboard = []
for i in range(n):
	x = int(str(input()), 2)
	scoreboard.append(x)
dp = [[False for i in range(k + 1)] for j in range(n)]
i = n - 1
bit_int = scoreboard[i]
for j in cost[bit_int]:
	if j <= k:
		dp[i][j] = True
for i in range(n - 2, -1, -1):
	bit_int = scoreboard[i]
	for j in range(k + 1):
		for x in cost[bit_int]:
			if j >= x:
				if dp[i + 1][j - x]:
					dp[i][j] = True
					break
if dp[0][k]:
	(ans, spend, pos) = ('', k, 0)
	for i in scoreboard:
		for j in range(9, -1, -1):
			v = cost[i][j]
			if pos == n - 1 and spend == v:
				ans += str(j)
				break
			elif pos < n - 1 and spend >= v:
				if dp[pos + 1][spend - v]:
					ans += str(j)
					spend -= v
					break
		pos += 1
	print(ans)
else:
	print(-1)


printn = lambda x: print(x, end='')
inn = lambda : int(input())
inl = lambda : list(map(int, input().split()))
inm = lambda : map(int, input().split())
ins = lambda : input().strip()
DBG = True
BIG = 10 ** 18
R = 10 ** 9 + 7

def ddprint(x):
	if DBG:
		print(x)
digs = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']

def chg(pat, c):
	dig = digs[c]
	cnt = 0
	for i in range(7):
		if pat[i] == '0' and dig[i] == '1':
			cnt += 1
		if pat[i] == '1' and dig[i] == '0':
			return 9
	return cnt
(n, k) = inm()
pats = []
chgh = {}
for i in range(n):
	p = ins()
	a = []
	for m in range(10):
		a.append(chg(p, m))
	chgh[p] = a
	pats.append(p)
d = [[0] * (k + 1) for i in range(n + 1)]
d[n][0] = 1
for i in range(n - 1, -1, -1):
	p = pats[i]
	for j in range(k + 1):
		if d[i + 1][j] == 0:
			continue
		for m in range(10):
			v = chgh[p][m]
			if v < 9 and j + v <= k:
				d[i][j + v] = 1
if d[0][k] == 0:
	print(-1)
	exit()
ans = []
x = k
for i in range(n):
	p = pats[i]
	for m in range(9, -1, -1):
		v = chgh[p][m]
		if v < 9 and x - v >= 0 and (d[i + 1][x - v] == 1):
			ans.append(str(m))
			x -= v
			break
print(''.join(ans))


import sys, os, io
input = sys.stdin.readline

def cout(a):
	for i in a:
		print(i, end='')
	print()
(n, m) = [int(i) for i in input().split()]
a = []
b = [[1, 1, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0], [1, 0, 1, 1, 1, 0, 1], [1, 0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 0, 1, 0], [1, 1, 0, 1, 0, 1, 1], [1, 1, 0, 1, 1, 1, 1], [1, 0, 1, 0, 0, 1, 0], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 1, 1]]
for i in range(n):
	a.append([int(i) for i in input().strip()])
cnt = [0] * n
for i in range(n):
	mini = 7
	for j in range(9, -1, -1):
		cs = 0
		for k in range(7):
			if a[i][k] == 1 and b[j][k] == 0:
				cs = 10
				break
			if a[i][k] == 0 and b[j][k] == 1:
				cs += 1
		mini = min(cs, mini)
	cnt[i] = mini
cnt1 = [0] * (n + 1)
for i in range(n):
	cnt1[i] = 7 - sum(a[i])
for i in range(n - 2, -1, -1):
	cnt[i] += cnt[i + 1]
	cnt1[i] += cnt1[i + 1]
cnt.append(0)
if cnt[0] > m or m > cnt1[0]:
	print(-1)
	exit()
extra = m
final = []
if n == 1:
	for i in range(n):
		for j in range(9, -1, -1):
			cs = 0
			for k in range(7):
				if a[i][k] == 1 and b[j][k] == 0:
					cs = -1
					break
				if a[i][k] == 0 and b[j][k] == 1:
					cs += 1
			if cs == -1:
				continue
			if extra - cs >= cnt[i + 1] and extra - cs <= cnt1[i + 1]:
				final.append(j)
				extra -= cs
				break
	if len(final) == 0:
		print(-1)
	else:
		for i in final:
			print(i, end='')
		print()
	exit()
lastcs = 0
for i in range(n - 2):
	for j in range(9, -1, -1):
		cs = 0
		for k in range(7):
			if a[i][k] == 1 and b[j][k] == 0:
				cs = -1
				break
			if a[i][k] == 0 and b[j][k] == 1:
				cs += 1
		if cs == -1:
			continue
		if extra - cs >= cnt[i + 1] and extra - cs <= cnt1[i + 1]:
			final.append(j)
			extra -= cs
			lastcs = cs
			break
if n >= 3:
	extra += lastcs
available1 = set()
available2 = set()
for i in range(1, 3):
	for j in range(9, -1, -1):
		cs = 0
		for k in range(7):
			if a[-i][k] == 1 and b[j][k] == 0:
				cs = -1
				break
			if a[-i][k] == 0 and b[j][k] == 1:
				cs += 1
		if cs == -1:
			continue
		if i == 1:
			available1.add(cs)
		else:
			available2.add(cs)
if n == 2:
	available = list(available1)
	for i in range(n - 2, n):
		for j in range(9, -1, -1):
			cs = 0
			for k in range(7):
				if a[i][k] == 1 and b[j][k] == 0:
					cs = -1
					break
				if a[i][k] == 0 and b[j][k] == 1:
					cs += 1
			if cs == -1:
				continue
			if extra - cs >= cnt[i + 1] and extra - cs <= cnt1[i + 1] and (extra - cs in available):
				final.append(j)
				available = [0]
				extra -= cs
				break
else:
	if len(final):
		final.pop()
	available = []
	for i in available1:
		for j in available2:
			available.append(i + j)
	i = n - 3
	for j in range(9, -1, -1):
		cs = 0
		for k in range(7):
			if a[n - 3][k] == 1 and b[j][k] == 0:
				cs = -1
				break
			if a[n - 3][k] == 0 and b[j][k] == 1:
				cs += 1
		if cs == -1:
			continue
		if extra - cs >= cnt[i + 1] and extra - cs <= cnt1[i + 1] and (extra - cs in available):
			final.append(j)
			extra -= cs
			break
	available = list(available1)
	for i in range(n - 2, n):
		for j in range(9, -1, -1):
			cs = 0
			for k in range(7):
				if a[i][k] == 1 and b[j][k] == 0:
					cs = -1
					break
				if a[i][k] == 0 and b[j][k] == 1:
					cs += 1
			if cs == -1:
				continue
			if extra - cs >= cnt[i + 1] and extra - cs <= cnt1[i + 1] and (extra - cs in available):
				final.append(j)
				available = [0]
				extra -= cs
				break
if len(final) < n:
	print(-1)
else:
	for i in final:
		print(i, end='')
	print()


import sys
(n, k) = map(int, input().split())
l = []
nums = [[1, 1, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0], [1, 0, 1, 1, 1, 0, 1], [1, 0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 0, 1, 0], [1, 1, 0, 1, 0, 1, 1], [1, 1, 0, 1, 1, 1, 1], [1, 0, 1, 0, 0, 1, 0], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 1, 1]]
for _ in range(n):
	l.append(list(map(int, list(input()))))

def dist(a, b):
	c = 0
	for (ai, bi) in zip(a, b):
		if ai != bi:
			if ai == 1:
				return -1
			else:
				c += 1
	return c
least = []
most = []
for v in l:
	le = 100
	mo = -1
	for i in range(10):
		d = dist(v, nums[i])
		if d != -1:
			le = min(le, d)
			mo = max(mo, d)
	least.append(le)
	most.append(mo)

def rec(i, k, rl, rm):
	if i == n:
		return ''
	v = l[i]
	nrl = rl - least[i]
	nrm = rm - most[i]
	for j in range(10)[::-1]:
		d = dist(v, nums[j])
		if d != -1 and d <= k and (k - d >= nrl) and (k - d <= nrm):
			r = rec(i + 1, k - d, nrl, nrm)
			if r is not None:
				return str(j) + r
	return None
r = rec(0, k, sum(least), sum(most))
if r is None:
	print(-1)
else:
	print(r)


import sys
stdin = sys.stdin
ns = lambda : stdin.readline().rstrip()
ni = lambda : int(stdin.readline().rstrip())
nm = lambda : map(int, stdin.readline().split())
nl = lambda : list(map(int, stdin.readline().split()))
dig = [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
pct = [0] * (1 << 7)
for bit in range(1 << 7):
	for j in range(7):
		if not bit & 1 << j:
			pct[bit | 1 << j] = pct[bit] + 1

def solve():
	(n, k) = nm()
	s = [int(input(), 2) for _ in range(n)]
	dp = [[False] * (k + 20) for _ in range(n + 1)]
	dp[n][k] = True
	for i in range(n - 1, -1, -1):
		for j in range(k, -1, -1):
			if dp[i + 1][j]:
				for d in range(10):
					if s[i] & dig[d] == s[i]:
						dp[i][j - pct[s[i] ^ dig[d]]] = True
	if not dp[0][0]:
		return -1
	cur = ''
	ck = 0
	for i in range(n):
		for d in range(9, -1, -1):
			if s[i] & dig[d] == s[i] and dp[i + 1][ck + pct[s[i] ^ dig[d]]]:
				ck += pct[s[i] ^ dig[d]]
				cur += str(d)
				break
	return cur
print(solve())


from sys import stdin, stderr

def rl():
	return [int(w) for w in stdin.readline().split()]
D = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
(n, k) = rl()
x = [stdin.readline().rstrip() for _ in range(n)]
r = [[-1] * (k + 1) for _ in range(n + 1)]
r[n][0] = 0
for i in range(n - 1, -1, -1):
	for d in range(10):
		dc = 0
		for (f, t) in zip(x[i], D[d]):
			if f > t:
				break
			else:
				dc += f != t
		else:
			z = dc * 10 + d
			for c in range(k + 1 - dc):
				if r[i + 1][c] >= 0:
					r[i][c + dc] = z
if r[0][k] >= 0:
	for i in range(n):
		print(r[i][k] % 10, end='')
		k -= r[i][k] // 10
	print()
else:
	print(-1)


sevsegbits = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
sevseg = [int(x, 2) for x in sevsegbits]
(n, k) = [int(x) for x in input().split()]
dp = [[False for _ in range(k + 1)] for i in range(n + 1)]
dp[n][0] = True
rip = [[-1 for i in range(10)] for i in range(n)]
popat = [-1 for i in range(n)]
for i in range(n):
	popat[i] = int(input(), 2)
for i in range(n - 1, -1, -1):
	p = popat[i]
	for j in range(10):
		if sevseg[j] & p == p:
			ct = bin(sevseg[j] ^ p).count('1')
			rip[i][j] = ct
			for l in range(k + 1):
				if dp[i + 1][l] == True and l + ct <= k:
					dp[i][l + ct] = True
if dp[0][k] == False:
	print(-1)
else:
	cct = k
	for i in range(n):
		for j in range(9, -1, -1):
			if rip[i][j] != -1 and cct >= rip[i][j] and (dp[i + 1][cct - rip[i][j]] == True):
				print(j, end='')
				cct -= rip[i][j]
				break


(n, k) = map(int, input().split())
bins = [input() for _ in range(n)]
digits = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
memo = [[-1 for _ in range(k + 1)] for _ in range(n + 1)]
memo[n][0] = 0

def foo(u, p):
	d = 0
	for (cu, cp) in zip(u, p):
		if cu > cp:
			return -1
		d += cu != cp
	return d
for i in range(n - 1, -1, -1):
	for (m, s) in enumerate(digits):
		d = foo(bins[i], s)
		if d == -1:
			continue
		for j in range(k + 1 - d):
			recu = memo[i + 1][j]
			if recu == -1:
				continue
			memo[i][j + d] = 10 * d + m
if memo[0][k] >= 0:
	for i in range(n):
		print(memo[i][k] % 10, end='')
		k -= memo[i][k] // 10
	print()
else:
	print(-1)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

def main():
	(n, k) = RL()
	arr = []
	num = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
	num = [int(i, 2) for i in num]
	dis = [[0] * 10 for _ in range(n + 1)]
	for i in range(1, n + 1):
		now = int(input(), 2)
		for j in range(10):
			ret = 0
			for l in range(7):
				if now >> l & 1 == 0 and num[j] >> l & 1 == 1:
					ret += 1
				elif now >> l & 1 == 1 and num[j] >> l & 1 == 0:
					dis[i][j] = -1
					break
			else:
				dis[i][j] = ret
	dp = [[0] * (k + 1) for _ in range(n + 2)]
	dp[n + 1][0] = 1
	for i in range(n, -1, -1):
		for nm in range(10):
			cost = dis[i][nm]
			if cost == -1:
				continue
			for j in range(cost, k + 1):
				if cost > k:
					break
				dp[i][j] |= dp[i + 1][j - cost]
	if dp[1][k] == 0:
		print(-1)
	else:
		res = []
		for i in range(1, n + 1):
			for j in range(9, -1, -1):
				if dis[i][j] == -1:
					continue
				if k >= dis[i][j] and dp[i + 1][k - dis[i][j]] == 1:
					res.append(j)
					k -= dis[i][j]
					break
		print(''.join((str(i) for i in res)))
main()


binrep = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
bintoint = {n: binrep[n] for n in range(10)}
allowed = {pos: set((n for n in range(10) if binrep[n][pos] == '1')) for pos in range(7)}
size = {n: sum((1 for c in binrep[n] if c == '1')) for n in range(10)}

def analyse(binstr):
	possible = set((n for n in range(10)))
	for (pos, c) in enumerate(binstr):
		if c == '1':
			possible = possible.intersection(allowed[pos])
	return sorted(list(possible), reverse=True)

def countlights(binstr):
	total = 0
	for c in binstr:
		total += int(c)
	return total

def solvenumber(sparemoves, N, pos=0, number=''):
	if pos == N:
		if sparemoves == 0:
			return number
		else:
			return -1
	possibilities = possibilityarray[pos]
	missing = missingarray[pos]
	posminmoves = min(missing)
	extramoves = [moves - posminmoves for moves in missing]
	for (index, digit) in enumerate(possibilities):
		cost = extramoves[index]
		if cost <= sparemoves:
			result = solvenumber(sparemoves - cost, N, pos + 1, number + str(digit))
			if result != -1:
				return result
	return -1
(N, K) = list(map(int, input().split()))
lightsonarray = [input() for n in range(N)]
possibilityarray = [analyse(string) for string in lightsonarray]
missingarray = [[size[num] - countlights(string) for num in possibilityarray[index]] for (index, string) in enumerate(lightsonarray)]
minmoves = sum((min(movesreq) for movesreq in missingarray))
maxmoves = sum((max(movesreq) for movesreq in missingarray))
if K < minmoves or K > maxmoves:
	print('-1')
else:
	sparemoves = K - minmoves
	number = solvenumber(sparemoves, N)
	print(number)


import sys

def to_dec(s):
	x = 0
	for j in range(7):
		if int(s[j]):
			x |= 1 << j
	return x

def tic_count(x):
	c = 0
	while x > 0:
		if x % 2 == 1:
			c += 1
		x //= 2
	return c
t = 1
for _ in range(t):
	(n, k) = map(int, input().split())
	digs = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
	digs = list(map(to_dec, digs))
	tics = [tic_count(x) for x in digs]
	d = [[False for j in range(k + 1)] for i in range(n + 1)]
	a = [0] * n
	t = [0] * n
	for i in range(n):
		a[i] = to_dec(input())
		t[i] = tic_count(a[i])
	d[n][k] = True
	for i in range(n - 1, -1, -1):
		cur = a[i]
		for x in range(10):
			for left in range(k + 1):
				if digs[x] & cur == cur:
					need = tics[x] - t[i]
					if left - need >= 0 and d[i + 1][left] == True:
						d[i][left - need] = True
	left = 0
	res = []
	for i in range(n):
		for x in range(9, -1, -1):
			if digs[x] & a[i] == a[i]:
				need = tics[x] - t[i]
				if left + need <= k and d[i + 1][left + need]:
					res.append(str(x))
					left += need
					break
	if len(res) != n:
		print(-1)
	else:
		print(''.join(res))


di = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
(n, m) = map(int, input().split())
dist = [[0] * 10 for i in range(n)]
for i in range(n):
	s = input()
	for j in range(10):
		for k in range(7):
			if s[k] == '1' and di[j][k] == '0':
				dist[i][j] = -1
				break
			if s[k] == '0' and di[j][k] == '1':
				dist[i][j] += 1
dp = [[0] * (m + 1) for i in range(n + 1)]
dp[n][0] = 1
for i in range(n, 0, -1):
	for j in range(m + 1):
		if dp[i][j]:
			for k in range(10):
				if dist[i - 1][k] != -1 and j + dist[i - 1][k] <= m:
					dp[i - 1][j + dist[i - 1][k]] = 1
if dp[0][m] == 0:
	print(-1)
else:
	for i in range(n):
		p = -1
		for j in range(9, -1, -1):
			if dist[i][j] != -1 and m >= dist[i][j] and dp[i + 1][m - dist[i][j]]:
				p = j
				m -= dist[i][j]
				break
		print(p, end='')


zero = '1110111'
one = '0010010'
two = '1011101'
three = '1011011'
four = '0111010'
five = '1101011'
six = '1101111'
seven = '1010010'
eight = '1111111'
nine = '1111011'
numbers = [nine, eight, seven, six, five, four, three, two, one, zero]
(n, k2) = map(int, input().split())
bank = 0
completefail = 0
listofusage = []
listofbestnums = []
lamps = []

def convert(s):
	new = ''
	for x in s:
		new += x
	return new
for i in range(n):
	lamp = input()
	lamps.append(lamp)
	maxusage = 100
	bestnum = ''
	for j in numbers:
		fail = 0
		usage = 0
		for k in range(7):
			if j[k] == '0' and lamp[k] == '1':
				fail = 1
			if j[k] == '1' and lamp[k] == '0':
				usage += 1
		if fail == 1:
			continue
		if usage < maxusage:
			bestnum = j
			maxusage = usage
	if maxusage == 100:
		completefail = 1
		break
	listofusage.append(maxusage)
	listofbestnums.append(bestnum)
if completefail == 1 or sum(listofusage) > k2:
	print(-1)
else:
	ans = []
	bank = k2 - sum(listofusage)
	for i in range(n - 1):
		lamp = lamps[i]
		change = 0
		for j in numbers:
			fail = 0
			usage = 0
			for k in range(7):
				if j[k] == '0' and lamp[k] == '1':
					fail = 1
				if j[k] == '1' and lamp[k] == '0':
					usage += 1
			if fail == 1:
				continue
			if usage - listofusage[i] <= bank:
				change = 1
				bank -= usage - listofusage[i]
				break
		if change == 0:
			ans.append(listofbestnums[i])
		else:
			ans.append(j)
	totalfail = 0
	if bank > 7 - listofusage[n - 1]:
		j = n - 2
		const = bank - 7 + listofusage[n - 1]
		for i in range(const):
			if j == -1:
				totalfail = 1
				break
			if ans[j] == eight:
				i -= 1
				j -= 1
				continue
			ans[j] = eight
			bank -= 1
			j -= 1
	lamp = lamps[n - 1]
	change = 0
	for j in numbers:
		fail = 0
		usage = 0
		for k in range(7):
			if j[k] == '0' and lamp[k] == '1':
				fail = 1
			if j[k] == '1' and lamp[k] == '0':
				usage += 1
		if fail == 1:
			continue
		if usage - listofusage[n - 1] == bank:
			change = 1
			bank -= usage - listofusage[n - 1]
			break
	if change == 0:
		ans.append(listofbestnums[n - 1])
	else:
		ans.append(j)
	if totalfail == 1 or not bank == 0:
		print(-1)
	else:
		printans = []
		for i in range(n):
			for j in range(10):
				if ans[i] == numbers[j]:
					printans.append(str(9 - j))
					break
		print(convert(printans))


from sys import stdin
from collections import Counter, deque
nm = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
(n, k) = map(int, input().split())
sg = []
for _ in range(n):
	sg.append(input())

def get_conv(fm, nm):
	ls = []
	for (num, to) in enumerate(nm):
		cc = 0
		for i in range(7):
			if fm[i] == to[i]:
				pass
			elif fm[i] == '0' and to[i] == '1':
				cc += 1
			else:
				break
		else:
			ls.append((num, cc))
	return ls
dp = [[0] * (k + 1) for _ in range(n)]
conv = get_conv(sg[n - 1], nm)
for (num, cc) in conv:
	if k - cc >= 0:
		dp[n - 1][k - cc] = 1
for i in reversed(range(n - 1)):
	conv = get_conv(sg[i], nm)
	for j in range(k + 1):
		if not dp[i + 1][j]:
			continue
		for (num, cc) in conv:
			if j - cc >= 0:
				dp[i][j - cc] = 1
if not dp[0][0]:
	print(-1)
	exit()
(res, p) = ([], 0)
for i in range(n):
	conv = get_conv(sg[i], nm)
	for (num, cc) in reversed(conv):
		if i == n - 1 and p + cc != k:
			continue
		if i == n - 1 or (p + cc <= k and dp[i + 1][p + cc]):
			res.append(num)
			p += cc
			break
print(''.join(map(str, res)))


import os
import sys
NUM_CODES = [[1, 1, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0], [1, 0, 1, 1, 1, 0, 1], [1, 0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 0, 1, 0], [1, 1, 0, 1, 0, 1, 1], [1, 1, 0, 1, 1, 1, 1], [1, 0, 1, 0, 0, 1, 0], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 1, 1]]
NUM_CODES_DICT = {''.join(map(str, k)): idx for (idx, k) in enumerate(NUM_CODES)}
NUM_CODES2 = [int(''.join(map(str, k)), 2) for k in NUM_CODES]

def check2(s):
	d = int(s, 2)
	valid = {}
	for (idx, n) in enumerate(NUM_CODES2):
		if d & n == d:
			cost = bin(d ^ n).count('1')
			valid[cost] = idx
	return valid

def f(nums, k, n_nums):
	costs = {0: 0}
	for n in nums:
		new_costs = {}
		valid = check2(n)
		v = valid.items()
		for (old_cost, old_num) in costs.items():
			nnn = old_num * 10
			for (new_cost, new_num) in v:
				total_cost = old_cost + new_cost
				if total_cost > k:
					continue
				nn = nnn + new_num
				if total_cost not in new_costs or new_costs[total_cost] < nn:
					new_costs[total_cost] = nn
		if not new_costs:
			return '-1'
		else:
			costs = new_costs
	v = [x for (c, x) in costs.items() if c == k]
	if v:
		return ('%0' + str(n_nums) + 'd') % max(v)
	else:
		return '-1'

def f2(nums, k):
	nums = nums[::-1]
	sets = [{0: 0}]
	checks_dict = [check2(num) for num in nums]
	checks = [sorted(c.items(), key=lambda x: (-x[1], x[0])) for c in checks_dict]
	for (idx, num) in enumerate(nums):
		ns = {}
		for (new_cost, _) in checks[idx]:
			for old_cost in sets[-1]:
				total_cost = old_cost + new_cost
				if total_cost > k or total_cost in ns:
					continue
				ns[total_cost] = old_cost
		sets.append(ns)
	if k not in sets[-1]:
		return '-1'
	path = []
	cost = k
	for s in sets[::-1][:-1]:
		parent_cost = s[cost]
		path.append(cost - parent_cost)
		cost = parent_cost
	return ''.join(map(str, (c[p] for (c, p) in zip(checks_dict, path[::-1]))))[::-1]

def pp(input):
	(n, k) = map(int, input().split())
	nums = [input() for i in range(n)]
	print(f2(nums, k))
if 'paalto' in os.getcwd():
	from string_source import string_source
	pp(string_source('10 0\n    0111010\n    1101111\n    1111011\n    0111010\n    1101011\n    1101011\n    1110111\n    1010010\n    1111111\n    0010010'))
	pp(string_source('10 10\n0101111\n0000000\n1111011\n1011011\n1011011\n1111011\n0010010\n1010010\n1101111\n0000000'))
	pp(string_source('2 5\n0010010\n0010010'))
	pp(string_source('1 7\n0000000'))
	pp(string_source('1 3\n0000000'))
	pp(string_source('3 5\n0100001\n1001001\n1010011'))
else:
	pp(iter(sys.stdin.buffer.read().decode().splitlines()).__next__)


from sys import stdin, stdout

def find(arr, N, K):
	nums = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
	dist = [[-1] * 10 for _ in range(N)]
	arr.reverse()
	for i in range(N):
		for j in range(10):
			c = 0
			for k in range(7):
				if nums[j][k] == arr[i][k]:
					continue
				if nums[j][k] == '1' and arr[i][k] == '0':
					c += 1
				else:
					c = -1
					break
			dist[i][j] = c
	dp = [[0] * (K + 1) for _ in range(N)]
	for i in range(10):
		if dist[0][i] != -1 and dist[0][i] <= K:
			dp[0][dist[0][i]] = 1
	for i in range(1, N):
		for j in range(K + 1):
			if dp[i - 1][j]:
				for k in range(10):
					if dist[i][k] != -1 and j + dist[i][k] <= K:
						dp[i][j + dist[i][k]] = 1
	r = []
	j = K
	if dp[-1][-1] == 0:
		return -1
	for i in range(N)[::-1]:
		for k in range(10)[::-1]:
			if dist[i][k] != -1 and j - dist[i][k] >= 0:
				if i == 0 and dist[i][k] == j or (i != 0 and dp[i - 1][j - dist[i][k]]):
					r.append(k)
					j -= dist[i][k]
					break
	return ''.join(map(str, r))

def main():
	(N, K) = list(map(int, stdin.readline().split()))
	arr = []
	for _ in range(N):
		arr.append(stdin.readline().strip())
	print(find(arr, N, K))
main()


import sys
lines = sys.stdin.readlines()
(n, k) = map(int, lines[0].strip().split(' '))
strings = []
for i in range(1, n + 1):
	strings.append(lines[i].strip())
encoding = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
cnt = []
for i in range(10):
	cnt.append(encoding[i].count('1'))
S = set(strings)

def xor(a, b):
	val = 0
	for i in range(7):
		if a[i] == '1':
			if b[i] == '0':
				val += 1
		elif b[i] == '1':
			return -1
	return val
cache = {}
for s in S:
	arr = []
	seen = set()
	for i in range(9, -1, -1):
		tmp = xor(encoding[i], s)
		if tmp != -1 and tmp not in seen:
			arr.append((str(i), tmp))
			seen.add(tmp)
	cache[s] = arr
dp = [[0 for _ in range(k + 1)] for _ in range(n)]
for node in cache[strings[-1]]:
	if node[1] <= k:
		dp[-1][node[1]] = node[0]
for i in range(n - 2, -1, -1):
	for val in cache[strings[i]]:
		for j in range(val[1], k + 1):
			if dp[i][j] != 0:
				continue
			if dp[i + 1][j - val[1]] != 0:
				dp[i][j] = val[0]
if dp[0][-1] == 0:
	print(-1)
else:
	res = ''
	cK = k
	for i in range(n):
		tmp = dp[i][cK]
		res += tmp
		val = xor(encoding[int(tmp)], strings[i])
		cK -= val
	print(res)


import sys
input = sys.stdin.readline
inf = 10000000
mod = 998244353
STR = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
(N, M) = map(int, input().split())
A = [input().strip() for i in range(N)]
NUM = [[0] * 10 for i in range(N + 1)]
F = [[False] * (M + 1) for i in range(N + 1)]
F[N][M] = True
for i in range(N):
	for j in range(10):
		for k in range(7):
			if A[i][k] != STR[j][k]:
				if A[i][k] == '1':
					NUM[i][j] = inf
					break
				else:
					NUM[i][j] += 1
for i in range(N - 1, -1, -1):
	for j in range(M + 1):
		for k in range(10):
			delta = NUM[i][k]
			if j + delta > M:
				continue
			if F[i + 1][delta + j] == True:
				F[i][j] = True
if F[0][0] == False:
	print('-1')
	sys.exit()
pos = 0
ANS = []
for i in range(N):
	for j in range(9, -1, -1):
		if pos + NUM[i][j] <= M and F[i + 1][pos + NUM[i][j]] == True:
			pos = pos + NUM[i][j]
			ANS.append(j)
			break
for ans in ANS:
	print(ans, end='')


D = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
(n, k) = list(map(int, input().split()))
x = [input() for _ in range(n)]
r = [[-1] * (k + 1) for _ in range(n + 1)]
r[n][0] = 0
for i in range(n - 1, -1, -1):
	for d in range(10):
		dc = 0
		for (f, t) in zip(x[i], D[d]):
			if f > t:
				break
			else:
				dc += f != t
		else:
			z = dc * 10 + d
			for c in range(k + 1 - dc):
				if r[i + 1][c] >= 0:
					r[i][c + dc] = z
if r[0][k] >= 0:
	for i in range(n):
		print(r[i][k] % 10, end='')
		k -= r[i][k] // 10
	print()
else:
	print(-1)


def calc(a1, a2):
	if (a1 ^ a2) & a1 == 0:
		d = a1 ^ a2
		return sum([d >> i & 1 for i in range(7)])
	else:
		return -1
D = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
(n, k) = list(map(int, input().split()))
x = [input() for _ in range(n)]
r = [[-1] * (k + 1) for _ in range(n + 1)]
r[n][0] = 0
for i in range(n - 1, -1, -1):
	for d in range(10):
		dc = calc(int(x[i], 2), int(D[d], 2))
		if dc != -1:
			z = dc * 10 + d
			for c in range(k + 1 - dc):
				if r[i + 1][c] >= 0:
					r[i][c + dc] = z
if r[0][k] >= 0:
	for i in range(n):
		print(r[i][k] % 10, end='')
		k -= r[i][k] // 10
	print()
else:
	print(-1)


import sys
from typing import List
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())

def get_digit_masks():
	digits = [[1, 2, 5, 7, 6, 3], [3, 6], [1, 3, 4, 5, 7], [1, 3, 4, 6, 7], [2, 4, 3, 6], [1, 2, 4, 6, 7], [1, 2, 4, 5, 6, 7], [1, 3, 6], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 6, 7]]
	digit_mask = []
	for sticks in digits:
		mask = 0
		for i in sticks:
			mask |= 1 << i - 1
		digit_mask.append(mask)
	return digit_mask

def fill_transitions(digit_mask) -> List[List[int]]:
	options = 2 ** 7
	T = [[-1] * 10 for _ in range(options)]
	for cur in range(options):
		for d in range(10):
			if cur == 37 and d == 7:
				gg = 0
			dmask = digit_mask[d]
			k = get_diff(cur, dmask)
			if k == -1:
				continue
			T[cur][d] = k
	return T

def find_max_digit(T, A: List[int], index, budget, dp) -> int:
	if index == len(A):
		if budget == 0:
			return 0
		return -1
	if dp[index][budget] is not None:
		return dp[index][budget]
	cur = A[index]
	for d in range(9, -1, -1):
		r = T[cur][d]
		if r == -1:
			continue
		if r <= budget:
			rec = find_max_digit(T, A, index + 1, budget - r, dp)
			if rec != -1:
				dp[index][budget] = d
				return d
	else:
		dp[index][budget] = -1
		return -1

def from_file(f):
	return f.readline

def get_diff(a, b):
	intersection = a & b
	if intersection != a:
		return -1
	b -= intersection
	k = 0
	while b != 0:
		if b & 1 == 1:
			k += 1
		b >>= 1
	return k
A = []
d_to_mask = get_digit_masks()
T = fill_transitions(d_to_mask)
(n, K) = invr()
for _ in range(n):
	s = insr()
	d = 0
	for (i, c) in enumerate(s):
		if c == '1':
			d |= 1 << i
	A.append(d)
dp = [[-1] * (K + 1) for _ in range(n + 1)]
dp[n][0] = 0
for index in range(n - 1, -1, -1):
	for d in range(9, -1, -1):
		diff = get_diff(A[index], d_to_mask[d])
		if diff == -1:
			continue
		for k in range(diff, K + 1):
			if dp[index + 1][k - diff] >= 0:
				dp[index][k] = max(d, dp[index][k])
if dp[0][K] == -1:
	print('-1')
else:
	res = []
	for index in range(n):
		res.append(dp[index][K])
		K -= get_diff(A[index], d_to_mask[dp[index][K]])
	print(''.join(map(str, res)))


import sys
sys.setrecursionlimit(10000)
input = sys.stdin.readline

class Memoize:

	def __init__(self, f):
		self.f = f
		self.memo = {}

	def __call__(self, *args):
		if not args in self.memo:
			self.memo[args] = self.f(*args)
		return self.memo[args]

class Recurse(Exception):

	def __init__(self, *args, **kwargs):
		self.args = args
		self.kwargs = kwargs

def recurse(*args, **kwargs):
	raise Recurse(*args, **kwargs)

def tail_recursive(f):

	def decorated(*args, **kwargs):
		while True:
			try:
				return f(*args, **kwargs)
			except Recurse as r:
				args = r.args
				kwargs = r.kwargs
				continue
	return decorated
nums = {0: 119, 1: 18, 2: 93, 3: 91, 4: 58, 5: 107, 6: 111, 7: 82, 8: 127, 9: 123}
rev = {v: k for (k, v) in nums.items()}
counts = {0: 6, 1: 2, 2: 5, 3: 5, 4: 4, 5: 5, 6: 6, 7: 3, 8: 7, 9: 6}
(n, k) = map(int, input().split())
digits = [int(input(), 2) for _ in range(0, n)]
dp = [[0] * (k + 1) for _ in range(n + 1)]
dp[n][0] = 1
for i in range(n - 1, -1, -1):
	for x in range(9, -1, -1):
		used = -1 if nums[x] | digits[i] != nums[x] else bin(nums[x] ^ digits[i]).count('1')
		if used == -1:
			continue
		for j in range(k, -1, -1):
			if j - used < 0:
				continue
			dp[i][j] = dp[i][j] | dp[i + 1][j - used]
if dp[0][k] == 0:
	print('-1')
else:
	ans = ''
	j = k
	for i in range(n):
		for x in range(9, -1, -1):
			used = -1 if nums[x] | digits[i] != nums[x] else bin(nums[x] ^ digits[i]).count('1')
			if used != -1 and j >= used and dp[i + 1][j - used]:
				ans += str(x)
				j -= used
				break
	print(ans)


(n, k) = map(int, input().split())
ss = []
ks = []
kss = []
ka = 0
civ = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
civn = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]
it = ''
pref = []
for i in range(n):
	s = input()
	ss.append(s)
	maa = 10
	kk = []
	kks = []
	for j in range(10):
		ma = 0
		for jj in range(7):
			if s[jj] == '1' and civ[j][jj] == '0':
				ma = 10
			elif s[jj] == '0' and civ[j][jj] == '1':
				ma += 1
		if ma < maa:
			maa = ma
			kk = [j]
		elif ma == maa:
			kk.append(j)
		if ma < 10:
			kks.append(j)
	ka += maa
	pref.append(ka)
	ks.append(kk[:])
	kss.append(kks[:])
if ka > k:
	print(-1)
	exit()
sum = 0
ssk = kss[:]
for i in range(n):
	maxs = pref[-1] - pref[i]
	y = max(kss[i])
	while civn[y] - ss[i].count('1') + sum + maxs > k:
		kss[i].pop(kss[i].index(y))
		y = max(kss[i])
	it += str(y)
	sum += civn[y] - ss[i].count('1')
k -= sum
if k == 0:
	print(it)
	exit()
for i in range(n - 1, -1, -1):
	x = int(it[i])
	ma = civn[x]
	mi = x
	for j in range(len(kss[i])):
		if civn[kss[i][j]] >= ma and k - (civn[kss[i][j]] - civn[x]) >= 0:
			ma = civn[kss[i][j]]
			mi = kss[i][j]
	k += civn[x]
	k -= civn[mi]
	it = it[:i] + str(mi) + it[i + 1:]
	if k == 0:
		break
if k != 0:
	print(-1)
else:
	print(it)


import sys
input = sys.stdin.readline

def main():
	(N, K) = [int(x) for x in input().split()]
	S = [int(input().strip(), 2) for _ in range(N)]
	A = [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
	B = [[-1] * 10 for j in range(N)]
	for (i, s) in enumerate(S):
		for j in range(10):
			if A[j] & s == s:
				B[i][j] = bin(A[j] ^ s).count('1')
	dp = [[0] * (K + 1) for _ in range(N + 2)]
	dp[N + 1][0] = 1
	for i in range(N, -1, -1):
		for j in range(K + 1):
			if dp[i + 1][j] == 0:
				continue
			for k in range(10):
				if B[i - 1][k] == -1 or j + B[i - 1][k] > K:
					continue
				dp[i][j + B[i - 1][k]] = 1
	if dp[1][K] == 0:
		print(-1)
		return
	ans = []
	c = K
	for i in range(1, N + 1):
		for k in range(9, -1, -1):
			if B[i - 1][k] != -1 and c - B[i - 1][k] >= 0 and (dp[i + 1][c - B[i - 1][k]] != 0):
				c -= B[i - 1][k]
				ans.append(str(k))
				break
	print(''.join(ans))
main()


from sys import stdin, gettrace
if not gettrace():

	def input():
		return next(stdin)[:-1]
NUMS = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']

def main():
	(n, k) = map(int, input().split())
	digits = []
	counts = []
	for _ in range(n):
		digit = input()
		digits.append(digit)
		counts.append([])
		for num in NUMS:
			count = 0
			for j in range(7):
				if num[j] == '0' and digit[j] == '1':
					count = k + 1
					break
				if num[j] == '1' and digit[j] == '0':
					count += 1
			counts[-1].append(count)
	prems = [set() for _ in range(n)] + [{0}]
	for i in range(n - 1, -1, -1):
		for c in counts[i]:
			for r in prems[i + 1]:
				if c + r <= k:
					prems[i].add(c + r)
	res = []
	if k not in prems[0]:
		print(-1)
		return
	for i in range(n):
		for j in range(9, -1, -1):
			if k - counts[i][j] in prems[i + 1]:
				res.append(j)
				k -= counts[i][j]
				break
	print(''.join(map(str, res)))
main()


import bisect
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
digits = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
(n, k) = rinput()
s = [input() for _ in range(n)]
howmany = [[0 for i in range(10)] for i in range(n)]
for i in range(n):
	for d in range(10):
		cnt = 0
		(a, b) = (s[i], digits[d])
		for j in range(7):
			if a[j] is '1' and b[j] is '0':
				cnt = -1
				break
			elif a[j] is '0' and b[j] is '1':
				cnt += 1
		howmany[i][d] = cnt
canmake = [[False for i in range(k + 1)] for i in range(n + 1)]
canmake[n][0] = True
for i in range(n, 0, -1):
	for j in range(k + 1):
		if canmake[i][j]:
			for d in range(10):
				if howmany[i - 1][d] != -1 and j + howmany[i - 1][d] <= k:
					canmake[i - 1][j + howmany[i - 1][d]] = True
if not canmake[0][k]:
	print(-1)
	sys.exit()
ans = ''
for i in range(n):
	for d in range(9, -1, -1):
		if howmany[i][d] != -1 and k >= howmany[i][d] and canmake[i + 1][k - howmany[i][d]]:
			ans += str(d)
			k -= howmany[i][d]
			break
print(ans)


numbers = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
(n, m) = list(map(int, input().split()))
changes = [[0] * 10 for i in range(n)]
for i in range(n):
	s = input()
	for j in range(10):
		count = 0
		for k in range(7):
			if numbers[j][k] == '1' and s[k] == '0':
				count += 1
			elif numbers[j][k] == '0' and s[k] == '1':
				count = -1
				break
		changes[i][j] = count
dp = [[0] * (m + 1) for i in range(n + 1)]
dp[n][0] = 1
for i in range(n, 0, -1):
	for j in range(m + 1):
		if dp[i][j]:
			for k in range(10):
				if changes[i - 1][k] != -1 and changes[i - 1][k] + j <= m:
					dp[i - 1][j + changes[i - 1][k]] = 1
if dp[0][m] == 0:
	print(-1)
else:
	for i in range(n):
		num = 0
		for j in range(9, -1, -1):
			if changes[i][j] != -1 and m >= changes[i][j] and dp[i + 1][m - changes[i][j]]:
				num = j
				m -= changes[i][j]
				break
		print(num, end='')


import os
import sys
from io import BytesIO, IOBase

def iin():
	return int(input())

def lin():
	return list(map(int, input().split()))
dc = {0: int('1110111', 2), 1: int('0010010', 2), 2: int('1011101', 2), 3: int('1011011', 2), 4: int('0111010', 2), 5: int('1101011', 2), 6: int('1101111', 2), 7: int('1010010', 2), 8: int('1111111', 2), 9: int('1111011', 2)}

def main():

	def ones_count(a):
		ba = bin(a)
		return ba.count('1')

	def get_all(x):
		ans = []
		ox = ones_count(x)
		for i in range(10):
			if x | dc[i] == dc[i]:
				ans.append([i, ones_count(dc[i]) - ox])
		return ans
	T = 1
	for _ in range(T):
		(n, k) = lin()
		a = [get_all(int(input(), 2)) for i in range(n)]
		a = a[::-1]
		ans = [[-1 for i in range(k + 1)] for j in range(n)]
		for (i, j) in a[0]:
			if j <= k:
				ans[0][j] = max(ans[0][j], i)
		for i in range(1, n):
			for j in range(k + 1):
				j1 = ans[i - 1][j]
				if j1 >= 0:
					for (k1, l) in a[i]:
						if j + l <= k:
							ans[i][j + l] = max(ans[i][j + l], k1)
		if ans[-1][k] > -1:
			sol = []
			j = k
			for i in range(n - 1, -1, -1):
				if j < 0:
					print(-1)
					break
				sol.append(ans[i][j])
				step = 0
				for (l, m) in a[i]:
					if l == ans[i][j]:
						step = m
						break
				j -= step
			else:
				print(*sol, sep='')
		else:
			print(-1)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def a2b(a, b):
	if a & (a ^ b) != 0:
		return -1
	else:
		return sum((d == '1' for d in bin(b & (a ^ b))[2:]))
(n, k) = map(int, input().split())
arr = []
for _ in range(n):
	arr.append(int(input(), 2))
num_txt = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
numbers = list(map(lambda x: int(x, 2), num_txt))
cost = [[0] * 10 for _ in range(n)]
for i in range(n):
	for d in range(10):
		cost[i][d] = a2b(arr[i], numbers[d])
dp = [[0] * (k + 1) for _ in range(n + 1)]
dp[n][0] = 1
for i in range(n, 0, -1):
	for j in range(k + 1):
		if dp[i][j] == 1:
			for d in range(10):
				if cost[i - 1][d] != -1 and cost[i - 1][d] <= k - j:
					dp[i - 1][j + cost[i - 1][d]] = 1
if dp[0][k] == 0:
	print(-1)
else:
	ans = ''
	for i in range(n):
		for d in range(9, -1, -1):
			if 0 <= cost[i][d] <= k and dp[i + 1][k - cost[i][d]] == 1:
				ans += str(d)
				k -= cost[i][d]
				break
	print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
mod = 10 ** 9 + 7
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	fact(x, mod)
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa.reverse()

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def floorsum(a, b, c, n):
	if a == 0:
		return b // c * (n + 1)
	if a >= c or b >= c:
		return floorsum(a % c, b % c, c, n) + b // c * (n + 1) + a // c * n * (n + 1) // 2
	m = (a * n + b) // c
	return n * m - floorsum(c, c - b - 1, a, m - 1)

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

def lowbit(n):
	return n & -n

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class ST:

	def __init__(self, arr):
		n = len(arr)
		mx = n.bit_length()
		self.st = [[0] * mx for i in range(n)]
		for i in range(n):
			self.st[i][0] = arr[i]
		for j in range(1, mx):
			for i in range(n - (1 << j) + 1):
				self.st[i][j] = max(self.st[i][j - 1], self.st[i + (1 << j - 1)][j - 1])

	def query(self, l, r):
		if l > r:
			return -inf
		s = (r + 1 - l).bit_length() - 1
		return max(self.st[l][s], self.st[r - (1 << s) + 1][s])

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] > self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return prime

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		seen.add(u)
		for (v, w) in graph[u]:
			if v not in d or d[v] > d[u] + w:
				d[v] = d[u] + w
				heappush(heap, (d[v], v))
	return d

def GP(it):
	return [[ch, len(list(g))] for (ch, g) in groupby(it)]

def lcm(a, b):
	return a * b // gcd(a, b)

def lis(nums):
	res = []
	for k in nums:
		i = bisect.bisect_left(res, k)
		if i == len(res):
			res.append(k)
		else:
			res[i] = k
	return len(res)

def RP(nums):
	n = len(nums)
	s = set(nums)
	d = {}
	for (i, k) in enumerate(sorted(s), 1):
		d[k] = i
	bi = BIT([0] * (len(s) + 1))
	ans = 0
	for i in range(n - 1, -1, -1):
		ans += bi.query(d[nums[i]] - 1)
		bi.update(d[nums[i]], 1)
	return ans

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None

def nb(i, j):
	for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j - 1], [i, j + 1]]:
		if 0 <= ni < n and 0 <= nj < m:
			yield (ni, nj)

def topo(n):
	q = deque()
	res = []
	for i in range(1, n + 1):
		if ind[i] == 0:
			q.append(i)
			res.append(i)
	while q:
		u = q.popleft()
		for v in g[u]:
			ind[v] -= 1
			if ind[v] == 0:
				q.append(v)
				res.append(v)
	return res

@bootstrap
def gdfs(r, p):
	if len(g[r]) == 1 and p != -1:
		yield None
	for ch in g[r]:
		if ch != p:
			yield gdfs(ch, r)
	yield None
t = 1
for i in range(t):
	(n, k) = RL()
	cnt = [[3000] * 10 for i in range(128)]
	res = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
	for i in range(128):
		for j in range(10):
			c = 0
			for a in range(7):
				if i & 1 << a:
					if res[j][6 - a] == '0':
						c = 3000
						break
				else:
					c += res[j][6 - a] == '1'
			cnt[i][j] = c
	arr = [0] * n
	for i in range(n):
		s = input()
		s = int(s, 2)
		arr[i] = s
	p = [[False] * (k + 1) for i in range(n)]
	for a in range(10):
		change = cnt[arr[-1]][a]
		if change <= k:
			p[-1][change] = True
	for i in range(n - 2, -1, -1):
		for a in range(10):
			change = cnt[arr[i]][a]
			for j in range(change, k + 1):
				p[i][j] = p[i][j] or p[i + 1][j - change]
	if not p[0][k]:
		print(-1)
	else:
		ans = []
		for i in range(n - 1):
			for j in range(9, -1, -1):
				if cnt[arr[i]][j] <= k:
					if p[i + 1][k - cnt[arr[i]][j]]:
						ans.append(str(j))
						k -= cnt[arr[i]][j]
						break
		for j in range(9, -1, -1):
			if cnt[arr[-1]][j] == k:
				ans.append(str(j))
				break
		ans = ''.join(ans)
		print(ans)


import sys, math, cmath, time
start_time = time.time()

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())

def solve():
	(n, kk) = invr()
	a = []
	for i in range(n):
		s = insr()
		a.append(int(s, 2))
	ww = [[-1] * (kk + 1) for i in range(n + 1)]
	q = [[-1] * 8 for i in range(128)]
	qw = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
	ww[n][kk] = 0
	for i in range(128):
		w = bin(i)[2:]
		w = (7 - len(w)) * '0' + w
		for j in range(10):
			qq = 0
			c = 0
			for k in range(7):
				if w[k] == '0' and qw[j][k] == '1':
					c = c + 1
				elif w[k] == '1' and qw[j][k] == '0':
					qq = 1
					break
			if qq == 0:
				q[i][c] = j
	for i in range(n - 1, -1, -1):
		for j in range(kk + 1):
			qq = -1
			for k in range(min(8, (j + 1) * 128)):
				if j + k > kk:
					break
				if q[a[i]][k] > qq and ww[i + 1][j + k] >= 0:
					ww[i][j] = k
					qq = q[a[i]][k]
	qw = []
	if ww[0][0] == -1:
		qw.append(str(ww[0][0]))
	else:
		w = 0
		for i in range(n):
			qw.append(str(q[a[i]][ww[i][w]]))
			w = w + ww[i][w]
	print(''.join(qw))
ONLINE_JUDGE = __debug__
if not ONLINE_JUDGE:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = sys.stdin.readline
t = 1
for tt in range(t):
	solve()
if not ONLINE_JUDGE:
	print('Time Elapsed:', time.time() - start_time, 'seconds')
sys.stdout.close()


CORRECTS = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']

def binary(gen):
	digit = bin(gen)[2:]
	while len(digit) < 7:
		digit = '0' + digit
	return digit

def tocorrect(digit):
	global CORRECTS
	possibles = []
	for correct in CORRECTS:
		changes = 0
		possible = True
		for (correct_segment, segment) in zip(correct, digit):
			if segment == '0' and correct_segment == '1':
				changes += 1
			elif segment == '1' and correct_segment == '0':
				possible = False
				break
		if possible:
			possibles += (changes,)
	possibles.sort()
	return possibles

def newdigit(digit, possibilities, pascazinedine):
	global CORRECT
	for (i, correct) in enumerate(CORRECTS[::-1]):
		number = 9 - i
		changes = 0
		possible = True
		for (correct_segment, segment) in zip(correct, digit):
			if segment == '0' and correct_segment == '1':
				changes += 1
			elif segment == '1' and correct_segment == '0':
				possible = False
				break
		if changes in possibilities and changes < 10 and possible and (not number in pascazinedine):
			return (number, changes)
pregen = {}
for gen in range(128):
	digit = binary(gen)
	pregen[digit] = tocorrect(digit)
(N, K) = map(int, input().split())
scoreboard = []
mintochange = 0
maxtochange = 0
for i in range(N):
	digit = input()
	scoreboard += (digit,)
	mintochange += pregen[digit][0]
	maxtochange += pregen[digit][-1]
possibilities = [[] for x in range(N)]
interdits = [[] for x in range(N)]
for (i_, digit) in enumerate(scoreboard[::-1]):
	i = N - i_ - 1
	possibilities[i] = pregen[digit]
	mini = pregen[digit][0]
	maxi = pregen[digit][-1]
	exceptions = []
	for possibility in range(mini, maxi + 1):
		if not possibility in pregen[digit]:
			exceptions += (possibility,)
	if i_ == 0:
		interdits[i] = exceptions
	elif len(pregen[digit]) == 1:
		try:
			interdits[i] += (pregen[digit][0] + interdits[i - 1][0],)
		except IndexError:
			pass
if mintochange > K or maxtochange < K or K in interdits[0]:
	print(-1)
else:
	k = K
	ans = ''
	for (p, digit) in enumerate(scoreboard):
		mintochange -= pregen[digit][0]
		maxtochange -= pregen[digit][-1]
		maxchangeable = k - mintochange
		minchangeable = k - maxtochange
		possibility = pregen[digit]
		i = 0
		while i < len(possibility):
			if possibility[i] < minchangeable or possibility[i] > maxchangeable:
				del possibility[i]
				i -= 1
			i += 1
		Done = False
		pascazinedine = []
		while not Done:
			(number, changes) = newdigit(digit, possibility, pascazinedine)
			try:
				if k - changes in interdits[p + 1]:
					pass
				else:
					Done = True
			except IndexError:
				Done = True
			if not Done:
				pascazinedine += (number,)
		ans += str(number)
		k -= changes
	print(ans)


import sys
input = sys.stdin.readline
from operator import itemgetter
(N, K) = map(int, input().split())
Ss = [input().rstrip() for _ in range(N)]
Seg = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
nSeg = [int(S, 2) for S in Seg]

def possiblenum(S):
	nS = int(S, 2)
	ret = {}
	for (num, T) in enumerate(nSeg):
		if T | nS == T:
			need = bin(T ^ nS).count('1')
			if need in ret:
				ret[need] = max(num, ret[need])
			else:
				ret[need] = num
	return ret
dp = [[-1] * (K + 1) for _ in range(N)]
par = [[-1] * (K + 1) for _ in range(N)]
que = [0]
for (i, S) in enumerate(Ss):
	dic = possiblenum(S)
	NUMs = list(dic.items())
	NUMs.sort(key=itemgetter(1), reverse=True)
	qq = []
	for ind in que:
		for (need, num) in NUMs:
			if ind + need <= K and dp[i][ind + need] == -1:
				dp[i][ind + need] = num
				par[i][ind + need] = ind
				qq.append(ind + need)
	que = qq
if dp[N - 1][K] == -1:
	print(-1)
else:
	ind = K
	ans = ''
	for i in reversed(range(N)):
		num = dp[i][ind]
		ind = par[i][ind]
		ans += str(num)
	print(ans[::-1])


import sys

def f():
	(n, k) = map(int, input().split())
	ch = {0: '1110111', 1: '0010010', 2: '1011101', 3: '1011011', 4: '0111010', 5: '1101011', 6: '1101111', 7: '1010010', 8: '1111111', 9: '1111011'}
	l = []
	for _ in range(n):
		l.append(sys.stdin.readline().rstrip())

	def tr(s1, s2):
		tot = 0
		for i in range(7):
			if s1[i] == '1' and s2[i] == '0':
				return 10000000
			elif s1[i] == '0' and s2[i] == '1':
				tot += 1
		return tot
	trd = {}
	acc = {}
	for i in range(2 ** 7):
		s1 = bin(i)[2:].zfill(7)
		trd[s1] = {}
		acc[s1] = set()
		for j in range(10):
			s2 = ch[j]
			cout = tr(s1, s2)
			trd[s1][s2] = cout
			if cout < 8:
				acc[s1].add(cout)
	poss = True
	remp = [[False for i in range(k + 1)] for j in range(n)]
	usable = [0]
	for ind in range(n - 1, -1, -1):
		new_usable = set()
		for modif in usable:
			for diff in acc[l[ind]]:
				if diff + modif <= k:
					remp[ind][modif + diff] = True
					new_usable.add(modif + diff)
		usable = new_usable
	rep = []
	for i in range(n):
		found = False
		for c in range(9, -1, -1):
			cout = trd[l[i]][ch[c]]
			if i < n - 1 and cout <= k and remp[i + 1][k - cout] or (i == n - 1 and cout == k):
				rep.append(c)
				k -= cout
				found = True
				break
		if not found:
			poss = False
			break
	if poss:
		print(*rep, sep='')
	else:
		print(-1)
f()


(n, k) = map(int, input().split())
str1 = []
for i in range(n):
	str1.append(input())
digit = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
poss = [[0 for d in range(10)] for i in range(n)]
for i in range(n):
	for d in range(10):
		temp = str1[i]
		stat = 0
		for j in range(7):
			if temp[j] == '1' and digit[d][j] == '0':
				stat = -1
				break
			elif temp[j] == '0' and digit[d][j] == '1':
				stat += 1
		poss[i][d] = stat
make = [[False for i in range(k + 1)] for j in range(n + 1)]
make[n][0] = True
for i in range(n, 0, -1):
	for j in range(k + 1):
		if make[i][j] == True:
			for d in range(10):
				if poss[i - 1][d] != -1 and j + poss[i - 1][d] <= k:
					make[i - 1][j + poss[i - 1][d]] = True
if make[0][k] != True:
	print(-1)
else:
	fin = ''
	for i in range(n):
		for j in range(9, -1, -1):
			if poss[i][j] != -1 and poss[i][j] <= k and make[i + 1][k - poss[i][j]]:
				fin += str(j)
				k -= poss[i][j]
				break
	print(fin)


from sys import stdin, stdout
from collections import defaultdict, Counter
input = stdin.readline

def check(d, arr):
	for x in arr:
		if x[0] == d:
			return True
	return False

def valll(arr, d):
	for x in arr:
		if x[0] == d:
			return x[1]
	return -1

def poss(s):
	res = []
	count = 10
	aru = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
	aru = aru[::-1]
	for s1 in aru:
		count -= 1
		fl = 0
		for i in range(7):
			if s1[i] == '1' and s[i] == '0':
				fl += 1
			elif s1[i] == '0' and s[i] == '1':
				fl = 10 ** 10
				break
		if fl != 10 ** 10:
			res.append([str(count), fl])
	return res
(n, k) = list(map(int, input().split()))
dist = [[-1 for __ in range(10)] for _____ in range(n)]
a = []
for _ in range(n):
	aaa = input()
	a.append(aaa[:-1])
iii = 0
for x in a:
	vall = poss(x)
	for y in vall:
		dist[iii][int(y[0])] = y[1]
	iii += 1
dp = [[0 for __ in range(k + 1)] for ____ in range(n + 1)]
dp[n][0] = 1
for i in range(n, 0, -1):
	for j in range(k + 1):
		if dp[i][j]:
			for d in range(10):
				if dist[i - 1][d] != -1 and dist[i - 1][d] + j <= k:
					dp[i - 1][dist[i - 1][d] + j] = 1
flag = 0
if dp[0][k] == 0:
	print(-1)
	flag = -1
if flag == 0:
	for i in range(n):
		now = -1
		for d in range(9, -1, -1):
			if dist[i][d] != -1 and dist[i][d] <= k and dp[i + 1][k - dist[i][d]]:
				now = d
				k -= dist[i][d]
				break
		print(now, end='')
	print()


import sys
import bisect
input = sys.stdin.readline
t = 1
for _ in range(t):
	(n, k) = map(int, input().split())
	count = [[-1] * 10 for j in range(n)]
	l = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
	d = {}
	for i in range(n):
		d[i] = []
	for i in range(n):
		d[i] = input()
		for j in range(10):
			cnt = 0
			for j1 in range(7):
				if l[j][j1] == '0' and d[i][j1] == '1':
					cnt = -1
					break
				elif l[j][j1] != d[i][j1]:
					cnt += 1
			if cnt != -1:
				count[i][j] = cnt
	ans = [[0] * (k + 1) for j in range(n + 1)]
	ans[n][0] = 1
	for i in range(n, 0, -1):
		for j in range(k + 1):
			if ans[i][j] == 1:
				for i1 in range(10):
					if count[i - 1][i1] != -1 and j + count[i - 1][i1] <= k:
						ans[i - 1][j + count[i - 1][i1]] = 1
	if ans[0][k] == 0:
		print(-1)
	else:
		for i in range(n):
			for j in range(9, -1, -1):
				if count[i][j] != -1 and count[i][j] <= k and (ans[i + 1][k - count[i][j]] == 1):
					maxi = j
					k -= count[i][j]
					break
			print(maxi, end='')


from sys import stdin, stdout
input = stdin.readline
from math import *
print = stdout.write

def cst(s, d):
	res = 0
	for i in range(7):
		if s[i] == '1' and d[i] == '0':
			return -1
		elif s[i] == '0' and d[i] == '1':
			res += 1
	return res
(n, k) = map(int, input().split())
d = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
cost = [[0] * 10 for i in range(n)]
t = [[0] * (k + 1) for i in range(n)]
for i in range(n):
	s = input()
	for j in range(10):
		cost[i][j] = cst(s, d[j])
ans = [-1] * n

def dfs(i, k):
	if i == n and k == 0:
		return True
	elif i == n and k != 0:
		return False
	if t[i][k] != 0:
		return t[i][k] == 1
	for j in range(9, -1, -1):
		temp = cost[i][j]
		if temp >= 0 and temp <= k and dfs(i + 1, k - cost[i][j]):
			ans[i] = j
			t[i][k] = 1
			return True
	t[i][k] = -1
	return False
dfs(0, k)
if -1 in ans:
	print('-1')
else:
	print(''.join(map(str, ans)))


import sys
sys.setrecursionlimit(1000000000)

def fastio():
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
INF = 10 ** 20
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br
encode = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
enc = [int(i, 2) for i in encode]
req = [i.count('1') for i in encode]
(n, k) = I()
min_stick = [0] * (n + 1)
max_stick = [0] * (n + 1)
(l, a) = ([], [])
s = 0
for i in range(n):
	s = input()
	t = int(s, 2)
	l.append(t)
	a.append(t)
	if t not in enc:
		min_stick[i] = INF
		max_stick[i] = -INF
		for j in enc:
			if j & t == t:
				extra = bin(j ^ t).count('1')
				min_stick[i] = min(min_stick[i], extra)
				if extra == min_stick[i]:
					a[i] = j
		if min_stick[i] == INF:
			print(-1)
			exit()
	max_stick[i] = s.count('0')
if k > sum(max_stick) or k < sum(min_stick):
	print(-1)
	exit()
for i in range(n - 2, -1, -1):
	min_stick[i] += min_stick[i + 1]
	max_stick[i] += max_stick[i + 1]

def dfs(idx, cur):
	if idx == n and cur == 0:
		print(*[enc.index(i) for i in a], sep='')
		exit()
	if cur < min_stick[idx] or cur > max_stick[idx]:
		return
	for i in range(9, -1, -1):
		if enc[i] & l[idx] == l[idx]:
			extra = bin(enc[i] ^ l[idx]).count('1')
			a[idx] = enc[i]
			dfs(idx + 1, cur - extra)
dfs(0, k)
print(-1)


from sys import setrecursionlimit
from functools import lru_cache

def main():
	ans = solve_case()
	print(ans)

def solve_case():
	(n, k) = read_int_list()
	digits = read_lines(n, read_str)
	num_to_digit = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
	digit_to_num = dict()
	for num in range(10):
		digit_to_num[num_to_digit[num]] = num

	def is_valid_digit(digit):
		return digit in num_to_digit

	@lru_cache(maxsize=None)
	def cost_to_transform(digit, target_digit):
		need_sticks = 0
		for stick_idx in range(7):
			if target_digit[stick_idx] == '0':
				if digit[stick_idx] == '0':
					pass
				else:
					return -1
			elif digit[stick_idx] == '0':
				need_sticks += 1
			else:
				pass
		return need_sticks

	def can_transform_to(digit):
		psbl_num_costs = []
		for num in reversed(range(10)):
			target_digit = num_to_digit[num]
			cost = cost_to_transform(digit, target_digit)
			if cost == -1:
				continue
			psbl_num_costs.append((num, cost))
		return psbl_num_costs
	digit_transforms = [can_transform_to(digit) for digit in digits]
	min_cost_from = [0] * (n + 1)
	max_cost_from = [0] * (n + 1)
	for i in reversed(range(n)):
		min_cost = min((cost for (num, cost) in digit_transforms[i]))
		max_cost = max((cost for (num, cost) in digit_transforms[i]))
		min_cost_from[i] = min_cost + min_cost_from[i + 1]
		max_cost_from[i] = max_cost + max_cost_from[i + 1]
	ans = [None] * n

	@lru_cache(maxsize=None)
	def max_nums(stick_cnt, from_digit_idx):
		if from_digit_idx == len(digits):
			if stick_cnt == 0:
				return True
			else:
				return None
		if not min_cost_from[from_digit_idx] <= stick_cnt <= max_cost_from[from_digit_idx]:
			return None
		if stick_cnt < 0:
			return None
		if stick_cnt == 0:
			if all((is_valid_digit(digit) for digit in digits[from_digit_idx:])):
				for di in range(from_digit_idx, n):
					ans[di] = digit_to_num[digits[di]]
				return True
		num_costs = digit_transforms[from_digit_idx]
		for (num, cost) in num_costs:
			max_nums_after = max_nums(stick_cnt - cost, from_digit_idx + 1)
			if max_nums_after is None:
				continue
			ans[from_digit_idx] = num
			return True
		return None
	max_nums(k, 0)
	if ans[0] is None:
		return -1
	return l2s(ans, '')

def read_str():
	return input()

def read_int():
	return int(input())

def read_str_list():
	return input().split(' ')

def read_int_list():
	return list(map(int, input().split(' ')))

def read_lines(n, read_func):
	return [read_func() for _ in range(n)]

def list_to_str(l, sep=' '):
	return sep.join(map(str, l))
l2s = list_to_str

def make_list(shape, value=None):
	if len(shape) == 1:
		return [value] * shape[0]
	return [make_list(shape[1:], value) for _ in range(shape[0])]
setrecursionlimit(1000000)
main()