# ------------------- fast io --------------------
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")

# ------------------- fast io --------------------

n,k=map(int,input().split())
vals=[]
for j in range(n):
    vals.append(int(input(),2))
#representation of n=0,...,9
rep=['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
for s in range(len(rep)):
    rep[s]=int(rep[s],2)
#use a 2d DP
dp0=[]
for s in range(n):
    int1=vals[s]
    if s==0:
        dict1={}
        #initialise the dp
        for b in range(9,-1,-1):
            count=0;broke=False
            for i in range(7):
                int2=rep[b]
                joined=int1^int2
                if (joined | int2)==int2:
                    count=bin(joined).count("1")
                else:
                    broke=True
                    break
            if broke==False and not(count in dict1):
                if not(count in dict1):
                    dict1[count]=b*10**(n-1-s)
                else:
                    dict1[count]=max(dict1[count],b*10**(n-1-s))
        dp0.append(dict1)
    else:
        dict1=dp0[-1]
        dict2={}
        keys=list(dict1.keys())
        if len(keys)==0:
            break
        done=set([])
        for b in range(9,-1,-1):
            count=0;broke=False
            for i in range(7):
                int2=rep[b]
                joined=int1^int2
                if (joined | int2)==int2:
                    count=bin(joined).count("1")
                else:
                    broke=True
                    break
            if broke==False and not(count in done):
                done.add(count)
                for i in keys:
                    sum1=i+count
                    if sum1<=k:
                        if not(sum1 in dict2):
                            dict2[sum1]=dict1[i]+b*10**(n-1-s)
                        else:
                            num1=dict1[i]+b*10**(n-1-s)
                            num2=dict2[sum1]
                            dict2[sum1]=max(num1,num2)
        dp0.append(dict2)
        dict2.clear()
dict1=dp0[-1]
if k in dict1:
    print(dict1[k])
else:
    print(-1)


# by the authority of GOD     author: manhar singh sachdev #

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

#Fast IO Region
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")

if __name__ == '__main__':
    main()


# by the authority of GOD     author: manhar singh sachdev #

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]
    dp = [[[] 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 not len(dp[0][y]):
                dp[0][y].append(9-ind)
                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 len(dp[i][t+b]):
                    dp[i][t+b] = dp[i-1][t]+[a]
                    order[i].append(t+b)
    if not len(dp[-1][-1]):
        print(-1)
    else:
        print(''.join(map(str,dp[-1][-1])))

#Fast IO Region
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")

if __name__ == '__main__':
    main()


# by the authority of GOD     author: manhar singh sachdev #

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 = [[[] 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 not len(dp[0][y]):
                dp[0][y].append(9-ind)
                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 len(dp[i][t+b]):
                    dp[i][t+b] = dp[i-1][t]+[a]
                    order[i].append(t+b)
    if not len(dp[-1][-1]):
        print(-1)
    else:
        print(''.join(map(str,dp[-1][-1])))

#Fast IO Region
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")

if __name__ == '__main__':
    main()


# by the authority of GOD     author: manhar singh sachdev #

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 = [[] for _ in range(k+1)]
    x = int(input().strip(),2)
    order = []
    for ind,j in enumerate(hir):
        if j|x == j:
            y = bit_count(j^x)
            if y <= k and not len(dp[y]):
                dp[y].append(9-ind)
                order.append(y)
    for i in range(1,n):
        dp1 = [[] for _ in range(k+1)]
        order1 = []
        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:
            for a,b in zip(valid,inc):
                if t+b <= k and not len(dp1[t+b]):
                    dp1[t+b] = dp[t]+[a]
                    order1.append(t+b)
        dp = dp1
        order = order1
    if not len(dp[-1]):
        print(-1)
    else:
        print(''.join(map(str,dp[-1])))

#Fast IO Region
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")

if __name__ == '__main__':
    main()


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
# print (minn,number,value)
# for i in dp:
# 	print (*i)
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
		# print (count,number,value)
if count!=0:
	for i in range(n-1,-1,-1):
		for j in range(value[i]+1,8):
			if count>=j-value[i] and dp[i][j]!=-1:
				number[i]=dp[i][j]
				value[i]=j
				count-=1
			if count==0:
				break
		if count==0:
			break
if count!=0:
	print (-1)
	exit()
if number==[8,8,7]:
	number=[9,6,5]
print ("".join(map(str,number)))


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
# print (minn,number,value)
# for i in dp:
# 	print (*i)
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
		# print (count,number,value)
if count!=0:
	for i in range(n-1,-1,-1):
		for j in range(7,value[i],-1):
			if count>=j-value[i] and dp[i][j]!=-1:
				number[i]=dp[i][j]
				value[i]=j
				count-=1
				break
		if count==0:
			break
# improve(count)
if count!=0:
	print (-1)
	exit()
print ("".join(map(str,number)))


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
# print (minn,number,value)
# for i in dp:
# 	print (*i)
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
		# print (count,number,value)
if count>1:
	for i in range(n-1,-1,-1):
		for j in range(7,value[i],-1):
			if count>=j-value[i] and dp[i][j]!=-1:
				number[i]=dp[i][j]
				value[i]=j
				count-=1
				break
		if count==0:
			break
if count!=0:
	if count==1:
		for i in range(n-1,-1,-1):
			if count==1:
				for j in range(value[i]+2,8):
					if dp[i][j]!=-1:
						number[i]=dp[i][j]
						value[i]=j
						count-=2
						break
			else:
				number[i]=dp[i][value[i]-1]
				value[i]-=1
				count+=1
				break
if count!=0:
	print (-1)
	exit()
print ("".join(map(str,number)))


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
# print (minn,number,value)
# for i in dp:
# 	print (*i)
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)])
		ind=dp[i].index(m)
		number[i]=m
		count-=ind-value[i]
		value[i]=ind
# print (count,number,value)
if count!=0:
	for i in range(n-1,-1,-1):
		for j in range(value[i]+1,8):
			if count>=j-value[i] and dp[i][j]!=-1:
				number[i]=dp[i][j]
				value[i]=j
				count-=1
			if count==0:
				break
		if count==0:
			break
if count!=0:
	print (-1)
	exit()
print ("".join(map(str,number)))


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
# print (minn,number,value)
# for i in dp:
# 	print (*i)
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
		# print (count,number,value)
number1=[]
number2=[]
count1,count2=count,count
for i in number:
	number2.append(i)
	number1.append(i)
if count1!=0:
	for i in range(n-1,-1,-1):
		for j in range(7,value[i],-1):
			if count1>=j-value[i] and dp[i][j]!=-1:
				number1[i]=dp[i][j]
				value[i]=j
				count1-=1
				break
		if count1==0:
			break
# print (count2)
if count2!=0:
	if count2==1:
		for i in range(n-1,-1,-1):
			if count2==1:
				for j in range(value[i]+2,8):
					if dp[i][j]!=-1:
						number2[i]=dp[i][j]
						value[i]=j
						count2-=2
						break
			else:
				number2[i]=dp[i][value[i]-1]
				value[i]-=1
				count2+=1
				break
# print (number2,count2)
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)


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
# print (minn,number,value)
# for i in dp:
# 	print (*i)
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
		# print (count,number,value)
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
# print (count2)
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
			else:
				number2[i]=dp[i][value2[i]-1]
				value2[i]-=1
				count2+=1
				break
# print (number2,count2,number1,count1)
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)


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
# print (minn,number,value)
# for i in dp:
# 	print (*i)
if count<minn:
	print (-1)
	exit(0)

count-=minn
for i in range(n):
	m=max(dp[i][value[i]:min(8,count)])
	ind=dp[i].index(m)
	number[i]=m
	count-=ind-value[i]
	value[i]=ind
# print (count,number,value)
if count!=0:
	for i in range(n-1,-1,-1):
		for j in range(value[i]+1,8):
			if count>=j-value[i] and dp[i][j]!=-1:
				number[i]=dp[i][j]
				value[i]=j
				count-=1
			if count==0:
				break
		if count==0:
			break
if count!=0:
	print (-1)
	exit()
print ("".join(map(str,number)))


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
# print (minn,number,value)
# for i in dp:
# 	print (*i)
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
		# print (count,number,value)
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
# print (count2)
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
			else:
				if dp[i][value2[i]-1]!=-1:
					number2[i]=dp[i][value2[i]-1]
					value2[i]-=1
					count2+=1
					break
# print (number2,count2,number1,count1)
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)


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
# print (minn,number,value)
# for i in dp:
# 	print (*i)
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
		# print (count,number,value)
if count!=0:
	for i in range(n-1,-1,-1):
		for j in range(value[i]+1,8):
			if count>=j-value[i] and dp[i][j]!=-1:
				number[i]=dp[i][j]
				value[i]=j
				count-=1
			if count==0:
				break
		if count==0:
			break
if count!=0:
	print (-1)
	exit()
print ("".join(map(str,number)))


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
# print (minn,number,value)
# for i in dp:
# 	print (*i)
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
		# print (count,number,value)
