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:

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.

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_HARD
Tags: Dynamic programming

Bit manipulation

Graph algorithms

Greedy algorithms


Solutions:
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)


def binStringToInt(s):
	return int(s, base=2)

def binIntToString(x):
	return bin(x)[2:]
numToString = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
digits = [[-1 for _ in range(10)] for __ in range(2 ** 7)]
for i in range(2 ** 7):
	iS = binIntToString(i)
	for num in range(10):
		numS = numToString[num]
		num2 = binStringToInt(numS)
		if i | num2 == num2:
			digits[i][num] = numS.count('1') - iS.count('1')
(n, k) = [int(x) for x in input().split()]
board = []
for _ in range(n):
	board.append(binStringToInt(input()))
possibleMoves = [set() for _ in range(n)]
for i in range(n):
	binaryInt = board[i]
	for num in range(10):
		if digits[binaryInt][num] != -1:
			possibleMoves[i].add(digits[binaryInt][num])
dp = [[False for _ in range(k + 1)] for __ in range(n + 1)]
dp[n][0] = True
for i in range(n - 1, -1, -1):
	for kk in range(k + 1):
		for cost in possibleMoves[i]:
			if kk - cost >= 0 and dp[i + 1][kk - cost] == True:
				dp[i][kk] = True
				break
if dp[0][k] == True:
	ans = ''
	currK = k
	for i in range(n):
		binaryInt = board[i]
		for num in range(9, -1, -1):
			cost = digits[binaryInt][num]
			if cost != -1 and currK - cost >= 0 and (dp[i + 1][currK - cost] == True):
				ans = ans + str(num)
				currK -= cost
				break
	print(ans)
else:
	print(-1)


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

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

def cost(good, broken):
	ans = 0
	for i in range(7):
		if good[i] == '0' and broken[i] == '1':
			return -1
		if good[i] == '1' and broken[i] == '0':
			ans += 1
	return ans
s = ['{:07b}'.format(i) for i in range(128)]
d = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
f = [[-1 for i in range(8)] for j in range(128)]
g = [[] for i in range(128)]
lc = []
rc = []
for i in range(128):
	for j in range(10):
		c = cost(d[j], s[i])
		if c == -1:
			continue
		if f[i][c] == -1:
			g[i].append(c)
		f[i][c] = max(f[i][c], j)
	g[i].sort()
	lc.append(g[i][0])
	rc.append(g[i][-1])
(n, k) = read_ints()
nums = []
total = 0
for i in range(n):
	num = input()
	for stick in num:
		if stick == '1':
			total += 1
	nums.append(int(num, 2))
if total + k > 7 * n:
	print(-1)
else:
	lo = 0
	ls = [0]
	rs = [0]
	for i in range(n):
		ls.append(ls[-1] + lc[nums[i]])
		rs.append(rs[-1] + rc[nums[i]])
	if k < ls[n]:
		print(-1)
	else:
		ans = [-1 for i in range(n)]
		used = 0
		for i in range(n):
			rmin = ls[n] - ls[i + 1]
			rmax = rs[n] - rs[i + 1]
			u = 0
			for j in g[nums[i]]:
				if rmin <= k - used - j <= rmax:
					if f[nums[i]][j] > ans[i]:
						ans[i] = f[nums[i]][j]
						u = j
			used += u
		print(int(''.join(map(str, ans))))


(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)


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)


from sys import stdin, stdout
arr = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
d = {}
dr = {}
for i in range(len(arr)):
	d[i] = int(arr[i], 2)
	dr[int(arr[i], 2)] = i
trans = [[] for i in range(1 << 7)]
for i in range(1 << 7):
	for j in range(9, -1, -1):
		target = d[j]
		if target | i == target:
			trans[i].append(target)
			trans[i].append(bin(target ^ i).count('1'))
(n, k) = stdin.readline().strip().split(' ')
(n, k) = (int(n), int(k))
arr = []
for i in range(n):
	arr.append(int(stdin.readline().strip(), 2))
arr = arr[::-1]
dp = [[None for i in range(2001)] for j in range(2001)]
dp[0][0] = (0, 0)
for i in range(1, n + 1):
	for j in range(k + 1):
		curr_mask = arr[i - 1]
		for k1 in range(0, len(trans[curr_mask]), 2):
			new_mask = trans[curr_mask][k1]
			cost = trans[curr_mask][k1 + 1]
			if j - cost >= 0:
				if dp[i - 1][j - cost] != None:
					dp[i][j] = (cost, dr[new_mask])
					break
if dp[n][k] == None:
	stdout.write('-1\n')
else:
	ans = ''
	while n != 0:
		ans += str(dp[n][k][1])
		k -= dp[n][k][0]
		n -= 1
	stdout.write(ans + '\n')


(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, sys
from io import BytesIO, IOBase

def bit_count(x):
	ans = 0
	while x:
		x &= x - 1
		ans += 1
	return ans

def main():
	(n, k) = map(int, input().split())
	hir = [123, 127, 82, 111, 107, 58, 91, 93, 18, 119]
	if not k:
		l = []
		for _ in range(n):
			x = int(input().strip(), 2)
			if x in hir:
				l.append(9 - hir.index(x))
		if len(l) == n:
			print(''.join(map(str, l)))
		else:
			print(-1)
		exit()
	dp = [[0 for _ in range(k + 1)] for _ in range(n)]
	x = int(input().strip(), 2)
	order = [[] for _ in range(n)]
	for (ind, j) in enumerate(hir):
		if j | x == j:
			y = bit_count(j ^ x)
			if y <= k and (not dp[0][y]):
				dp[0][y] = (9 - ind, y)
				order[0].append(y)
	for i in range(1, n):
		x = int(input().strip(), 2)
		(valid, inc) = ([], [])
		for (ind, j) in enumerate(hir):
			if j | x == j:
				valid.append(9 - ind)
				inc.append(bit_count(j ^ x))
		for t in order[i - 1]:
			for (a, b) in zip(valid, inc):
				if t + b <= k and (not dp[i][t + b]):
					dp[i][t + b] = (a, b)
					order[i].append(t + b)
	if not dp[-1][-1]:
		print(-1)
	else:
		xx = []
		(st, st1) = (k, n - 1)
		while st1 != -1:
			xx.append(str(dp[st1][st][0]))
			st -= dp[st1][st][1]
			st1 -= 1
		print(''.join(map(str, reversed(xx))))
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()


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__)


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 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)


from sys import stdin, stdout
codes = dict()

def create_codes():
	digits = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
	global codes
	for i in range(128):
		c = '{:07b}'.format(i)
		cnt_dict = dict()
		for (k, x) in enumerate(digits):
			cnt = 0
			for j in range(7):
				if c[j] > x[j]:
					j -= 1
					break
				elif c[j] < x[j]:
					cnt += 1
			if j == 6:
				cnt_dict[k] = cnt
		codes[c] = cnt_dict