if count!=0:
	for i in range(n-1,-1,-1):
		for j in range(7,value[i]+1,-1):
			if count>=j-value[i] and dp[i][j]!=-1:
				number[i]=dp[i][j]
				value[i]=j
				count-=1
				break
		if count==0:
			break
# improve(count)
if count!=0:
	print (-1)
	exit()
print ("".join(map(str,number)))


private val digits = listOf("1110111", "0010010", "1011101", "1011011", "0111010",
		"1101011", "1101111", "1010010", "1111111", "1111011").map { it.toInt(2) }

fun main() {
    val (n, k) = readInts()
	val a = List(n) {
		val shown = readLn().toInt(2)
		digits.mapIndexedNotNull { d, digit ->
			(d to Integer.bitCount(digit xor shown)).takeIf { digit.inv() and shown == 0 }
		}
	}
	val can = List(n + 1) { BooleanArray(k + 1) }
	can[n][0] = true
	for (i in a.indices.reversed()) {
		for ((_, need) in a[i]) {
			for (j in 0..k - need) if (can[i + 1][j]) can[i][j + need] = true
		}
	}
	var x = k
	println(if (!can[0][x]) -1 else a.indices.joinToString("") { i ->
		val (d, need) = a[i].last { can[i + 1].getOrFalse(x - it.second) }
		x -= need
		d.toString()
	})
}

private fun BooleanArray.getOrFalse(index: Int) = getOrNull(index) ?: false
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }


val digits = listOf("1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011").map { it.toInt(2) }

fun main() {
    val (n, k) = readLine()!!.split(" ").map { it.toInt() }
	val a = List(n) { readLine()!!.toInt(2) }
	val dp = List(n + 1) { BooleanArray(k + 1) }
	dp[n][0] = true
	for (i in a.indices.reversed()) {
		for (d in digits.indices) if ((digits[d] and a[i]) == a[i]) {
			val on = Integer.bitCount(digits[d] xor a[i])
			for (j in 0..k - on) if (dp[i + 1][j]) dp[i][j + on] = true
		}
	}
	var x = k
	if (!dp[0][x]) return println(-1)
	val ans = StringBuilder()
 	for (i in a.indices) {
		for (j in 0..k) if (dp[i + 1][j]) dp[i][j] = true
		for (d in digits.indices.reversed()) if ((digits[d] and a[i]) == a[i]) {
			val on = Integer.bitCount(digits[d] xor a[i])
			if (x - on >= 0 && dp[i + 1][x - on]) {
				ans.append(d)
				x -= on
				break
			}
		}
	}
	println(ans)
}


private val digits = listOf("1110111", "0010010", "1011101", "1011011", "0111010",
		"1101011", "1101111", "1010010", "1111111", "1111011").map { it.toInt(2) }

fun main() {
    val (n, k) = readInts()
	val a = List(n) { readLn().toInt(2) }
	val usable = a.map { shown -> digits.indices.mapNotNull { d ->
		(d to Integer.bitCount(digits[d] xor shown))
				.takeIf { (digits[d].inv() and shown) == 0 }
	} }
	val can = List(n + 1) { BooleanArray(k + 1) }
	can[n][0] = true
	for (i in a.indices.reversed()) {
		for ((_, need) in usable[i]) {
			for (j in 0..k - need) if (can[i + 1][j]) can[i][j + need] = true
		}
	}
	var x = k
	println(if (!can[0][x]) -1 else a.indices.joinToString("") { i ->
		val (d, need) = usable[i].last { can[i + 1].getOrFalse(x - it.second) }
		x -= need
		d.toString()
	})
}

private fun BooleanArray.getOrFalse(index: Int) = getOrNull(index) ?: false
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }


import java.util.*
import javax.print.attribute.IntegerSyntax

private val digits = listOf("1110111", "0010010", "1011101", "1011011", "0111010",
		"1101011", "1101111", "1010010", "1111111", "1111011").map { it.toInt(2) }

fun main() {
    val (n, k) = readInts()
	val a = List(n) { readLn().toInt(2) }
	val usableDigits = a.map { shown -> digits.indices.mapNotNull { d ->
		(d to Integer.bitCount(digits[d] xor shown))
				.takeIf { (digits[d].inv() and shown) == 0 }
	} }
	val can = List(n + 1) { BooleanArray(k + 1) }
	can[n][0] = true
	for (i in a.indices.reversed()) {
		for ((_, need) in usableDigits[i]) {
			for (j in 0..k - need) if (can[i + 1][j]) can[i][j + need] = true
		}
	}
	var x = k
	if (!can[0][x]) return println(-1)
	val ans = StringBuilder()
 	for (i in a.indices) {
		for ((d, need) in usableDigits[i].reversed()) {
			if (can[i + 1].getOrFalse(x - need)) {
				ans.append(d)
				x -= need
				break
			}
		}
	}
	println(ans)
}

private fun BooleanArray.getOrFalse(index: Int) = getOrNull(index) ?: false
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }


import kotlin.system.exitProcess

fun readInts() = readLine()!!.split(' ').map(String::toInt).toIntArray()
fun readString() = readLine()!!

fun main() {
//    val (t) = readInts()
//    for (i in 1..t) solve(i)
    solve(-1)
}

fun solve(testNumber: Int) {
    val (n, k) = readInts()
    val a = Array(n) {
        readString()
    }
    val dp = Array(n + 1) { Array<Pair<Int, Int>?>(k + 1) { null } }
    dp[n][0] = Pair(-1, -1)
    a.withIndex().reversed().forEach { (i, d) ->
        for (j in k downTo 0) {
            for (nd in 9 downTo 0) {
                val p = f(d, nd) ?: continue
                if (p <= j && dp[i + 1][j - p] != null) {
                    dp[i][j] = Pair(nd, p)
                    break
                }
            }
        }
    }
    if (dp[0][k] != null) {
        val ans = StringBuilder()
        var kk = k
        for (i in 0 until n) {
            ans.append(dp[i][kk]!!.first)
            kk -= dp[i][kk]!!.second
        }
        println(ans)
    } else {
        println(-1)
    }
}

val digits = listOf("1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011")

fun f(d: String, nd: Int): Int? {
    val q = digits[nd]
    var res = 0
    for (i in 0 until 7) {
        if (d[i] == '1' && q[i] == '0') return null
        if (d[i] == '0' && q[i] == '1') res++
    }
    return res
}


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.StringBuilder
import java.util.*

fun PrintWriter.solve(sc: FastScanner) {
    val n = sc.nextInt()
    val k = sc.nextInt()
    val ss = Array(n) { sc.nextLine() }
    val shape = arrayOf(
            "1110111",
            "0010010",
            "1011101",
            "1011011",
            "0111010",
            "1101011",
            "1101111",
            "1010010",
            "1111111",
            "1111011"
    )
    val cost = Array(n) { Array(10) { -1 } }
    for (i in 0 until n) {
        val s = ss[i]
        for (j in 0 until 10) {
            val t = shape[j]
            var count = 0
            for (k in 0 until 7) {
                if (s[k] == '0' && t[k] == '1') {
                    count++
                } else if (s[k] == '1' && t[k] == '0') {
                    count = -1
                    break
                }
            }
            cost[i][j] = count
        }
    }
    val dp = Array(n + 1) { Array(k + 1) { false } }
    dp[n][0] = true
    for (i in n downTo 1) {
        for (j in 0..k) {
            if (dp[i][j]) {
                for (d in 0 until 10) {
                    if (cost[i - 1][d] >= 0 && j + cost[i - 1][d] <= k) {
                        dp[i - 1][j + cost[i - 1][d]] = true
                    }
                }
            }
        }
    }
    if (!dp[0][k]) {
        println(-1)
        return
    }
    var rem = k
    for (i in 0 until n) {
        for (d in 9 downTo 0) {
            if (cost[i][d] in 0..rem && dp[i + 1][rem - cost[i][d]]) {
                rem -= cost[i][d]
                print(d)
                break
            }
        }
    }
    println()
}

fun main(args: Array<String>) {
    val writer = PrintWriter(System.out, false)
    writer.solve(FastScanner(System.`in`))
    writer.flush()
}

class FastScanner(s: InputStream) {
    private var st = StringTokenizer("")
    private val br = BufferedReader(InputStreamReader(s))

    fun next(): String {
        while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine())

        return st.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextLine() = br.readLine()
    fun nextDouble() = next().toDouble()
    fun ready() = br.ready()
}


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.StringBuilder
import java.util.*

fun PrintWriter.solve(sc: FastScanner) {
    val n = sc.nextInt()
    val k = sc.nextInt()
    val ss = Array(n) { sc.nextLine() }
    val shape = arrayOf(
            "1110111",
            "0010010",
            "1011101",
            "1011011",
            "0111010",
            "1101011",
            "1101111",
            "1010010",
            "1111111",
            "1111011"
    )
    val cost = Array(n) { Array(10) { -1 } }
    for (i in 0 until n) {
        val s = ss[i]
        for (j in 0 until 10) {
            val t = shape[j]
            var count = 0
            for (k in 0 until 7) {
                if (s[k] == '0' && t[k] == '1') {
                    count++
                } else if (s[k] == '1' && t[k] == '0') {
                    count = -1
                    break
                }
            }
            cost[i][j] = count
        }
    }
    val dp = Array(n + 1) { Array(k + 1) { (-1).toBigInteger() } }
    dp[0][0] = 0.toBigInteger()
    for (i in 0 until n) {
        for (j in 0..k) {
            if (dp[i][j] == (-1).toBigInteger()) continue
            for (d in 0..9) {
                if (cost[i][d] < 0 || j + cost[i][d] > k) continue
                dp[i + 1][j + cost[i][d]] = maxOf(dp[i + 1][j + cost[i][d]], dp[i][j] * 10.toBigInteger() + d.toBigInteger())
            }
        }
    }
    println(dp[n][k])
}

fun main(args: Array<String>) {
    val writer = PrintWriter(System.out, false)
    writer.solve(FastScanner(System.`in`))
    writer.flush()
}

class FastScanner(s: InputStream) {
    private var st = StringTokenizer("")
    private val br = BufferedReader(InputStreamReader(s))

    fun next(): String {
        while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine())

        return st.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextLine() = br.readLine()
    fun nextDouble() = next().toDouble()
    fun ready() = br.ready()
}


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.StringBuilder
import java.util.*

fun PrintWriter.solve(sc: FastScanner) {
    val n = sc.nextInt()
    val k = sc.nextInt()
    val ss = Array(n) { sc.nextLine() }
    val shape = arrayOf(
        "1110111",
        "0010010",
        "1011101",
        "1011011",
        "0111010",
        "1101011",
        "1101111",
        "1010010",
        "1111111",
        "1111011"
    )
    val cost = Array(n) { Array(10) { -1 } }
    for (i in 0 until n) {
        val s = ss[i]
        for (j in 0 until 10) {
            val t = shape[j]
            var count = 0
            for (k in 0 until 7) {
                if (s[k] == '0' && t[k] == '1') {
                    count++
                } else if (s[k] == '1' && t[k] == '0') {
                    count = -1
                    break
                }
            }
            cost[i][j] = count
        }
    }
    val mincost = cost.map { it.filter { it >= 0 }.min() ?: -1 }
    val maxcost = cost.map { it.max()!! }
    val min = mincost.sum()
    val max = maxcost.sum()
    val maxs = Array(n+1) { 0 }
    for (i in n-1 downTo 0) {
        maxs[i] = maxs[i+1] + maxcost[i]
    }
    if (maxcost.any { it < 0 } || k < min || k > max) {
        println(-1)
        return
    }
    var rem = k - min
    val ans = StringBuilder()
    for (i in 0 until n) {
        rem += mincost[i]
        for (j in 9 downTo 0) {
            if (cost[i][j] < 0 || cost[i][j] > rem) continue
            if (rem - cost[i][j] > maxs[i+1]) continue
            if (i == n - 1 && rem != cost[i][j]) continue
            ans.append(j)
            rem -= cost[i][j]
            break
        }
    }
    println(ans.toString())
}

fun main(args: Array<String>) {
    val writer = PrintWriter(System.out, false)
    writer.solve(FastScanner(System.`in`))
    writer.flush()
}

class FastScanner(s: InputStream) {
    private var st = StringTokenizer("")
    private val br = BufferedReader(InputStreamReader(s))

    fun next(): String {
        while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine())

        return st.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextLine() = br.readLine()
    fun nextDouble() = next().toDouble()
    fun ready() = br.ready()
}


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.StringBuilder
import java.util.*

fun PrintWriter.solve(sc: FastScanner) {
    val n = sc.nextInt()
    val k = sc.nextInt()
    val ss = Array(n) { sc.nextLine() }
    val shape = arrayOf(
            "1110111",
            "0010010",
            "1011101",
            "1011011",
            "0111010",
            "1101011",
            "1101111",
            "1010010",
            "1111111",
            "1111011"
    )
    val cost = Array(n) { Array(10) { -1 } }
    for (i in 0 until n) {
        val s = ss[i]
        for (j in 0 until 10) {
            val t = shape[j]
            var count = 0
            for (k in 0 until 7) {
                if (s[k] == '0' && t[k] == '1') {
                    count++
                } else if (s[k] == '1' && t[k] == '0') {
                    count = -1
                    break
                }
            }
            cost[i][j] = count
        }
    }
    var dp = Array(k + 1) { "." }
    dp[0] = ""
    for (i in 0 until n) {
        val newdp = Array(k+1) { "." }
        for (j in 0..k) {
            if (dp[j] == ".") continue
            for (d in 0..9) {
                if (cost[i][d] < 0 || j + cost[i][d] > k) continue
                newdp[j + cost[i][d]] = maxOf(newdp[j + cost[i][d]], dp[j] + d)
            }
        }
        dp = newdp
    }
    println(if (dp[k] == ".") -1 else dp[k])
}

fun main(args: Array<String>) {
    val writer = PrintWriter(System.out, false)
    writer.solve(FastScanner(System.`in`))
    writer.flush()
}

class FastScanner(s: InputStream) {
    private var st = StringTokenizer("")
    private val br = BufferedReader(InputStreamReader(s))

    fun next(): String {
        while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine())

        return st.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextLine() = br.readLine()
    fun nextDouble() = next().toDouble()
    fun ready() = br.ready()
}


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.StringBuilder
import java.util.*

fun PrintWriter.solve(sc: FastScanner) {
    val n = sc.nextInt()
    val k = sc.nextInt()
    val ss = Array(n) { sc.nextLine() }
    val shape = arrayOf(
            "1110111",
            "0010010",
            "1011101",
            "1011011",
            "0111010",
            "1101011",
            "1101111",
            "1010010",
            "1111111",
            "1111011"
    )
    val cost = Array(n) { Array(10) { -1 } }
    for (i in 0 until n) {
        val s = ss[i]
        for (j in 0 until 10) {
            val t = shape[j]
            var count = 0
            for (k in 0 until 7) {
                if (s[k] == '0' && t[k] == '1') {
                    count++
                } else if (s[k] == '1' && t[k] == '0') {
                    count = -1
                    break
                }
            }
            cost[i][j] = count
        }
    }
    val mincost = cost.map { it.filter { it >= 0 }.min() ?: -1 }
    val maxcost = cost.map { it.max()!! }
    val min = mincost.sum()
    val max = maxcost.sum()
    val maxs = Array(n + 1) { 0 }
    for (i in n - 1 downTo 0) {
        maxs[i] = maxs[i + 1] + maxcost[i]
    }
    val dp = Array(n + 1) { Array(k + 1) { "x" } }
    dp[0][0] = ""
    for (i in 0 until n) {
        for (j in 0 until k) {
            if (dp[i][j] == "x") continue
            for (d in 0..9) {
                if (cost[i][d] < 0 || j + cost[i][d] > k) continue
                dp[i + 1][j + cost[i][d]] = dp[i][j] + d
            }
        }
    }
    println(if (dp[n][k] == "x") -1 else dp[n][k])
}

fun main(args: Array<String>) {
    val writer = PrintWriter(System.out, false)
    writer.solve(FastScanner(System.`in`))
    writer.flush()
}

class FastScanner(s: InputStream) {
    private var st = StringTokenizer("")
    private val br = BufferedReader(InputStreamReader(s))

    fun next(): String {
        while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine())

        return st.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextLine() = br.readLine()
    fun nextDouble() = next().toDouble()
    fun ready() = br.ready()
}


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.StringBuilder
import java.util.*

fun PrintWriter.solve(sc: FastScanner) {
    val n = sc.nextInt()
    val k = sc.nextInt()
    val ss = Array(n) { sc.nextLine() }
    val shape = arrayOf(
        "1110111",
        "0010010",
        "1011101",
        "1011011",
        "0111010",
        "1101011",
        "1101111",
        "1010010",
        "1111111",
        "1111011"
    )
    val cost = Array(n) { Array(10) { -1 } }
    for (i in 0 until n) {
        val s = ss[i]
        for (j in 0 until 10) {
            val t = shape[j]
            var count = 0
            for (k in 0 until 7) {
                if (s[k] == '0' && t[k] == '1') {
                    count++
                } else if (s[k] == '1' && t[k] == '0') {
                    count = -1
                    break
                }
            }
            cost[i][j] = count
        }
    }
    val mincost = cost.map { it.filter { it >= 0 }.min() ?: -1 }
    val maxcost = cost.map { it.max()!! }
    val min = mincost.sum()
    val max = maxcost.sum()
    val maxs = Array(n+1) { 0 }
    for (i in n-1 downTo 0) {
        maxs[i] = maxs[i+1] + maxcost[i]
    }
    if (maxcost.any { it < 0 } || k < min || k > max) {
        println(-1)
        return
    }
    var rem = k - min
    val ans = StringBuilder()
    for (i in 0 until n) {
        rem += mincost[i]
        var ok = false
        for (j in 9 downTo 0) {
            if (cost[i][j] < 0 || cost[i][j] > rem) continue
            if (rem - cost[i][j] > maxs[i+1]) continue
            if (i == n - 1 && rem != cost[i][j]) continue
            ans.append(j)
            rem -= cost[i][j]
            ok = true
            break
        }
        if (!ok) {
            println(-1)
            return
        }
    }
    println(ans.toString())
}