def main():
	(n, k) = list(map(int, stdin.readline().split()))
	global codes
	create_codes()
	inp = []
	for _ in range(n):
		code = stdin.readline().rstrip()
		inp.append(code)
	dp = [[False] * (k + 1) for _ in range(n + 1)]
	dp[n][0] = True
	for i in range(n, 0, -1):
		code = inp[i - 1]
		for j in range(k + 1):
			if not dp[i][j]:
				continue
			for (key, val) in codes[code].items():
				if val + j > k:
					continue
				dp[i - 1][val + j] = True
	if not dp[0][k]:
		stdout.write('-1')
		return
	for i in range(n):
		code = inp[i]
		for d in range(9, -1, -1):
			if d in codes[code] and k - codes[code][d] >= 0 and dp[i + 1][k - codes[code][d]]:
				k -= codes[code][d]
				stdout.write(str(d))
				break
main()


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 + 1)]
dp[n][k] = 1
for i in reversed(range(n)):
	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 p + cc <= k and dp[i + 1][p + cc]:
			res.append(num)
			p += cc
			break
print(''.join(map(str, res)))


import sys
(n, k) = map(int, input().split())
digits = []
ex = [[0] * 10 for _ in range(n)]
a = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
a = list(map(lambda s: int(s, 2), a))
for i in range(n):
	x = int(input(), 2)
	for d in range(10):
		ex[i][d] = bin(a[d] - x).count('1')
	digits.append(x)
dp = [[False] * (k + 1) for _ in range(n + 1)]
dp[n][0] = True
for i in range(n - 1, -1, -1):
	for x in range(k + 1):
		for d in range(10):
			if a[d] & digits[i] != digits[i]:
				continue
			excess = ex[i][d]
			if x - excess >= 0 and dp[i + 1][x - excess]:
				dp[i][x] = True
				break
ans = ''
cur = k
for i in range(n):
	found = False
	for d in range(9, -1, -1):
		if a[d] & digits[i] != digits[i]:
			continue
		excess = ex[i][d]
		if cur - excess >= 0 and dp[i + 1][cur - excess]:
			cur -= excess
			ans += str(d)
			found = True
			break
	if not found:
		print(-1)
		exit()
print(ans)


(n, k) = list(map(int, input().split()))
numbers = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
distance = [[0] * 10 for i in range(n)]
for i in range(n):
	s = str(input())
	for j in range(10):
		for l in range(7):
			if s[l] == '0' and numbers[j][l] == '1':
				distance[i][j] += 1
			elif s[l] == '1' and numbers[j][l] == '0':
				distance[i][j] = -1
				break
dp = [[0] * (k + 1) for i 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 l in range(10):
				if distance[i - 1][l] != -1 and j + distance[i - 1][l] <= k:
					dp[i - 1][j + distance[i - 1][l]] = 1
if dp[0][k] == 0:
	print(-1)
else:
	ans = ''
	for i in range(n):
		temp = -1
		for j in range(9, -1, -1):
			if distance[i][j] != -1 and k >= distance[i][j] and (dp[i + 1][k - distance[i][j]] == 1):
				temp = j
				k -= distance[i][j]
				break
		ans += str(temp)
	print(ans)


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()


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

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

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify, _heapify_max, _heappop_max, nsmallest, nlargest
INF = 999999999999999999999999
alphabets = 'abcdefghijklmnopqrstuvwxyz'

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

class SegTree:

	def __init__(self, n):
		self.N = 1 << n.bit_length()
		self.tree = [0] * (self.N << 1)

	def update(self, i, j, v):
		i += self.N
		j += self.N
		while i <= j:
			if i % 2 == 1:
				self.tree[i] += v
			if j % 2 == 0:
				self.tree[j] += v
			(i, j) = (i + 1 >> 1, j - 1 >> 1)

	def query(self, i):
		v = 0
		i += self.N
		while i > 0:
			v += self.tree[i]
			i >>= 1
		return v

def SieveOfEratosthenes(limit):
	isPrime = [True] * (limit + 1)
	isPrime[0] = isPrime[1] = False
	primes = []
	for i in range(2, limit + 1):
		if not isPrime[i]:
			continue
		primes += [i]
		for j in range(i * i, limit + 1, i):
			isPrime[j] = False
	return primes
from collections import Counter

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def memodict(f):

	class memodict(dict):

		def __missing__(self, key):
			ret = self[key] = f(key)
			return ret
	return memodict().__getitem__

def pollard_rho(n):
	if n & 1 == 0:
		return 2
	if n % 3 == 0:
		return 3
	s = (n - 1 & 1 - n).bit_length() - 1
	d = n >> s
	for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
		p = pow(a, d, n)
		if p == 1 or p == n - 1 or a % n == 0:
			continue
		for _ in range(s):
			prev = p
			p = p * p % n
			if p == 1:
				return gcd(prev - 1, n)
			if p == n - 1:
				break
		else:
			for i in range(2, n):
				(x, y) = (i, (i * i + 1) % n)
				f = gcd(abs(x - y), n)
				while f == 1:
					(x, y) = ((x * x + 1) % n, (y * y + 1) % n)
					y = (y * y + 1) % n
					f = gcd(abs(x - y), n)
				if f != n:
					return f
	return n

@memodict
def prime_factors(n):
	if n <= 1:
		return Counter()
	f = pollard_rho(n)
	return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)

def distinct_factors(n):
	factors = [1]
	for (p, exp) in prime_factors(n).items():
		factors += [p ** i * factor for factor in factors for i in range(1, exp + 1)]
	return factors