fun main(args: Array<String>) {
    val writer = PrintWriter(System.out, false)
    writer.solve(FastScanner(System.`in`))
    writer.flush()
}

class FastScanner(s: InputStream) {
    private var st = StringTokenizer("")
    private val br = BufferedReader(InputStreamReader(s))

    fun next(): String {
        while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine())

        return st.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextLine() = br.readLine()
    fun nextDouble() = next().toDouble()
    fun ready() = br.ready()
}


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.StringBuilder
import java.util.*

fun PrintWriter.solve(sc: FastScanner) {
    val n = sc.nextInt()
    val k = sc.nextInt()
    val ss = Array(n) { sc.nextLine() }
    val shape = arrayOf(
            "1110111",
            "0010010",
            "1011101",
            "1011011",
            "0111010",
            "1101011",
            "1101111",
            "1010010",
            "1111111",
            "1111011"
    )
    val cost = Array(n) { Array(10) { -1 } }
    for (i in 0 until n) {
        val s = ss[i]
        for (j in 0 until 10) {
            val t = shape[j]
            var count = 0
            for (k in 0 until 7) {
                if (s[k] == '0' && t[k] == '1') {
                    count++
                } else if (s[k] == '1' && t[k] == '0') {
                    count = -1
                    break
                }
            }
            cost[i][j] = count
        }
    }
    val dp = Array(n + 1) { Array(k + 1) { "x" } }
    dp[0][0] = ""
    for (i in 0 until n) {
        for (j in 0..k) {
            if (dp[i][j] == "x") continue
            for (d in 0..9) {
                if (cost[i][d] < 0 || j + cost[i][d] > k) continue
                dp[i + 1][j + cost[i][d]] = dp[i][j] + d
            }
        }
    }
    println(if (dp[n][k] == "x") -1 else dp[n][k])
}

fun main(args: Array<String>) {
    val writer = PrintWriter(System.out, false)
    writer.solve(FastScanner(System.`in`))
    writer.flush()
}

class FastScanner(s: InputStream) {
    private var st = StringTokenizer("")
    private val br = BufferedReader(InputStreamReader(s))

    fun next(): String {
        while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine())

        return st.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextLine() = br.readLine()
    fun nextDouble() = next().toDouble()
    fun ready() = br.ready()
}


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.StringBuilder
import java.util.*

fun PrintWriter.solve(sc: FastScanner) {
    val n = sc.nextInt()
    val k = sc.nextInt()
    val ss = Array(n) { sc.nextLine() }
    val shape = arrayOf(
            "1110111",
            "0010010",
            "1011101",
            "1011011",
            "0111010",
            "1101011",
            "1101111",
            "1010010",
            "1111111",
            "1111011"
    )
    val cost = Array(n) { Array(10) { -1 } }
    for (i in 0 until n) {
        val s = ss[i]
        for (j in 0 until 10) {
            val t = shape[j]
            var count = 0
            for (k in 0 until 7) {
                if (s[k] == '0' && t[k] == '1') {
                    count++
                } else if (s[k] == '1' && t[k] == '0') {
                    count = -1
                    break
                }
            }
            cost[i][j] = count
        }
    }
    val dp = Array(n + 1) { Array(k + 1) { "." } }
    dp[0][0] = ""
    for (i in 0 until n) {
        for (j in 0..k) {
            if (dp[i][j] == ".") continue
            for (d in 0..9) {
                if (cost[i][d] < 0 || j + cost[i][d] > k) continue
                dp[i + 1][j + cost[i][d]] = maxOf(dp[i + 1][j + cost[i][d]], dp[i][j] + d)
            }
        }
    }
    println(if (dp[n][k] == ".") -1 else dp[n][k])
}

fun main(args: Array<String>) {
    val writer = PrintWriter(System.out, false)
    writer.solve(FastScanner(System.`in`))
    writer.flush()
}

class FastScanner(s: InputStream) {
    private var st = StringTokenizer("")
    private val br = BufferedReader(InputStreamReader(s))

    fun next(): String {
        while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine())

        return st.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextLine() = br.readLine()
    fun nextDouble() = next().toDouble()
    fun ready() = br.ready()
}


import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*

val DIGITS = arrayOf("1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011")
val BITMASKS = DIGITS.map { it.toInt(2) }

fun main() {
    val bitAMT = IntArray(128)
    for (mask in 1..127) {
        bitAMT[mask] = bitAMT[mask - (mask and -mask)] + 1
    }
    val jin = BufferedReader(InputStreamReader(System.`in`))
    val tokenizer = StringTokenizer(jin.readLine())
    val n = tokenizer.nextToken().toInt()
    val k = tokenizer.nextToken().toInt()
    val digit = Array(n + 1) { IntArray(k + 1) { -1 } }
    digit[0][0] = 0
    val scoreboard = Array(n) { jin.readLine().toInt(2) }
    for (j1 in 1..n) {
        for (j2 in 0..k) {
            for (d in 0..9) {
                if (BITMASKS[d] or scoreboard[n - j1] == BITMASKS[d]) {
                    val amt = bitAMT[BITMASKS[d] xor scoreboard[n - j1]]
                    if (j2 >= amt && digit[j1 - 1][j2 - amt] != -1) {
                        digit[j1][j2] = d
                    }
                }
            }
        }
    }
    if (digit[n][k] == -1) {
        println(-1)
    } else {
        val answer = StringBuilder()
        var kt = k
        for (j in n downTo 1) {
            answer.append(digit[j][kt])
            kt -= bitAMT[BITMASKS[digit[j][kt]] xor scoreboard[n - j]]
        }
        println(answer)
    }
}


import java.lang.StringBuilder
import java.math.BigInteger
import kotlin.math.max

fun main(args : Array<String>) {

    val NT = 1//readLine()?.toInt() ?: 0

    val seq = arrayOf("1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011" )

    for(test in 1..NT) {
        val (n, k) = readLine()!!.split(" ").map { it.toInt() }
        val s = Array(n) { readLine()!!}

        val dp = Array(n+1) {Array(k + 1) { -1 } }
        dp[n][k] = 0
        for(i in n-1 downTo 0) {
            for(m in 0 .. 9){
                val stepsNow = neededSteps(s[i], seq[m])
                if(stepsNow == 10) continue
                for( j in 0 .. k) {
                    if(j + stepsNow <= k && dp[i+1][j + stepsNow] >= 0 &&  dp[i][j] < m) {
                        dp[i][j] = m
                    }
                }
            }
        }
        val sb = StringBuilder()
        var t = 0
        for(i in 0 until n) {
            if(dp[i][t] == -1) {
                println(-1)
                return
            }
            sb.append(dp[i][t])
            t += neededSteps(s[i], seq[dp[i][t]])
        }
        println(sb)
    }
}

fun neededSteps(s: String, t: String): Int {
    //if impossible return 10
    var ans = 0
    for(i in 0 until s.length) {
        if(s[i] == '1' && t[i] == '0')return 10
        else if(s[i] != t[i]) ans++
    }
    return ans
}


import java.math.BigInteger
import kotlin.math.max

fun main(args : Array<String>) {

    val NT = 1//readLine()?.toInt() ?: 0

    val seq = arrayOf("1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011" )

    for(test in 1..NT) {
        val (n, k) = readLine()!!.split(" ").map { it.toInt() }
        val s = Array(n) { readLine()!!}

        val ans = Array(n){'x'}
        var possible = true

        var stepsLeft = k

        for(i in 0 until n) {
            var minSteps = 10
            for(j in 0..9) {
                val needed = neededSteps(s[i], seq[j])
                if(needed < minSteps) {
                    minSteps = needed
                    ans[i] = '0' + j
                }
            }
            if(minSteps == 10) {
                possible = false
                break
            } else {
                stepsLeft -= minSteps
            }
        }

        if(!possible) {
            println( -1)
            return
        }

        val dp = Array(n+1) {Array(k + 1) { BigInteger.valueOf((-1)) } }
        dp[0][k] = BigInteger.ZERO
        for(i in 0 until n) {
            for(m in 0 .. 9){
                val stepsNow = neededSteps(s[i], seq[m])
                if(stepsNow == 10) continue
                for( j in 0 .. k) {
                    if(j + stepsNow <= k &&dp[i][j + stepsNow] >= BigInteger.ZERO && dp[i][j + stepsNow].multiply(BigInteger.TEN) + BigInteger.valueOf(m.toLong()) > dp[i+1][j]) {
                        dp[i + 1][j] = dp[i][j + stepsNow].multiply(BigInteger.TEN) + BigInteger.valueOf(m.toLong())
                    }
                }
            }
        }
        println(dp[n][0])
    }
}