def all_factors(n):
	(small, large) = ([], [])
	for i in range(1, int(n ** 0.5) + 1, 2 if n & 1 else 1):
		if not n % i:
			small.append(i)
			large.append(n // i)
	if small[-1] == large[-1]:
		large.pop()
	large.reverse()
	small.extend(large)
	return small

def main():
	mod = 1000000007
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	tc = 1
	tc = 1
	for _ in range(tc):
		(n, k) = ria()
		segments = ['.']
		for i in range(n):
			segments.append(rs())
		digits = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']

		def cost(board, digits):
			c = 0
			for i in range(7):
				if board[i] == '1' and digits[i] == '0':
					return -1
				if board[i] == '0' and digits[i] == '1':
					c += 1
			return c
		costs = [[-1 for i in range(10)] for j in range(n + 1)]
		for i in range(1, n + 1):
			for d in range(10):
				costs[i][d] = cost(segments[i], digits[d])
		dp = [[0 for i in range(k + 1)] for j in range(n + 1)]
		for d in range(10):
			c = costs[n][d]
			if c != -1 and c <= k:
				dp[n][c] = 1
		for i in range(n, 1, -1):
			for j in range(k + 1):
				for d in range(10):
					if dp[i][j] and 0 <= costs[i - 1][d] <= k - j:
						dp[i - 1][j + costs[i - 1][d]] = 1
		if dp[1][k] == 0:
			wi(-1)
		else:
			curr = k
			ans = []
			for i in range(1, n):
				for d in range(9, -1, -1):
					if dp[i][curr] and 0 <= costs[i][d] <= curr and dp[i + 1][curr - costs[i][d]]:
						ans.append(str(d))
						curr -= costs[i][d]
						break
			for d in range(9, -1, -1):
				if curr == costs[n][d]:
					ans.append(str(d))
					break
			ws(''.join(ans))
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			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, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			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()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

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

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


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()


(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)


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
digits = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
counts = [s.count('1') for s in digits]
bits = [int(s, 2) for s in digits]
(n, k) = list(map(int, stdin.readline().split()))
poss = [[] for i in range(n)]
for i in range(n):
	s = stdin.readline()
	count = s.count('1')
	bit = int(s, 2)
	for d in range(9, -1, -1):
		if bit & bits[d] == bit:
			poss[i].append((d, counts[d] - count))
dp = [[False] * (k + 1) for i in range(n + 1)]
dp[0][0] = True
for i in range(n):
	allowed = poss[n - i - 1]
	for j in range(k + 1):
		if dp[i][j]:
			for (_, c) in allowed:
				if j + c <= k:
					dp[i + 1][j + c] = True
out = ''
if dp[n][k]:
	curr = k
	for i in range(n):
		for (v, c) in poss[i]:
			if curr - c >= 0 and dp[n - i - 1][curr - c]:
				out += str(v)
				curr -= c
				break
		assert dp[n - i - 1][curr]
	print(out)
else:
	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()


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

def I():
	return sys.stdin.readline().rstrip()
cds = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']

def dist(s, n):
	cs = cds[n]
	cost = 0
	for (c, cc) in zip(s, cs):
		if c != cc:
			if c == '1':
				return (False, 0)
			cost += 1
	return (True, cost)

def main():
	(n, k) = map(int, I().split())
	dstring = [I() for _ in range(n)]
	lens = {n: [0]}
	dp = [[None] * (k + 1) for _ in range(n + 1)]
	dp[n][0] = ('-', 0)
	for i in range(n - 1, -1, -1):
		idone = set()
		lens[i] = set()
		for d in range(9, -1, -1):
			char = chr(ord('0') + d)
			res = dist(dstring[i], d)
			if res[0]:
				diff = res[1]
				if diff in idone:
					continue
				idone.add(diff)
				for ln in lens[i + 1]:
					ndiff = ln + diff
					if ndiff <= k and ndiff not in lens[i]:
						lens[i].add(ndiff)
						dp[i][ndiff] = (char, diff)
	if dp[0][k] != None:
		ans = []
		for i in range(n):
			dpv = dp[i][k]
			ans.append(dpv[0])
			k -= dpv[1]
		print(''.join(ans))
	else:
		print('-1')
main()


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')
(n, k) = map(int, input().split())
vals = []
for j in range(n):
	vals.append(int(input(), 2))
rep = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
for s in range(len(rep)):
	rep[s] = int(rep[s], 2)
cost = [[] for s in range(n)]
nums = [[] for s in range(n)]
for s in range(n):
	int1 = vals[s]
	found = set([])
	for b in range(9, -1, -1):
		count = 0
		broke = False
		int2 = rep[b]
		joined = int1 ^ int2
		if joined | int2 == int2:
			count = bin(joined).count('1')
		else:
			broke = True
		if broke == False and (not count in found):
			found.add(count)
			cost[s].append(count)
			nums[s].append(b)
dp = [[0 for s in range(k + 1)] for s in range(n)]
dp[n - 1][k] = 1
previous = set([k])
broke = False
for s in range(n - 2, -1, -1):
	new = set([])
	for i in range(len(cost[s + 1])):
		for b in previous:
			if b - cost[s + 1][i] >= 0:
				new.add(b - cost[s + 1][i])
				dp[s][b - cost[s + 1][i]] = 1
	if len(new) == 0:
		broke = True
		break
	else:
		previous = new
cv = 0
for s in range(len(cost[0])):
	if cost[0][s] <= k and dp[0][cost[0][s]] == 1:
		continue
	else:
		cv += 1
if cv == len(cost[0]):
	broke = True
if broke == False:
	cumsum = 0
	ans = []
	for s in range(n):
		for b in range(len(cost[s])):
			if cumsum + cost[s][b] <= k and dp[s][cumsum + cost[s][b]] == 1:
				ans.append(str(nums[s][b]))
				cumsum += cost[s][b]
				break
	print(''.join(ans))
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')
nums = {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)}
(n, ki) = map(int, input().split(' '))
li = []
for i in range(n):
	li.append(int(input(), 2))
d = [{}]
for (k, v) in nums.items():
	c = 0
	if li[-1] & v == li[-1]:
		cur = li[-1] ^ v
		while cur:
			c += 1
			cur -= cur & -cur
		d[0][c] = (max(k, d[0].get(c, (0, c))[0]), c)
li.pop()
dc = {}
ctr = 1
while len(li):
	ctr += 1
	for (k, v) in nums.items():
		c = 0
		if li[-1] & v == li[-1]:
			cur = li[-1] ^ v
			while cur:
				c += 1
				cur -= cur & -cur
			for (j, jv) in d[-1].items():
				if j + c <= 2000:
					if j + c in dc:
						if dc[j + c][0] > k:
							continue
						else:
							dc[j + c] = (k, c)
							continue
					dc[j + c] = (k, c)
	d.append(dc)
	dc = {}
	li.pop()
if ki in d[-1]:
	while len(d):
		print(d[-1][ki][0], end='')
		ki -= d[-1][ki][1]
		d.pop()
else:
	print(-1)


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()


from collections import deque
nums = [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
(n, k) = 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

def compare(x, s):
	for i in range(len(x)):
		if x[i] == '1' and s[i] == '0':
			return False
	return True

def compare2(x, s):
	count = 0
	for i in range(len(x)):
		if x[i] == '0' and s[i] == '1':
			count += 1
	return count
li = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
dummy = li + []
dict = {}
num = 0
for i in li:
	dict[i] = num
	num += 1
(n, k) = [int(x) for x in input().split()]
arr = []
for i in range(n):
	s = input()
	arr.append(s)
ans = []
k_ans = []
for i in range(len(arr)):
	need = 0
	if dict.get(arr[i]) is not None:
		ans.append(arr[i])
	else:
		need = 7
		todo = li[8]
		for j in li:
			if compare(arr[i], j):
				p = compare2(arr[i], j)
				if p < need:
					need = p
					todo = j
		k -= need
		ans.append(todo)
	k_ans.append(need)
if k < 0:
	print(-1)
	sys.exit(0)
to_print = ''
li = li[::-1]
for i in range(n):
	s = ans[i]
	for j in li:
		if dict[j] <= dict[s]:
			break
		if compare(arr[i], j):
			p = compare2(arr[i], j)
			if p - k_ans[i] <= k:
				ans[i] = j
				k -= p - k_ans[i]
				k_ans[i] = p
				break
if k >= 2:
	for i in range(n - 1, -1, -1):
		if dict[ans[i]] == 7:
			if compare(arr[i], dummy[5]):
				ans[i] = dummy[5]
				k -= 2
			else:
				ans[i] = dummy[3]
				k -= 2
			break
flag = 0
if k > 0:
	index = 0
	for i in range(n - 1, -1, -1):
		for j in li:
			if dict[j] < dict[ans[i]] and compare(arr[i], j):
				p = compare2(arr[i], j)
				if p - k_ans[i] <= k:
					k -= p - k_ans[i]
					if p - k_ans[i] < 0:
						flag = 1
					else:
						flag = 2
					ans[i] = j
					index = i
					break
		if flag != 0:
			break
	if flag == 1:
		nn = 0
		for i in range(index + 1, n):
			for j in li:
				if dict[j] > dict[ans[i]] and compare(arr[i], j):
					p = compare2(arr[i], j)
					if p - k_ans[i] > k:
						continue
					k -= p - k_ans[i]
					ans[i] = j
					nn = 1
					break
			if nn == 1:
				break
		if nn == 0:
			for i in range(n - 1, -1, -1):
				if dict[ans[i]] == 7:
					if compare(arr[i], dummy[5]):
						ans[i] = dummy[5]
						k -= 2
					else:
						ans[i] = dummy[3]
						k -= 2
					break
if k > 0:
	for i in range(n - 1, -1, -1):
		if k == 0:
			break
		if dict[ans[i]] == 9:
			ans[i] = dummy[8]
			k -= 1
if k > 0:
	print(-1)
	sys.exit(0)
for i in range(n):
	print(dict[ans[i]], end='')


vk = dict(zip(range(10), ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']))
kv = {k: v for (v, k) in vk.items()}

def transfer(s1, s2):
	reachable = True
	dist = 0
	for (x, y) in zip(s1, s2):
		if y == '0' and x == '1':
			reachable = False
			break
		elif y == '1' and x == '0':
			dist += 1
	return (reachable, dist)
(n, k) = list(map(int, input().split()))
rep = []
for _ in range(n):
	rep.append(input())
target = {}
for i in range(n):
	for j in range(9, -1, -1):
		(reachable, dist) = transfer(rep[i], vk[j])
		if reachable and dist <= k:
			target[i, j] = dist
f = [[-1 for _ in range(k + 1)] for _ in range(n + 1)]
f[n][0] = 1
for j in range(9, -1, -1):
	if (i, j) in target:
		dist = target[i, j]
		f[n - 1][dist] = 1
for i in range(n - 2, -1, -1):
	for j in range(9, -1, -1):
		if (i, j) in target:
			dist = target[i, j]
			for w in range(dist, k + 1):
				if f[i + 1][w - dist] == 1:
					f[i][w] = 1
if f[0][k] == -1:
	print(-1)
else:
	ans = []
	quota = k
	for i in range(n):
		for j in range(9, -1, -1):
			if (i, j) in target:
				dist = target[i, j]
				if dist <= quota and f[i + 1][quota - dist] == 1:
					ans.append(j)
					quota -= dist
					break
	print(''.join(map(str, 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)


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)


def b_d(x):
	dec = 0
	for i in x:
		dec = 2 * dec + int(i)
	return dec
(n, c) = map(int, input().split())
a = []
for i in range(n):
	st = input()
	a.append(st)
b = [[] for i in range(n + 1)]
cc = '1111111'
count = 0
bina = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
for i in range(n):
	for j in range(10):
		if b_d(a[i]) & b_d(bina[j]) == b_d(a[i]):
			e = bin((b_d(a[i]) ^ b_d(cc)) & b_d(bina[j])).replace('0b', '')
			count = 0
			for l in e:
				if l == '1':
					count += 1
			b[i].append([j, count])
store = [[0] * 10 for i in range(n + 1)]
dp = [[-1] * (c + 1) for i in range(n + 1)]
dp[n][c] = c
d = []
for i in range(n, 0, -1):
	d = b[i - 1]
	for j in range(c + 1):
		if dp[i][j] >= 0:
			for k in d:
				if k[1] <= j:
					dp[i - 1][j - k[1]] = max(k[0], dp[i - 1][j - k[1]])
					if k[0] >= dp[i - 1][j - k[1]]:
						store[i - 1][k[0]] = k[1]
if dp[0][0] == -1:
	print(-1)
else:
	i = 0
	ans = ''
	j = 0
	while i < n:
		ans += str(dp[i][j])
		j += store[i][dp[i][j]]
		i += 1
	print(ans)


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='')


def main():
	(n, k) = map(int, input().split())
	c = [int(input(), 2) for _ in range(n)]
	num = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
	num = [(int(s, 2), i) for (i, s) in enumerate(num)]
	d = [[] for _ in range(128)]
	for i in range(128):
		for (s, j) in reversed(num):
			if i & s == i:
				x = bin(i ^ s).count('1')
				d[i].append((x, str(j)))
	dp = [[None] * (k + 1) for _ in range(n + 1)]
	dp[n][0] = ''
	for i in range(n - 1, -1, -1):
		t = dp[i + 1]
		u = dp[i]
		for j in range(k + 1):
			for (x, ch) in d[c[i]]:
				if j >= x and t[j - x] is not None:
					u[j] = (x, ch)
					break
	if dp[0][k] is None:
		print(-1)
		return
	x = k
	ans = []
	for i in range(n):
		if dp[i][k] is not None:
			ans.append(dp[i][k][1])
			k -= dp[i][k][0]
	print(''.join(ans))
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='')


import sys
from itertools import accumulate

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

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

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

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7

def popcount(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	i = i + (i >> 4) & 252645135
	i = i + (i >> 8)
	i = i + (i >> 16)
	return i & 63
B = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
for i in range(10):
	B[i] = int(B[i], 2)
(N, K) = MAP()
A = [int(input(), 2) for i in range(N)][::-1]
dp = list2d(N + 1, K + 1, 0)
dp[0][0] = 1
for (i, a) in enumerate(A):
	for j in range(K + 1):
		if not dp[i][j]:
			continue
		for (x, b) in enumerate(B):
			ab = a & b
			cnt = popcount(b ^ ab)
			ng = 1 if a ^ ab > 0 else 0
			if not ng and j + cnt <= K:
				dp[i + 1][j + cnt] |= 1 << x
if not dp[N][K]:
	print(-1)
	exit()
cnt = K
ans = []
for i in range(N, 0, -1):
	for j in range(9, -1, -1):
		if dp[i][cnt] >> j & 1:
			num = j
			break
	ans.append(str(num))
	need = popcount(B[num]) - popcount(A[i - 1])
	cnt -= need
print(''.join(ans))


from sys import stdin, stdout

class Param:
	inf = int(10000000000.0)
code = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
(n, k) = list(map(int, stdin.readline().split()))
s_list = []
for i in range(n):
	s_list.append(stdin.readline())
pass
bit_list = [int(s, 2) for s in s_list]
move_rec = [[0] * 10 for i in range(1 << 7)]

def move(bit, value):
	x = code[value]
	ans = 0
	for i in range(7):
		if x[i] == '1' and (not bit & 1 << 6 - i):
			ans += 1
		elif x[i] == '1' and bit & 1 << 6 - i:
			pass
		elif x[i] == '0' and (not bit & 1 << 6 - i):
			pass
		elif x[i] == '0' and bit & 1 << 6 - i:
			ans = Param.inf
			break
	pass
	move_rec[bit][value] = ans
for bit in bit_list:
	for value in range(10):
		move(bit, value)
dp = [[False] * (k + 1) for i in range(n + 1)]
dp[0][0] = True
for pos in range(n):
	for i in range(k + 1):
		if dp[pos][i]:
			for value in range(10):
				need = move_rec[bit_list[-(pos + 1)]][value]
				if need + i <= k:
					dp[pos + 1][need + i] = True
			pass
	pass
pass
ans = ''
if dp[n][k] == False:
	ans = '-1'
else:
	rest = k
	for pos in reversed(range(1, n + 1)):
		for value in reversed(range(0, 10)):
			need = move_rec[bit_list[-pos]][value]
			if rest - need >= 0 and dp[pos - 1][rest - need]:
				ans += str(value)
				rest = rest - need
				break
		pass
	pass
pass
print(ans)


import sys
input = sys.stdin.readline

def prog():
	digits = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
	(n, k) = map(int, input().split())
	dp = [[False for i in range(k + 1)] for i in range(n + 1)]
	dp[0][0] = True
	changes = [[None for i in range(10)] for i in range(n + 1)]
	nums = [input().strip() for i in range(n)]
	nums.reverse()
	for i in range(n):
		num = nums[i]
		for digit1 in range(10):
			digit = digits[digit1]
			change = 0
			fail = False
			for j in range(7):
				if num[j] == '1' and digit[j] == '0':
					fail = True
					break
				elif num[j] == '0' and digit[j] == '1':
					change += 1
			if not fail:
				changes[i + 1][digit1] = change
				for a in range(k + 1):
					if dp[i][a] == True and a + change <= k:
						dp[i + 1][a + change] = True
	if dp[n][k] == False:
		print(-1)
	else:
		ans = []
		for i in range(n, 0, -1):
			for j in range(9, -1, -1):
				val = changes[i][j]
				if val is not None and k - val >= 0 and (dp[i - 1][k - val] == True):
					ans.append(str(j))
					k -= val
					break
		print(''.join(ans))
prog()


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 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])


def popcount(x):
	x -= x >> 1 & 85
	x = (x & 51) + (x >> 2 & 51)
	x = x + (x >> 4) & 15
	return x & 15
D = [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
(N, K) = map(int, input().split())
X = [int(input(), 2) for _ in range(N)][::-1]
S = [1]
for (i, x) in enumerate(X):
	pre = S[-1]
	s = 0
	for (j, d) in enumerate(D):
		if d | x == d:
			a = popcount(d) - popcount(x)
			s |= pre << a
	S.append(s)
if S[-1] >> K & 1 == 0:
	print(-1)
	exit()
ANS = []
for i in range(N, 0, -1):
	x = X[i - 1]
	for j in range(9, -1, -1):
		d = D[j]
		if d | x == d:
			a = popcount(d) - popcount(x)
			if K >= a and S[i - 1] >> K - a & 1:
				ANS.append(j)
				K -= a
				break
print(''.join(map(str, ANS)))


digits = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
(n, k) = map(int, input().split())
dist = [[0] * 10 for i in range(n)]
strings = []
for i in range(n):
	strings.append(input())
for i in range(n):
	for j in range(10):
		for z in range(7):
			if strings[i][z] == '0' and digits[j][z] == '1':
				dist[i][j] += 1
			if strings[i][z] == '1' and digits[j][z] == '0':
				dist[i][j] = -1
				break
dp = [[0] * (k + 1) for i 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] > 0:
			for d in range(10):
				if dist[i - 1][d] != -1 and j + dist[i - 1][d] <= k:
					dp[i - 1][j + dist[i - 1][d]] = 1
if dp[0][k] == 0:
	print(-1)
	exit()
for i in range(n):
	now = -1
	for d in range(9, -1, -1):
		if dist[i][d] != -1 and k >= dist[i][d] and dp[i + 1][k - dist[i][d]]:
			now = d
			k -= dist[i][d]
			break
	print(now, end='')
print()


import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
from functools import lru_cache
NUMS_REP = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']

def diff(s, t):
	d = 0
	for i in range(7):
		sone = s & 1 << i > 0
		tone = t & 1 << i > 0
		if sone and (not tone):
			return -1
		if not sone and tone:
			d += 1
	return d

def str2int(s):
	v = 0
	for c in s:
		v <<= 1
		v |= 1 if c == '1' else 0
	return v
NUMS = [str2int(s) for s in NUMS_REP]
dist = [[0 for _ in range(10)] for _ in range(128)]
for s in range(128):
	for t in range(10):
		dist[s][t] = diff(s, NUMS[t])

def solve(N, K, A):
	A = [0] + A[::-1]
	dp = [[False for _ in range(K + 1)] for _ in range(N + 1)]
	dp[0][0] = True
	for i in range(1, N + 1):
		for k in range(min(K, 7 * i) + 1):
			for t in range(10):
				d = dist[A[i]][t]
				if 0 <= d <= k and dp[i - 1][k - d]:
					dp[i][k] = True
					break
	if not dp[N][K]:
		return -1
	ans = []
	(x, y) = (N, K)
	while x > 0:
		s = A[x]
		for t in range(9, -1, -1):
			d = dist[s][t]
			if 0 <= d <= y and dp[x - 1][y - d]:
				ans.append(t)
				x -= 1
				y -= d
				break
	return ''.join(map(str, ans))
(N, K) = map(int, input().split())
A = []
for i in range(N):
	A.append(str2int(input()))
print(solve(N, K, A))


import sys
from collections import defaultdict
D = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
SIGN = [bin(i)[2:].zfill(7) for i in range(1 << 7)]
RESTORE = {SIGN[i]: i for i in range(1 << 7)}
COST = [[-1] * 10 for i in range(1 << 7)]
for i in range(1 << 7):
	for j in range(10):
		si = SIGN[i]
		sj = D[j]
		cost = 0
		possible = True
		for k in range(7):
			if si[k] == '1' and sj[k] == '0':
				COST[i][j] = -1
				possible = False
				break
			elif si[k] == '0' and sj[k] == '1':
				cost += 1
		if possible:
			COST[i][j] = cost

def input():
	return sys.stdin.readline().rstrip()
V = [[-1] * 10 for i in range(1 << 7)]
for digit in range(1 << 7):
	for n_digit in range(10):
		c = COST[digit][n_digit]
		if c >= 0:
			V[digit][c] = max(V[digit][c], n_digit)

def slv():
	(n, K) = map(int, input().split())
	S = [input() for i in range(n)]
	S.reverse()
	DP = [[-1] * (K + 1) for i in range(n + 1)]
	LOG = [[-1] * (K + 1) for i in range(n + 1)]
	DP[0][0] = 0
	for i in range(1, n + 1):
		s = S[i - 1]
		rs = RESTORE[s]
		for cost in range(8):
			for k in range(cost, min(K, 8 * i) + 1):
				if DP[i - 1][k - cost] >= 0 & V[rs][cost] >= 0:
					if DP[i][k] < V[rs][cost]:
						DP[i][k] = V[rs][cost]
						LOG[i][k] = (V[rs][cost], k - cost)
	if DP[n][K] < 0:
		print(-1)
		return
	else:
		res = []
		idx = n
		cost = K
		while idx >= 1:
			(digit, next_cost) = LOG[idx][cost]
			res.append(str(digit))
			idx -= 1
			cost = next_cost
		ans = ''.join(res)
		print(ans)
		return
slv()


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()


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())


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
r = sys.stdin.readline
(n, k) = map(int, r().split())
seg0to9 = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
ck = [[-1] * 10 for _ in range(n)]

def bit_count(n):
	k = 0
	cnt = 0
	while n >= 1 << k:
		if n & 1 << k != 0:
			cnt += 1
		k += 1
	return cnt
for i in range(n):
	cur = r().strip()
	for (j, seg) in enumerate(seg0to9):
		if int(cur, 2) | int(seg, 2) == int(seg, 2):
			ck[i][j] = bit_count(int(cur, 2) ^ int(seg, 2))
dp = [[False] * (k + 1) for _ in range(n + 1)]
dp[n][0] = True
for i in range(n, 0, -1):
	for j in range(k + 1):
		if dp[i][j]:
			for d in range(10):
				if ck[i - 1][d] != -1 and ck[i - 1][d] + j <= k:
					dp[i - 1][j + ck[i - 1][d]] = True
if not dp[0][k]:
	print('-1')
	exit(0)
for i in range(n):
	cur = -1
	for d in range(9, -1, -1):
		if ck[i][d] != -1 and ck[i][d] <= k and dp[i + 1][k - ck[i][d]]:
			cur = d
			k -= ck[i][d]
			break
	print(cur, end='')


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
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')

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
(n, k) = list(map(int, input().split()))
numbers = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
distance = [[0] * 10 for i in range(n)]
for i in range(n):
	s = str(input())
	for j in range(10):
		for l in range(7):
			if s[l] == '0' and numbers[j][l] == '1':
				distance[i][j] += 1
			elif s[l] == '1' and numbers[j][l] == '0':
				distance[i][j] = -1
				break
dp = [[0] * (k + 1) for i 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 l in range(10):
				if distance[i - 1][l] != -1 and j + distance[i - 1][l] <= k:
					dp[i - 1][j + distance[i - 1][l]] = 1
if dp[0][k] == 0:
	print(-1)
else:
	ans = ''
	for i in range(n):
		temp = -1
		for j in range(9, -1, -1):
			if distance[i][j] != -1 and k >= distance[i][j] and (dp[i + 1][k - distance[i][j]] == 1):
				temp = j
				k -= distance[i][j]
				break
		ans += str(temp)
	print(ans)


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 os
import sys
from io import BytesIO, IOBase
import threading
from math import floor, ceil
from bisect import bisect_right
from collections import Counter
from math import gcd

def bit_1(x):
	assert x >= 0
	return bin(x)[2:].count('1')
mod = 10 ** 9 + 7
di = {'1110111': 0, '0010010': 1, '1011101': 2, '1011011': 3, '0111010': 4, '1101011': 5, '1101111': 6, '1010010': 7, '1111111': 8, '1111011': 9}

def main():
	(n, k) = map(int, input().split())
	s = [0] * n
	for i in range(n):
		s[i] = input()
	d2 = dict(zip(di.values(), di.keys()))
	dp = [[False] * (k + 1) for i in range(n + 1)]
	dp[n][0] = True
	trans = [[2002] * 10 for i in range(2 ** 7)]
	for i in range(2 ** 7):
		for j in range(10):
			el2 = int(d2[j], 2)
			if ~el2 & i == 0:
				trans[i][j] = bit_1(el2 & ~i)
	for i in range(n - 1, -1, -1):
		el = int(s[i], 2)
		for j in range(0, k + 1):
			for dig in range(10):
				j_ = j - trans[el][dig]
				if j_ >= 0 and dp[i + 1][j_]:
					dp[i][j] = True
					break
	if dp[0][k]:
		dig = [-1] * n
		for i in range(n):
			el = int(s[i], 2)
			op = -1
			for d in range(10):
				if k - trans[el][d] >= 0 and dp[i + 1][k - trans[el][d]]:
					op = d
			dig[i] = op
			k -= trans[el][op]
		print(''.join([str(i) for i in dig]))
	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()


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))


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
			self.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 collections import defaultdict as dd, deque as dq