fun neededSteps(s: String, t: String): Int {
    //if impossible return 10
    var ans = 0
    for(i in 0 until s.length) {
        if(s[i] == '1' && t[i] == '0')return 10
        else if(s[i] != t[i]) ans++
    }
    return ans
}


import java.lang.StringBuilder
import java.math.BigInteger
import kotlin.math.max

fun main(args : Array<String>) {

    val NT = 1//readLine()?.toInt() ?: 0

    val seq = arrayOf("1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011" )

    for(test in 1..NT) {
        val (n, k) = readLine()!!.split(" ").map { it.toInt() }
        val s = Array(n) { readLine()!!}

        val dp = Array(n+1) {Array(k + 1) { -1 } }
        dp[0][k] = 0
        for(i in 0 until n) {
            for(m in 0 .. 9){
                val stepsNow = neededSteps(s[i], seq[m])
                if(stepsNow == 10) continue
                for( j in 0 .. k) {
                    if(j + stepsNow <= k && dp[i][j + stepsNow] >= 0 &&  dp[i+1][j] < m) {
                        dp[i + 1][j] = m
                    }
                }
            }
        }
        val sb = StringBuilder()
        var t = 0
        for(i in n downTo 1) {
            if(dp[i][t] == -1) {
                println(-1)
                return
            }
            sb.append(dp[i][t])
            t += neededSteps(s[i - 1], seq[dp[i][t]])
        }
        println(sb)
    }
}

fun neededSteps(s: String, t: String): Int {
    //if impossible return 10
    var ans = 0
    for(i in 0 until s.length) {
        if(s[i] == '1' && t[i] == '0')return 10
        else if(s[i] != t[i]) ans++
    }
    return ans
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.TreeSet;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Andy Phan
 */
public class b {
    static String[] nums = {"1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011"};

    public static void main(String[] args) {
        FS in = new FS(System.in);
        PrintWriter out = new PrintWriter(System.out);

        new b().solve(in, out);

        out.close();
    }
    static int bits = 7;
    static int num = 1<<bits;
    public void solve(FS in, PrintWriter out) {
        int[] rev = new int[num];
        Arrays.fill(rev, -1);
        for(int i = 0; i < 10; i++) rev[Integer.parseInt(new StringBuilder(nums[i]).reverse().toString(), 2)] = i;
        int[][] max = new int[num][bits+1];
        for(int i = 0; i < num; i++) {
            for(int j = 0; j < bits+1; j++) max[i][j] = -1;
            for(int k = 0; k < num; k++) {
                if((i&k) != 0) continue;
                max[i][Integer.bitCount(k)] = Math.max(max[i][Integer.bitCount(k)], rev[i|k]);
            }
        }
        int n = in.nextInt();
        int k = in.nextInt();
        int[] nums = new int[n];
        for(int i = 0; i < n; i++) nums[i] = Integer.parseInt(new StringBuilder(in.next()).reverse().toString(), 2);
        boolean[][] can = new boolean[n+1][k+1];
        can[n][0] = true;
        for(int i = n-1; i >= 0; i--) {
            for(int j = 0; j <= k; j++) {
                int res = -1;
                for(int l = 0; l <= Math.min(bits, j); l++) {
                    if(can[i+1][j-l]) res = Math.max(res, max[nums[i]][l]);
                }
                can[i][j] = res != -1;
            }
        }

        if(!can[0][k]) {
            System.out.println(-1);
            return;
        }
        for(int i = 0; i < n; i++) {
            int res = -1;
            int num = 0;
            for(int l = 0; l <= Math.min(bits, k); l++) {
                if(can[i+1][k-l]) {
                    if(max[nums[i]][l] > res) num = l;
                    res = Math.max(res, max[nums[i]][l]);
                }
            }
            k -= num;
            out.print(res);
        }
        out.println();
    }

    static class FS {

        BufferedReader in;
        StringTokenizer token;

        public FS(InputStream str) {
            in = new BufferedReader(new InputStreamReader(str));
        }

        public String nextLine() {
            token = new StringTokenizer("");
            try {
                return in.readLine();
            } catch (Exception e) {
                return null;
            }
        }

        public String next() {
            if (token == null || !token.hasMoreElements()) {
                try {
                    token = new StringTokenizer(in.readLine());
                } catch (IOException ex) {
                }
                return next();
            }
            return token.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }
    }
}


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

public class Graph {

	static class Reader {
		final private int BUFFER_SIZE = 1 << 16;
		private DataInputStream din;
		private byte[] buffer;
		private int bufferPointer, bytesRead;

		public Reader() {
			din = new DataInputStream(System.in);
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public Reader(String file_name) throws IOException {
			din = new DataInputStream(new FileInputStream(file_name));
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public String readLine() throws IOException {
			byte[] buf = new byte[64]; // line length
			int cnt = 0, c;
			while ((c = read()) != -1) {
				if (c == '\n')
					break;
				buf[cnt++] = (byte) c;
			}
			return new String(buf, 0, cnt);
		}

		public int nextInt() throws IOException {
			int ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');

			if (neg)
				return -ret;
			return ret;
		}

		public long nextLong() throws IOException {
			long ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');
			if (neg)
				return -ret;
			return ret;
		}

		public double nextDouble() throws IOException {
			double ret = 0, div = 1;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();

			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');

			if (c == '.') {
				while ((c = read()) >= '0' && c <= '9') {
					ret += (c - '0') / (div *= 10);
				}
			}

			if (neg)
				return -ret;
			return ret;
		}

		private void fillBuffer() throws IOException {
			bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
			if (bytesRead == -1)
				buffer[0] = -1;
		}

		private byte read() throws IOException {
			if (bufferPointer == bytesRead)
				fillBuffer();
			return buffer[bufferPointer++];
		}

		public void close() throws IOException {
			if (din == null)
				return;
			din.close();
		}
	}
	public static void main(String[] args) throws IOException {

		Reader scan=new Reader();
		//int t=scan.nextInt();

//		while(t-->0) {
//			long n=scan.nextLong();
//			long l=scan.nextLong();
//			long r=scan.nextLong();
//
//			D1334(n, l, r, 1, 1);
//			System.out.println();
//		}

		B1340();

	}

	public static void D1334(long n, long l, long r, long seg, long cur) {

		if(cur>r) return;

		if(seg==n) {
			System.out.print(1);
			return;
		}

		long t= 2*(n-seg);

		long hi= cur+t-1;

		if(hi<l) {
			D1334(n, l, r, seg+1, hi+1);
			return;
		}

		long i= l-cur+1;

		if(i%2==0) {
			System.out.print((seg+i/2)+" ");
			i++;
		}

		for(;i+cur-1<=Math.min(r,  hi);i++) {

			if(i%2!=0) System.out.print(seg+" ");
			else System.out.print((seg+i/2)+" ");

		}

		if(i==r+1) return;

		D1334(n, hi+1, r, seg+1, hi+1);

	}

	public static void C1334() throws IOException {

		Reader scan=new Reader();
		int n=scan.nextInt();
		int m=scan.nextInt();

		List<Integer> adj[]=new ArrayList[n+1];
		List<Integer> rev[]=new ArrayList[n+1];
		for(int i=0;i<m;i++) {

			int u=scan.nextInt();
			int v=scan.nextInt();

			if(adj[v]==null) adj[v]=new ArrayList<>();
			if(rev[u]==null) rev[u]=new ArrayList<>();
			adj[v].add(u);
			rev[u].add(v);
		}

		boolean visited[]=new boolean[n+1];

		for(int i=1;i<=n;i++) {

			if(!visited[i]) {
				Set<Integer> cur=new HashSet<>();
				boolean ans= dfs(i, adj, visited, cur);
				if(ans) {
					System.out.println(-1);
					return;
				}
			}
		}

//		for(int i=1;i<=n;i++) {
//
//			System.out.print(i+"> ");
//			if(adj[i]==null) {
//				System.out.println();
//				continue;
//			}
//			System.out.println(Arrays.toString(adj[i].toArray()));
//
//		}

		int min1[]=new int[n+1];
		int min2[]=new int[n+1];
		visited=new boolean[n+1];
		for(int i=1;i<=n;i++) {

			if(!visited[i]) {
				getMin(min1, i, adj, visited);
			}
		}

		visited=new boolean[n+1];
		for(int i=1;i<=n;i++) {

			if(!visited[i]) {
				getMin(min2, i, rev, visited);
			}
		}

		int count=0;
		StringBuilder ans=new StringBuilder("");
		for(int i=1;i<=n;i++) {

			if(min1[i]==i&&min2[i]==i) {
				count++;
				ans.append("A");
			}else {
				ans.append("E");
			}
		}
		System.out.println(count);
		System.out.println(ans.toString());

	}

	public static int getMin(int min[], int start, List<Integer> adj[], boolean visited[]) {

		if(visited[start]) {
			return min[start];
		}

		min[start]=start;
		visited[start]=true;
		if(adj[start]==null) return min[start];
		for(Integer x: adj[start]) {
			min[start]=Math.min(min[start], getMin(min, x, adj, visited));
		}

		return min[start];

	}

	public static boolean dfs(int start, List<Integer> adj[], boolean visited[], Set<Integer> cur) {

		if(cur.contains(start)) {
			return true;
		}

		if(visited[start]) return false;

		visited[start]=true;
		cur.add(start);

		if(adj[start]==null) {
			cur.remove(start);
			return false;
		}

		for(int newStart: adj[start]) {
			if(dfs(newStart, adj, visited, cur)) {
				return true;
			}
		}

		cur.remove(start);
		return false;
	}

	public static void D1340() throws IOException {

		Reader scan=new Reader();
		int n=scan.nextInt();

		List<Integer> adj[]=new ArrayList[n+1];

		for(int i=0;i<n-1;i++) {
			int u=scan.nextInt();
			int v=scan.nextInt();

			if(adj[u]==null) adj[u]=new ArrayList<>();
			if(adj[v]==null) adj[v]=new ArrayList<>();

			adj[u].add(v);
			adj[v].add(u);
		}

		if(adj[1]==null) {
			System.out.println(1);
			System.out.println("1 0");
			return;
		}

		StringBuilder ans=new StringBuilder("");
		System.out.println(dfs(1, adj, 0, 0, ans));

		System.out.println(ans.toString());

	}

	public static int dfs(int start, List<Integer> adj[], int parent, int curTime, StringBuilder ans){

		int count=0;
		count++;
		ans.append(start+" "+curTime+"\n");

		int copy=curTime;

		if(curTime-adj[start].size()>=0) {
			copy=curTime-adj[start].size();
			count++;
			ans.append(start+" "+copy+"\n");
		}

		int i=copy+1;
		for(Integer x: adj[start]) {
			if(x==parent) continue;

			count+=dfs(x, adj, start, i, ans);
			count++;
			ans.append(start+" "+i+"\n");
			i++;

		}
		if(i!=curTime&&start!=1) {
			count++;
			ans.append(start+" "+(curTime-1)+"\n");
		}

		return count;

	}

	public static void C1340() throws IOException {

		Reader scan=new Reader();
		int n=scan.nextInt();
		int m=scan.nextInt();

		int arr[]=new int[m+1];
		for(int i=0;i<m;i++) {
			arr[i]=scan.nextInt();
		}

		arr[arr.length-1]=n;

		int g=scan.nextInt();
		int r=scan.nextInt();

		long dp[][]=new long[m+1][g+1];

		for(long x[]: dp) {
			Arrays.fill(x, -1);
		}
		long ans= C1340helper(0, arr, n, dp, g-arr[0], g, r);
		ans= (ans==Long.MAX_VALUE)?-1: ans;
		System.out.println(ans);

	}

	public static long C1340helper(int i, int arr[], int n, long dp[][], int rem, int g, int r) {

		//System.out.println("On i="+i);

		if(i<0) return Long.MAX_VALUE;
		if(i>=arr.length) return Long.MAX_VALUE;

		if(rem<0) return Long.MAX_VALUE;

		if(arr[i]==n) {
			return (long)0;
		}

		if(dp[i][rem]==-2) {
			return Long.MAX_VALUE;
		}

		if(rem==0&&dp[i][g]==-2) {
			return Long.MAX_VALUE;
		}

		if(dp[i][rem]!=-1) {
			return dp[i][rem];
		}

		dp[i][rem]=-2;

		long curTime= (rem==0)? (long)r: (long)0;
		int time= (rem==0)?g:rem;

		long ans1=Long.MAX_VALUE;
		if(i!=0) {
			ans1= C1340helper(i-1, arr, n, dp, time-(arr[i]-arr[i-1]), g, r);
			if(ans1!=Long.MAX_VALUE) {
				ans1+= arr[i]-arr[i-1];
			}
		}

		long ans2= C1340helper(i+1, arr, n, dp, time-(arr[i+1]-arr[i]), g, r);

		if(ans2!=Long.MAX_VALUE) {
			ans2+= arr[i+1]-arr[i];
		}
		long ans= Math.min(ans1, ans2);
		if(ans==Long.MAX_VALUE) {
			dp[i][rem]=Long.MAX_VALUE;

		}else {
			dp[i][rem]= ans+curTime;
		}

		return dp[i][rem];

	}

	public static void B1340() throws IOException {

		String str[]= {"0001000", "1101101", "0100010", "0100100", "1000101", "0010100", "0010000", "0101101", "0000000", "0000100"};
		int masks[]=new int[10];
		int ind=0;
		for(String s: str) {

			int val=0;
			int pow=1;
			for(int i=s.length()-1;i>=0;i--) {
				if(s.charAt(i)=='1') {
					val+= pow;
				}

				pow*=2;
			}

			masks[ind++]=val;
		}

		//System.out.println(Arrays.toString(masks));

		int vals[]=new int[10];

		for(int i=0;i<vals.length;i++) {
			vals[i]= 127- masks[i];
		}

		//System.out.println(Arrays.toString(vals));
		Scanner scan=new Scanner(System.in);

		int n=scan.nextInt();
		int k=scan.nextInt();

		int arr[]=new int[n];
		for(int i=0;i<n;i++) {
			String s=scan.next();
			int val=0;
			int pow=1;
			for(int j=s.length()-1;j>=0;j--) {
				if(s.charAt(j)=='1') {
					val+= pow;
				}

				pow*=2;
			}

			arr[i]=val;
		}
		String dp[][]=new String[n][k+1];

		for(String x[]: dp) {
			Arrays.fill(x, "");
		}

		String ans= B1340helper(0, arr, dp, k, masks, vals);
		if(ans==null) {
			System.out.println(-1);
		}else {
			System.out.println(ans);
		}
	}

	public static String B1340helper(int i, int arr[], String dp[][], int k, int masks[], int vals[]) {

		if(k<0) return null;

		if(i>=arr.length) {

			if(k==0) return"";

			return null;
		}

		if(dp[i][k]!="") {
			return dp[i][k];
		}

		for(int j=9;j>=0;j--) {

			if((arr[i]&masks[j])!=0) {

				continue;
			}

			int required= Integer.bitCount(vals[j]^arr[i]);
			String recAns= B1340helper(i+1, arr, dp, k-required, masks, vals);

			if(recAns!=null) {
				dp[i][k]= j+recAns;
				return dp[i][k];
			}

		}
		dp[i][k]=null;
		return null;

	}
}


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Graph {

	static class Reader {
		final private int BUFFER_SIZE = 1 << 16;
		private DataInputStream din;
		private byte[] buffer;
		private int bufferPointer, bytesRead;

		public Reader() {
			din = new DataInputStream(System.in);
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public Reader(String file_name) throws IOException {
			din = new DataInputStream(new FileInputStream(file_name));
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public String readLine() throws IOException {
			byte[] buf = new byte[64]; // line length
			int cnt = 0, c;
			while ((c = read()) != -1) {
				if (c == '\n')
					break;
				buf[cnt++] = (byte) c;
			}
			return new String(buf, 0, cnt);
		}

		public int nextInt() throws IOException {
			int ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');

			if (neg)
				return -ret;
			return ret;
		}

		public long nextLong() throws IOException {
			long ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');
			if (neg)
				return -ret;
			return ret;
		}

		public double nextDouble() throws IOException {
			double ret = 0, div = 1;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();

			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');

			if (c == '.') {
				while ((c = read()) >= '0' && c <= '9') {
					ret += (c - '0') / (div *= 10);
				}
			}

			if (neg)
				return -ret;
			return ret;
		}

		private void fillBuffer() throws IOException {
			bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
			if (bytesRead == -1)
				buffer[0] = -1;
		}

		private byte read() throws IOException {
			if (bufferPointer == bytesRead)
				fillBuffer();
			return buffer[bufferPointer++];
		}

		public void close() throws IOException {
			if (din == null)
				return;
			din.close();
		}
	}
	public static void main(String[] args) throws IOException {

		Reader scan=new Reader();
		//int t=scan.nextInt();

//		while(t-->0) {
//			long n=scan.nextLong();
//			long l=scan.nextLong();
//			long r=scan.nextLong();
//
//			D1334(n, l, r, 1, 1);
//			System.out.println();
//		}

		B1340();

	}

	public static void D1334(long n, long l, long r, long seg, long cur) {

		if(cur>r) return;

		if(seg==n) {
			System.out.print(1);
			return;
		}

		long t= 2*(n-seg);

		long hi= cur+t-1;

		if(hi<l) {
			D1334(n, l, r, seg+1, hi+1);
			return;
		}

		long i= l-cur+1;

		if(i%2==0) {
			System.out.print((seg+i/2)+" ");
			i++;
		}

		for(;i+cur-1<=Math.min(r,  hi);i++) {

			if(i%2!=0) System.out.print(seg+" ");
			else System.out.print((seg+i/2)+" ");

		}

		if(i==r+1) return;

		D1334(n, hi+1, r, seg+1, hi+1);

	}

	public static void C1334() throws IOException {

		Reader scan=new Reader();
		int n=scan.nextInt();
		int m=scan.nextInt();

		List<Integer> adj[]=new ArrayList[n+1];
		List<Integer> rev[]=new ArrayList[n+1];
		for(int i=0;i<m;i++) {

			int u=scan.nextInt();
			int v=scan.nextInt();

			if(adj[v]==null) adj[v]=new ArrayList<>();
			if(rev[u]==null) rev[u]=new ArrayList<>();
			adj[v].add(u);
			rev[u].add(v);
		}

		boolean visited[]=new boolean[n+1];

		for(int i=1;i<=n;i++) {

			if(!visited[i]) {
				Set<Integer> cur=new HashSet<>();
				boolean ans= dfs(i, adj, visited, cur);
				if(ans) {
					System.out.println(-1);
					return;
				}
			}
		}

//		for(int i=1;i<=n;i++) {
//
//			System.out.print(i+"> ");
//			if(adj[i]==null) {
//				System.out.println();
//				continue;
//			}
//			System.out.println(Arrays.toString(adj[i].toArray()));
//
//		}

		int min1[]=new int[n+1];
		int min2[]=new int[n+1];
		visited=new boolean[n+1];
		for(int i=1;i<=n;i++) {

			if(!visited[i]) {
				getMin(min1, i, adj, visited);
			}
		}

		visited=new boolean[n+1];
		for(int i=1;i<=n;i++) {

			if(!visited[i]) {
				getMin(min2, i, rev, visited);
			}
		}

		int count=0;
		StringBuilder ans=new StringBuilder("");
		for(int i=1;i<=n;i++) {

			if(min1[i]==i&&min2[i]==i) {
				count++;
				ans.append("A");
			}else {
				ans.append("E");
			}
		}
		System.out.println(count);
		System.out.println(ans.toString());

	}

	public static int getMin(int min[], int start, List<Integer> adj[], boolean visited[]) {

		if(visited[start]) {
			return min[start];
		}

		min[start]=start;
		visited[start]=true;
		if(adj[start]==null) return min[start];
		for(Integer x: adj[start]) {
			min[start]=Math.min(min[start], getMin(min, x, adj, visited));
		}

		return min[start];

	}

	public static boolean dfs(int start, List<Integer> adj[], boolean visited[], Set<Integer> cur) {

		if(cur.contains(start)) {
			return true;
		}

		if(visited[start]) return false;

		visited[start]=true;
		cur.add(start);

		if(adj[start]==null) {
			cur.remove(start);
			return false;
		}

		for(int newStart: adj[start]) {
			if(dfs(newStart, adj, visited, cur)) {
				return true;
			}
		}

		cur.remove(start);
		return false;
	}

	public static void D1340() throws IOException {

		Reader scan=new Reader();
		int n=scan.nextInt();

		List<Integer> adj[]=new ArrayList[n+1];

		for(int i=0;i<n-1;i++) {
			int u=scan.nextInt();
			int v=scan.nextInt();

			if(adj[u]==null) adj[u]=new ArrayList<>();
			if(adj[v]==null) adj[v]=new ArrayList<>();

			adj[u].add(v);
			adj[v].add(u);
		}

		if(adj[1]==null) {
			System.out.println(1);
			System.out.println("1 0");
			return;
		}

		StringBuilder ans=new StringBuilder("");
		System.out.println(dfs(1, adj, 0, 0, ans));

		System.out.println(ans.toString());

	}

	public static int dfs(int start, List<Integer> adj[], int parent, int curTime, StringBuilder ans){

		int count=0;
		count++;
		ans.append(start+" "+curTime+"\n");

		int copy=curTime;

		if(curTime-adj[start].size()>=0) {
			copy=curTime-adj[start].size();
			count++;
			ans.append(start+" "+copy+"\n");
		}

		int i=copy+1;
		for(Integer x: adj[start]) {
			if(x==parent) continue;

			count+=dfs(x, adj, start, i, ans);
			count++;
			ans.append(start+" "+i+"\n");
			i++;

		}
		if(i!=curTime&&start!=1) {
			count++;
			ans.append(start+" "+(curTime-1)+"\n");
		}

		return count;

	}

	public static void C1340() throws IOException {

		Reader scan=new Reader();
		int n=scan.nextInt();
		int m=scan.nextInt();

		int arr[]=new int[m+1];
		for(int i=0;i<m;i++) {
			arr[i]=scan.nextInt();
		}

		arr[arr.length-1]=n;

		int g=scan.nextInt();
		int r=scan.nextInt();

		long dp[][]=new long[m+1][g+1];

		for(long x[]: dp) {
			Arrays.fill(x, -1);
		}
		long ans= C1340helper(0, arr, n, dp, g-arr[0], g, r);
		ans= (ans==Long.MAX_VALUE)?-1: ans;
		System.out.println(ans);

	}

	public static long C1340helper(int i, int arr[], int n, long dp[][], int rem, int g, int r) {

		//System.out.println("On i="+i);

		if(i<0) return Long.MAX_VALUE;
		if(i>=arr.length) return Long.MAX_VALUE;

		if(rem<0) return Long.MAX_VALUE;

		if(arr[i]==n) {
			return (long)0;
		}

		if(dp[i][rem]==-2) {
			return Long.MAX_VALUE;
		}

		if(rem==0&&dp[i][g]==-2) {
			return Long.MAX_VALUE;
		}

		if(dp[i][rem]!=-1) {
			return dp[i][rem];
		}

		dp[i][rem]=-2;

		long curTime= (rem==0)? (long)r: (long)0;
		int time= (rem==0)?g:rem;

		long ans1=Long.MAX_VALUE;
		if(i!=0) {
			ans1= C1340helper(i-1, arr, n, dp, time-(arr[i]-arr[i-1]), g, r);
			if(ans1!=Long.MAX_VALUE) {
				ans1+= arr[i]-arr[i-1];
			}
		}

		long ans2= C1340helper(i+1, arr, n, dp, time-(arr[i+1]-arr[i]), g, r);

		if(ans2!=Long.MAX_VALUE) {
			ans2+= arr[i+1]-arr[i];
		}
		long ans= Math.min(ans1, ans2);
		if(ans==Long.MAX_VALUE) {
			dp[i][rem]=Long.MAX_VALUE;

		}else {
			dp[i][rem]= ans+curTime;
		}

		return dp[i][rem];

	}

	public static void B1340() throws IOException {

		String str[]= {"0001000", "1101101", "0100010", "0100100", "1000101", "0010100", "0010000", "0101101", "0000000", "0000100"};
		int masks[]=new int[10];
		int ind=0;
		for(String s: str) {

			int val=0;
			int pow=1;
			for(int i=s.length()-1;i>=0;i--) {
				if(s.charAt(i)=='1') {
					val+= pow;
				}

				pow*=2;
			}

			masks[ind++]=val;
		}

		//System.out.println(Arrays.toString(masks));

		int vals[]=new int[10];

		for(int i=0;i<vals.length;i++) {
			vals[i]= 127- masks[i];
		}

		//System.out.println(Arrays.toString(vals));
		Reader scan=new Reader();

		int n=scan.nextInt();
		int k=scan.nextInt();

		int arr[]=new int[n];
		for(int i=0;i<n;i++) {
			String s=scan.readLine();
			int val=0;
			int pow=1;
			for(int j=s.length()-1;j>=0;j--) {
				if(s.charAt(j)=='1') {
					val+= pow;
				}

				pow*=2;
			}

			arr[i]=val;
		}
		String dp[][]=new String[n][k+1];

		for(String x[]: dp) {
			Arrays.fill(x, "");
		}

		String ans= B1340helper(0, arr, dp, k, masks, vals);
		if(ans==null) {
			System.out.println(-1);
		}else {
			System.out.println(ans);
		}
	}

	public static String B1340helper(int i, int arr[], String dp[][], int k, int masks[], int vals[]) {

		if(k<0) return null;

		if(i>=arr.length) {

			if(k==0) return"";

			return null;
		}

		if(dp[i][k]!="") {
			return dp[i][k];
		}

		for(int j=9;j>=0;j--) {

			if((arr[i]&masks[j])!=0) {

				continue;
			}

			int required= Integer.bitCount(vals[j]^arr[i]);
			String recAns= B1340helper(i+1, arr, dp, k-required, masks, vals);

			if(recAns!=null) {
				dp[i][k]= j+recAns;
				return dp[i][k];
			}

		}
		dp[i][k]=null;
		return null;

	}
}


import java.io.*;
import java.io.IOException;

import java.util.*;
//import javafx.util.Pair;
//import java.util.concurrent.LinkedBlockingDeque;

//import sun.net.www.content.audio.wav;

   public  class Codeforces {

        public static long mod = (long)Math.pow(10, 9)+7 ;
        public static double epsilon=0.00000000008854;//value of epsilon
        public static InputReader sc = new InputReader(System.in);
        public static PrintWriter pw = new PrintWriter(System.out);

        public static long gcd(long a,long b){
            while(b>0){
                long t=b;
                b=a%b;
                a=t;
            }
            return a;
        }
        public static int fun(int v[][],int n,int k,int dp[][]){
            if(v.length==n){
                if(k==0)
                return 0;
                else return -1;
            }
            if(k<0){
                return -1;
            }
            if(dp[n][k]>-2){
                return dp[n][k];
            }
            for(int i=9;i>=0;i--){
                if(v[n][i]!=-1&&fun(v, n+1, k-v[n][i],dp)!=-1){
                    return dp[n][k]=i;
                }
            }
            return dp[n][k]=-1;
        }
        public static void main(String[] args) {
            // code starts..
            int n=sc.nextInt();
            int k=sc.nextInt();
            String s[]=scanStrings(n);
            String num[]={ "1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011"};
            int vnum[][]=new int[n][10];
            for(int i=0;i<n;i++){
                for(int j=0;j<10;j++){
                    for(int p=0;p<7;p++){
                        if(s[i].charAt(p)=='1'&&num[j].charAt(p)=='0'){
                            vnum[i][j]=-1;
                            break;
                        }
                        if(s[i].charAt(p)=='0'&&num[j].charAt(p)=='1'){
                            vnum[i][j]++;
                        }
                    }
                }
            }
            int dp[][]=new int[n][k+1];
            for(int i=0;i<n;i++){
                Arrays.fill(dp[i], -2);
            }
            int t=fun(vnum, 0, k, dp);
            if(t>-1)
            for(int i=0;i<n;i++){
                t=dp[i][k];
                pw.print(t);
                k=k-vnum[i][t];
            }
            else pw.println(t);
            // Code ends...
            pw.flush();
            pw.close();
        }

        public static Comparator<Integer[]> column(int i){
            return
            new Comparator<Integer[]>() {
                @Override
                public int compare(Integer[] o1, Integer[] o2) {
                    return o1[i].compareTo(o2[i]);//for ascending
                    //return o2[i].compareTo(o1[i]);//for descending
                }
            };
        }
        public static String reverseString(String s){
            StringBuilder input1 = new StringBuilder();
            input1.append(s);
            input1 = input1.reverse();
            return input1.toString();
        }
        public static int[] scanArray(int n){
            int a[]=new int [n];
            for(int i=0;i<n;i++)
            a[i]=sc.nextInt();

            return a;
        }
        public static long[] scanLongArray(int n){
            long a[]=new long [n];
            for(int i=0;i<n;i++)
            a[i]=sc.nextLong();

            return a;
        }
        public static String [] scanStrings(int n){
            String a[]=new String [n];
            for(int i=0;i<n;i++)
            a[i]=sc.nextLine();

            return a;
        }

    }

    class InputReader {

            private final InputStream stream;
            private final byte[] buf = new byte[8192];
            private int curChar, snumChars;
            private SpaceCharFilter filter;

            public InputReader(InputStream stream) {
                this.stream = stream;
            }

            public int snext() {
                if (snumChars == -1)
                    throw new InputMismatchException();
                if (curChar >= snumChars) {
                    curChar = 0;
                    try {
                        snumChars = stream.read(buf);
                    } catch (IOException e) {
                        throw new InputMismatchException();
                    }
                    if (snumChars <= 0)
                        return -1;
                }
                return buf[curChar++];
            }

            public int nextInt() {
                int c = snext();
                while (isSpaceChar(c)) {
                    c = snext();
                }
                int sgn = 1;
                if (c == '-') {
                    sgn = -1;
                    c = snext();
                }
                int res = 0;
                do {
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    res *= 10;
                    res += c - '0';
                    c = snext();
                } while (!isSpaceChar(c));
                return res * sgn;
            }

            public long nextLong() {
                int c = snext();
                while (isSpaceChar(c)) {
                    c = snext();
                }
                int sgn = 1;
                if (c == '-') {
                    sgn = -1;
                    c = snext();
                }
                long res = 0;
                do {
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    res *= 10;
                    res += c - '0';
                    c = snext();
                } while (!isSpaceChar(c));
                return res * sgn;
            }

            public int[] nextIntArray(int n) {
                int a[] = new int[n];
                for (int i = 0; i < n; i++) {
                    a[i] = nextInt();
                }
                return a;
            }

            public String readString() {
                int c = snext();
                while (isSpaceChar(c)) {
                    c = snext();
                }
                StringBuilder res = new StringBuilder();
                do {
                    res.appendCodePoint(c);
                    c = snext();
                } while (!isSpaceChar(c));
                return res.toString();
            }

            public String nextLine() {
                int c = snext();
                while (isSpaceChar(c))
                    c = snext();
                StringBuilder res = new StringBuilder();
                do {
                    res.appendCodePoint(c);
                    c = snext();
                } while (!isEndOfLine(c));
                return res.toString();
            }

            public boolean isSpaceChar(int c) {
                if (filter != null)
                    return filter.isSpaceChar(c);
                return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
            }

            private boolean isEndOfLine(int c) {
                return c == '\n' || c == '\r' || c == -1;
            }

            public interface SpaceCharFilter {
                public boolean isSpaceChar(int ch);
            }
        }


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Locale;
import java.util.StringTokenizer;

public class Solution implements Runnable {

	public static final int BITS = 7;
	public static final String[] CODES = {"1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011"};

	public static final String IMPOSSIBLE = "-1";

	private PrintStream out;
	private BufferedReader in;
	private StringTokenizer st;

	public void solve() throws IOException {
		long time0 = System.currentTimeMillis();

		int n = nextInt();
		int k = nextInt();
		String[] code = new String[n];
		for (int i = 0; i < n; i++) {
			code[i] = next();
		}
		String answer = solve(n, k, code);
		out.println(answer);

		System.err.println("time: " + (System.currentTimeMillis() - time0));
	}

	private String solve(int n, int k, String[] code) {
		int[][] trans = precalcTrans();
		int[] digits = new int[n];
		for (int i = 0; i < n; i++) {
			digits[i] = decode(code[i]);
		}
		int[][] a = new int[n + 1][k + 1];
		a[n][k] = 777;
		for (int i = n; i > 0; i--) {
			int[] t = trans[digits[i - 1]];
			for (int d = 0; d < t.length; d++) {
				if (t[d] != -1) {
					for (int j = t[d]; j <= k; j++) {
						if (a[i][j] > 0) {
							a[i - 1][j - t[d]] = Math.max(a[i - 1][j - t[d]], 10 + d);
						}
					}
				}
			}
		}
		if (a[0][0] == 0) {
			return IMPOSSIBLE;
		}
		char[] result = new char[n];
		int kk = 0;
		for (int i = 0; i < n; i++) {
			int d = a[i][kk] - 10;
			result[i] = (char) ('0' + d);
			kk = kk + trans[digits[i]][d];
		}
		return new String(result);
	}

	private int[][] precalcTrans() {
		int[] digits = new int[CODES.length];
		for (int i = 0; i < CODES.length; i++) {
			digits[i] = decode(CODES[i]);
		}
		int[][] result = new int[1 << BITS][CODES.length];
		for (int mask = 0; mask < result.length; mask++) {
			for (int c = 0; c < CODES.length; c++) {
				if ((mask | digits[c]) == digits[c]) {
					result[mask][c] = countBits(digits[c] ^ mask);
				} else {
					result[mask][c] = -1;
				}
			}
		}
		return result;
	}

	private int countBits(int x) {
		int result = 0;
		while (x > 0) {
			x = x & (x - 1);
			result = result + 1;
		}
		return result;
	}

	private int decode(String s) {
		int result = 0;
		for (int i = 0; i < BITS; i++) {
			if (s.charAt(i) == '1') {
				result |= (1 << i);
			}
		}
		return result;
	}

	public double nextDouble() throws IOException {
		return Double.parseDouble(next());
	}

	public long nextLong() throws IOException {
		return Long.parseLong(next());
	}

	public int nextInt() throws IOException {
		return Integer.parseInt(next());
	}

	public String next() throws IOException {
		while (!st.hasMoreTokens()) {
			String line = in.readLine();
			if (line == null) {
				return null;
			}
			st = new StringTokenizer(line);
		}
		return st.nextToken();
	}

	@Override
	public void run() {
		try {
			solve();
			out.close();
		} catch (Throwable e) {
			throw new RuntimeException(e);
		}
	}

	public Solution(String name) throws IOException {
		Locale.setDefault(Locale.US);
		if (name == null) {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintStream(new BufferedOutputStream(System.out));
		} else {
			in = new BufferedReader(new InputStreamReader(new FileInputStream(name + ".in")));
			out = new PrintStream(new BufferedOutputStream(new FileOutputStream(name + ".out")));
		}
		st = new StringTokenizer("");
	}

	public static void main(String[] args) throws IOException {
		new Thread(new Solution(null)).start();
	}
}