import math, string

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
MOD = 998244353

def solve():
	real_digs = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
	X = [int(d, 2) for d in real_digs]
	(N, K) = getInts()
	score_digs = []
	for n in range(N):
		s = getStr()
		score_digs.append(s)
	D = [int(d, 2) for d in score_digs]
	dp = [[] for i in range(N)]
	for i in range(N):
		for j in range(10):
			if D[i] | X[j] == X[j]:
				Y = D[i] ^ X[j]
				dp[i].append(sum([int(s) for s in bin(Y)[2:]]))
			else:
				dp[i].append(-1)
	dp2 = [[False for k in range(K + 1)] for n in range(N + 1)]
	dp2[N][0] = True
	for i in range(N, 0, -1):
		for j in range(K + 1):
			if dp2[i][j]:
				for d in range(10):
					if dp[i - 1][d] >= 0 and j + dp[i - 1][d] <= K:
						dp2[i - 1][j + dp[i - 1][d]] = True
	if not dp2[0][K]:
		return -1
	ans = ''
	for i in range(N):
		curr = -1
		for d in range(9, -1, -1):
			if dp[i][d] != -1 and dp[i][d] <= K and dp2[i + 1][K - dp[i][d]]:
				curr = d
				K -= dp[i][d]
				break
		ans += str(curr)
	return ans
print(solve())


def diff(a, b):
	c = 0
	for i in range(7):
		if a[i] == '0' and b[i] == '1':
			c = 5000
		elif a[i] == '1' and b[i] == '0':
			c += 1
	return c

def get(a, b):
	c = 0
	for i in range(7):
		if a[i] == '0' and b[i] == '1':
			c = 5000
		elif a[i] == '1' and b[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)
cost = []
for i in range(0, len(L)):
	s = L[i]
	tt = []
	for j in range(9, -1, -1):
		d = diff(pre[j], s)
		tt.append((d, j))
	tt.sort()
	cost.append(tt[0][0])
sumu = 0
for i in range(0, len(cost)):
	sumu += cost[i]
sumu2 = 0
for i in range(0, len(L)):
	for j in range(0, len(L[i])):
		if L[i][j] == '0':
			sumu2 += 1
if sumu > k or k > sumu2:
	print(-1)
else:
	ans = []
	rem = k - sumu
	for i in range(0, len(L)):
		rem += cost[i]
		for j in range(9, -1, -1):
			d = get(pre[j], L[i])
			if d <= rem:
				rem -= d
				ans.append(str(j))
				break
	for i in range(len(ans) - 1, -1, -1):
		if rem <= 0:
			break
		st = pre[int(ans[i])]
		init = get(st, L[i])
		rem += init
		temp = init
		fnl = int(ans[i])
		for j in range(int(ans[i]) - 1, -1, -1):
			d = get(pre[j], L[i])
			if d > temp and d <= rem:
				temp = d
				fnl = j
		rem -= temp
		ans[i] = str(fnl)
	if rem > 0:
		print(-1)
	else:
		ans = ''.join(ans)
		print(ans)


def comp(a, b):
	b = d[b]
	count = 0
	for i in range(7):
		if a[i] == '1' and b[i] == '0':
			return -1
		elif a[i] == '0' and b[i] == '1':
			count += 1
	return count
(n, count) = map(int, input().split())
l = []
d = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
num = set(d)
for i in range(n):
	l.append(input())
dp = [[-1 for i in range(9)] for j in range(n)]
for i in range(n):
	for j in range(1, 8):
		for k in range(10):
			if comp(l[i], k) == j:
				dp[i][j] = k
for i in range(n):
	if l[i] in num:
		dp[i][0] = d.index(l[i])
minn = 0
number = [-1] * n
value = [0] * n
for i in range(n):
	for j in range(8):
		if dp[i][j] != -1:
			minn += j
			value[i] = j
			number[i] = dp[i][j]
			break
if count < minn:
	print(-1)
	exit(0)
count -= minn
if count != 0:
	for i in range(n):
		m = max(dp[i][value[i]:min(8, value[i] + count + 1)])
		ind = dp[i].index(m)
		number[i] = m
		count -= ind - value[i]
		value[i] = ind
number1 = []
number2 = []
value1 = []
value2 = []
(count1, count2) = (count, count)
for i in range(n):
	number2.append(number[i])
	number1.append(number[i])
	value1.append(value[i])
	value2.append(value[i])
if count1 != 0:
	for i in range(n - 1, -1, -1):
		for j in range(7, value1[i], -1):
			if count1 >= j - value1[i] and dp[i][j] != -1:
				number1[i] = dp[i][j]
				value1[i] = j
				count1 -= 1
				break
		if count1 == 0:
			break
if count2 != 0:
	if count2 == 1:
		for i in range(n - 1, -1, -1):
			if count2 == 1:
				for j in range(value2[i] + 2, 8):
					if dp[i][j] != -1:
						number2[i] = dp[i][j]
						value2[i] = j
						count2 -= 2
						break
			elif dp[i][value2[i] - 1] != -1:
				number2[i] = dp[i][value2[i] - 1]
				value2[i] -= 1
				count2 += 1
				break
if count1 != 0 and count2 != 0:
	print(-1)
	exit()
elif count1 != 0 or count2 != 0:
	if count1 == 0:
		print(''.join(map(str, number1)))
	else:
		print(''.join(map(str, number2)))
else:
	ans1 = ''.join(map(str, number1))
	ans2 = ''.join(map(str, number2))
	if ans1 > ans2:
		print(ans1)
	else:
		print(ans2)


import sys
readline = sys.stdin.readline
inf = 10 ** 18
digits = [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
popcount = [[bin(x - y).count('1') if x & y == x else inf for y in range(2 ** 7)] for x in range(2 ** 7)]
(N, K) = map(int, input().split())
a = [int(readline().strip(), 2) for _ in range(N)]
dp = [[0] * (K + 1) for _ in range(N + 1)]
dp[0][K] = 1
for (i, x) in zip(range(N), reversed(a)):
	for j in range(K, -1, -1):
		if not dp[i][j]:
			continue
		for y in digits:
			if popcount[x][y] <= j:
				dp[i + 1][j - popcount[x][y]] = 1
if not dp[N][0]:
	print(-1)
	exit()
j = 0
ans = []
for (i, x) in zip(range(N, 0, -1), a):
	for (k, y) in zip(range(9, -1, -1), reversed(digits)):
		if j + popcount[x][y] <= K and dp[i - 1][j + popcount[x][y]]:
			ans.append(k)
			j += popcount[x][y]
			break
print(*ans, sep='')


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()


import sys
from math import ceil
from itertools import islice, cycle
from collections import Counter, defaultdict
stdin = sys.stdin
real_numbers = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']

def dist(x, y):
	d = 0
	for (b1, b2) in zip(x, y):
		if b1 == '0' and b2 == '1':
			d += 1
		elif b1 != b2:
			return -1
	return d
all_numbers = [bin(i)[2:] for i in range(128)]
all_numbers = ['0' * (7 - len(x)) + x for x in all_numbers]
possible_moves = defaultdict(dict)
for fr_num in all_numbers:
	for (dec_to_num, to_num) in enumerate(real_numbers):
		d = dist(fr_num, to_num)
		if d > -1:
			if d in possible_moves[fr_num]:
				if dec_to_num > possible_moves[fr_num][d]:
					possible_moves[fr_num][d] = dec_to_num
			else:
				possible_moves[fr_num][d] = dec_to_num
(n, k) = stdin.readline().strip().split()
n = int(n)
k = int(k)
dp = [[(-1, None) for __ in range(k + 1)] for _ in range(n)]
numbers = islice(stdin, n)
numbers = list(numbers)[::-1]
numbers = [num.strip() for num in numbers]
k_for_next = set([k])
for (n_idx, number) in enumerate(numbers):
	d2num = possible_moves[number]
	last_col = k_for_next
	k_for_next = set()
	for last_k in last_col:
		for (dk, to_num) in d2num.items():
			new_k = last_k - dk
			if new_k < 0:
				continue
			k_for_next.add(new_k)
			if to_num > dp[n_idx][new_k][0]:
				dp[n_idx][new_k] = (to_num, last_k)
	last_col = k_for_next
	if not last_col:
		break
if dp[n - 1][0][0] == -1:
	print(-1)
else:
	b = 0
	for n in range(n - 1, -1, -1):
		(a, b) = dp[n][b]
		print(a, end='')


digits = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
(n, k) = map(int, input().split())
cost = [[0] * 10 for _ in range(n)]
for i in range(n):
	x = input()
	for j in range(10):
		for d in range(7):
			if x[d] == '1' and digits[j][d] == '0':
				cost[i][j] = -1
				break
			if x[d] == '0' and digits[j][d] == '1':
				cost[i][j] += 1
dp = [[False] * (k + 1) for _ in range(n + 1)]
dp[n][0] = True
for i in range(n, 0, -1):
	for j in range(0, k + 1):
		if dp[i][j]:
			for d in range(10):
				if cost[i - 1][d] != -1 and cost[i - 1][d] + j <= k:
					dp[i - 1][cost[i - 1][d] + j] = True
if dp[0][k] == 0:
	print(-1)
else:
	for i in range(n):
		now = -1
		for d in range(9, -1, -1):
			if cost[i][d] != -1 and cost[i][d] <= k and dp[i + 1][k - cost[i][d]]:
				now = d
				k -= cost[i][d]
				break
		print(now, end='')
	print()


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()


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()


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

def linp():
	x = [int(i) for i in input().split()]
	return x
nums = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
(n, k) = linp()
d = []
for i in range(n):
	d.append(input())
dp = [[0] * (k + 1) for i in range(n + 1)]
can = [[1] * 10 for i in range(n)]
for q in range(n):
	for i in range(10):
		j = 0
		cnt = 0
		while j < 7 and can[q][i] >= 0:
			if d[q][j] == '1' and nums[i][j] == '0':
				can[q][i] = -1
			elif d[q][j] == '0' and nums[i][j] == '1':
				cnt += 1
			j += 1
		if can[q][i] >= 0:
			can[q][i] = cnt
dp[n][0] = 1
for i in range(n, 0, -1):
	for j in range(k + 1):
		if dp[i][j]:
			for w in range(10):
				if can[i - 1][w] != -1 and j + can[i - 1][w] <= k:
					dp[i - 1][j + can[i - 1][w]] = 1
ans = ''
if dp[0][k] == 0:
	ans = -1
else:
	for i in range(n):
		now = -1
		for w in range(9, -1, -1):
			if can[i][w] != -1 and k >= can[i][w] and dp[i + 1][k - can[i][w]]:
				now = w
				k -= can[i][w]
				break
		if now >= 0:
			ans += str(now)
		else:
			ans = -1
			break
print(ans)


import sys
input = sys.stdin.readline
T = [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
(N, K) = map(int, input().split())
dp = [[0] * (K + 1) for _ in range(N + 1)]
dp[N][0] = 1
X = []
for _ in range(N):
	x = int(input().strip(), 2)
	X.append(x)
for i in range(N - 1, -1, -1):
	x = X[i]
	for t in T:
		rt = -1 if t | x != t else bin(t ^ x).count('1')
		if rt < 0:
			continue
		for k in range(K, -1, -1):
			if k - rt < 0:
				continue
			dp[i][k] = dp[i + 1][k - rt] | dp[i][k]
if dp[0][K] == 0:
	print(-1)
	sys.exit()
R = ''
for i in range(N):
	x = X[i]
	for j in range(9, -1, -1):
		t = T[j]
		rt = -1 if t | x != t else bin(t ^ x).count('1')
		if rt < 0 or K - rt < 0:
			continue
		if dp[i + 1][K - rt]:
			K -= rt
			R += str(j)
			break
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())


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


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()


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, 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
input = sys.stdin.readline

def main():
	(n, k) = map(int, input().split())
	sb = [int(input(), 2) for _ in range(n)]
	digit = [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
	cnt = [[k + 1] * 10 for _ in range(n)]
	for i in range(n):
		for d in range(10):
			if digit[d] | sb[i] == digit[d]:
				c = 0
				x = digit[d] ^ sb[i]
				while x > 0:
					if x & 1:
						c += 1
					x >>= 1
				cnt[i][d] = c
	dp = [[False] * (k + 1) for _ in range(n + 1)]
	dp[-1][0] = True
	for i in range(n)[::-1]:
		for j in range(k + 1):
			for (d, c) in enumerate(cnt[i]):
				if j - c >= 0:
					dp[i][j] |= dp[i + 1][j - c]
	if not dp[0][k]:
		print(-1)
		exit()
	ans = [''] * n
	for i in range(n):
		for (d, c) in list(enumerate(cnt[i]))[::-1]:
			if k - c >= 0 and dp[i + 1][k - c]:
				ans[i] = str(d)
				k -= c
				break
	print(''.join(ans))
main()


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

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

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

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

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

def SI():
	return sys.stdin.readline()[:-1]

def main():
	seg = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
	seg = [int(s, 2) for s in seg]
	(n, k) = MI()
	ss = [SI() for _ in range(n)]
	dp = [1] * (n + 1)
	mask = (1 << k + 1) - 1
	for i in range(n - 1, -1, -1):
		a = int(ss[i], 2)
		pre = dp[i + 1]
		value = 0
		for (d, b) in enumerate(seg):
			if a & b != a:
				continue
			delta = bin(b ^ a).count('1')
			value |= pre << delta
		dp[i] = value & mask
	if dp[0] >> k & 1 == 0:
		print(-1)
		exit()
	ans = []
	for i in range(n):
		a = int(ss[i], 2)
		for d in range(9, -1, -1):
			b = seg[d]
			if a & b != a:
				continue
			delta = bin(b ^ a).count('1')
			if delta > k:
				continue
			if dp[i + 1] >> k - delta & 1:
				ans.append(d)
				k -= delta
				break
	print(*ans, sep='')
main()


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)


digits = ['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
counts = [s.count('1') for s in digits]
bits = [int(s, 2) for s in digits]
(n, k) = map(int, input().split())
poss = [[] for i in range(n)]
for i in range(n):
	s = input()
	count = s.count('1')
	bit = int(s, 2)
	for d in range(9, -1, -1):
		if bit & bits[d] == bit:
			poss[i].append((d, counts[d] - count))
dp = [[False] * (k + 1) for i in range(n + 1)]
dp[0][0] = True
for i in range(n):
	allowed = poss[n - i - 1]
	for j in range(k + 1):
		if dp[i][j]:
			for (_, c) in allowed:
				if j + c <= k:
					dp[i + 1][j + c] = True
out = []
if dp[n][k]:
	curr = k
	for i in range(n):
		for (v, c) in poss[i]:
			if curr - c >= 0 and dp[n - i - 1][curr - c]:
				out.append(v)
				curr -= c
				break
		assert dp[n - i - 1][curr]
	print(''.join(map(str, out)))
else:
	print(-1)


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()


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()


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)


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)


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)