import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintStream;
import java.util.Scanner;

public class Main implements Runnable, AutoCloseable {
    Scanner in = new Scanner(new BufferedInputStream(System.in));
    //    StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    PrintStream out = new PrintStream(new BufferedOutputStream(System.out));

    @Override
    public void run() {
        int t = in.nextInt();
        for (int i = 0; i < t; i++) {
            doOnce();
        }
    }

    private void doOnce() {
        int n = in.nextInt();
        int m = in.nextInt();
        int ansa = in.nextInt();
        for (int i = 1; i < n; i++) {
            int t = Math.min(in.nextInt(), m / i);
            m -= t * i;
            ansa += t;
        }
        out.println(ansa);
    }

    public static void main(String[] args) {
        try (Main main = new Main()) {
            main.run();
        }
    }

    @Override
    public void close() {
        out.close();
    }
}


import java.io.*;
public class test2
{
    public static void main(String args[])throws IOException
    {
        BufferedReader cat=new BufferedReader(new InputStreamReader(System.in));
        int tc=Integer.parseInt(cat.readLine());
        for(int i=0;i<tc;i++)
        {
            String a1=cat.readLine();
            String a11[]=a1.split(" ");
           int  d=Integer.parseInt(a11[1]);
           String hayy=cat.readLine();
           String a111[]=hayy.split(" ");
           int hayy1[]=new int[a111.length];
           for(int j=0;j<a111.length;j++)
           {
               hayy1[j]=Integer.parseInt(a111[j]);
            }
            hay(hayy1,d);

        }
    }
public static void hay(int hayy1[],int d)
    {
        int gg=0;
        int d1=d;
        int hayy[]=new int[hayy1.length];
        hayy=hayy1;
        int len=hayy.length;
        if(len==1)
        System.out.println(hayy[0]);
        else
        {
        while(d1!=0&&gg!=(len-1))
        {
            int i=0;
            while(i<len)
            {
             if(hayy[i+1]!=0)
             {
                 hayy[i]++;
                 hayy[i+1]--;
                 d1--;
                 break;
                }
                else
                {
                    for(int j=1;j<len;j++)
                    {
                       if(hayy[j]!=0)
                       {
                       hayy[j-1]++;
                       hayy[j]--;
                       d1--;
                       break;
                    }
                    else
                    {
                    gg=j;
                }

                    }
                    break;

                }

            }

        }
        System.out.println(hayy[0]);
    }

    }

}


/**
 * ******* Created  on 17/2/20 8:54 PM*******
 */

import java.io.*;
import java.util.*;

public class A1307 implements Runnable {

    private static final int MAX = (int) (1E5 + 5);
    private static final int MOD = (int) (1E9 + 7);
    private static final long Inf = (long) (1E14 + 10);

    private void solve() throws IOException {
        int t = reader.nextInt();
        int[] a = new int[105];
        while(t-- >0){
            int n = reader.nextInt();
            int d = reader.nextInt();
            for(int i=0;i<n;i++){
                a[i]= reader.nextInt();
            }
            while(d >0){
               // writer.println(d);
                int j =1;int i=0;
                while(j < n && a[j]==0)j++;
                d-= (j-i);
                if(j < n && a[j] >0 && d >0) {
                    a[j]--;
                    a[0]++;
                }else{
                    break;
                }
            }
            writer.println(a[0]);
        }
    }

    public static void main(String[] args) throws IOException {
        try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
            new A1307().run();
        }
    }

    StandardInput reader;
    PrintWriter writer;

    @Override
    public void run() {
        try {
            reader = new StandardInput();
            writer = new PrintWriter(System.out);
            solve();
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    interface Input extends Closeable {
        String next() throws IOException;

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

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

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

        default int[] readIntArray() throws IOException {
            return readIntArray(nextInt());
        }

        default int[] readIntArray(int size) throws IOException {
            int[] array = new int[size];
            for (int i = 0; i < array.length; i++) {
                array[i] = nextInt();
            }
            return array;
        }

        default long[] readLongArray(int size) throws IOException {
            long[] array = new long[size];
            for (int i = 0; i < array.length; i++) {
                array[i] = nextLong();
            }
            return array;
        }
    }

    private static class StandardInput implements Input {
        private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        private StringTokenizer stringTokenizer;

        @Override
        public void close() throws IOException {
            reader.close();
        }

        @Override
        public String next() throws IOException {
            if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
                stringTokenizer = new StringTokenizer(reader.readLine());
            }
            return stringTokenizer.nextToken();
        }
    }
}


/**
 * ******* Created  on 17/2/20 8:54 PM*******
 */

import java.io.*;
import java.util.*;

public class A1307 implements Runnable {

    private static final int MAX = (int) (1E5 + 5);
    private static final int MOD = (int) (1E9 + 7);
    private static final long Inf = (long) (1E14 + 10);

    private void solve() throws IOException {
        int t = reader.nextInt();
        int[] a = new int[105];
        while(t-- >0){
            int n = reader.nextInt();
            int d = reader.nextInt();
            for(int i=0;i<n;i++){
                a[i]= reader.nextInt();
            }
            while(d >0){
               // writer.println(d);
                int j =1;int i=0;
                while(j < n && a[j]==0)j++;
                d-= (j-i);
                if(j < n && a[j] >0 && d >=0) {
                    a[j]--;
                    a[0]++;
                }else{
                    break;
                }
            }
            writer.println(a[0]);
        }
    }

    public static void main(String[] args) throws IOException {
        try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
            new A1307().run();
        }
    }

    StandardInput reader;
    PrintWriter writer;

    @Override
    public void run() {
        try {
            reader = new StandardInput();
            writer = new PrintWriter(System.out);
            solve();
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    interface Input extends Closeable {
        String next() throws IOException;

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

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

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

        default int[] readIntArray() throws IOException {
            return readIntArray(nextInt());
        }

        default int[] readIntArray(int size) throws IOException {
            int[] array = new int[size];
            for (int i = 0; i < array.length; i++) {
                array[i] = nextInt();
            }
            return array;
        }

        default long[] readLongArray(int size) throws IOException {
            long[] array = new long[size];
            for (int i = 0; i < array.length; i++) {
                array[i] = nextLong();
            }
            return array;
        }
    }

    private static class StandardInput implements Input {
        private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        private StringTokenizer stringTokenizer;

        @Override
        public void close() throws IOException {
            reader.close();
        }

        @Override
        public String next() throws IOException {
            if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
                stringTokenizer = new StringTokenizer(reader.readLine());
            }
            return stringTokenizer.nextToken();
        }
    }
}


import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CowAndHaybales
{
    public static void main( String [] args )
    {
        Scanner input = new Scanner( System.in );
        int t = input.nextInt();

        for( int i = 0; i < t; i++ )
        {
            List<Integer> list = new ArrayList<>();

            int n = input.nextInt(), d = input.nextInt();
            for( int j = 0; j < n; j++ )
                list.add(input.nextInt());

            int answer = list.get(0);
            for( int j = 1; j < n; j++ )
            {
                int day = d / j;
                int value = list.get(j);

                if( day > 0 && value > 0 )
                {
                    answer += Math.min( day, value );
                    d -= Math.min( day, value ) * j;
                }
            }

            System.out.println(answer);
            list.clear();
        }
    }
}


import java.io.*;
import java.util.*;

/*
 * To execute Java, please define "static void main" on a class
 * named Solution.
 *
 * If you need more classes, simply define them inline.
 */

public class Solution {
  private static int maxHaybales(int[] arr, int d){
    //if(arr.length == 1) return arr[0];
    int count = arr[0];

    for(int i=1;i<arr.length;i++){
      int requiredDays = i-0;
      if(d < requiredDays) break;
      while(arr[i] > 0 && d >= requiredDays){
        count++;
        arr[i]--;
        d-=requiredDays;
      }
    }
    return count;
  }
  public static void main(String[] args) {
    //System.out.println(maxHaybales(new int[]{1,1,1,1,1},3));

    Scanner sc = new Scanner(System.in);

    int tests = sc.nextInt();

    while(tests > 0){

      int n = sc.nextInt();
      int days = sc.nextInt();

      int[] arr = new int[n];
      for(int i=0;i<n;i++){
        arr[i] = sc.nextInt();
      }
      System.out.println(maxHaybales(arr,days));
      tests--;
    }
  }
}

/*
Your previous Plain Text content is preserved below:

1 1 1 1 1

  1d 2d 3d 4d

 */


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.Collections;
import java.util.StringTokenizer;

public class Codeforces1307A {

	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int T = sc.nextInt();
		for (int tt = 0; tt < T; tt++) {
			int n = sc.nextInt();
			int d = sc.nextInt();
			int arr[] = new int[n];
			int k = 0;
			for(int i = 0; i < n; i++) {
				arr[i] = sc.nextInt();
			}
			for(int i = 1; i < n; i++) {
				if((k + arr[i] * (i)) > d) {
					arr[0] += (d - k)/i;
					break;
				}else {
					arr[0] += arr[i];
					k += arr[i]*i;
				}
			}
			System.out.println(arr[0]);
		}

	}

	public void sort(int[] a) {
		ArrayList<Integer> l=new ArrayList<>();
		for (int i:a) l.add(i);
		Collections.sort(l);
		for (int i=0; i<a.length; i++) a[i]=l.get(i);
	}

	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");

		public String next() {
			while (!st.hasMoreElements())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}

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

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

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

}


import java.net.Inet4Address;
import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;

public class Main {
    public static FastIO file = new FastIO();

    private static void solve() {
        int t = nextInt();
        while (t-- > 0) {
            int n = nextInt(), day = nextInt();
            int[] a = nextArray(n);
            for (int i = 0; i < day; i++) {
                for (int j = 0; j < n; j++) {
                    if(j+1 == n) break;
                    if (a[j+1] > 0) {
                        a[j+1]--;
                        a[j]++;
                        break;
                    }
                }
            }
            System.out.println(a[0]);
        }
    }

    private static int[] nextArray(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = nextInt();
        return a;
    }

    public static int[][] nextArray2D(int n, int m) {
        int[][] result = new int[n][];
        for (int i = 0; i < n; i++) {
            result[i] = nextArray(m);
        }
        return result;
    }

    public static long pow(long n, long p) {
        long ret = 1L;
        while (p > 0) {
            if (p % 2 != 0L)
                ret *= n;
            n *= n;
            p >>= 1L;
        }
        return ret;
    }

    public static String next() {
        return file.next();
    }

    public static int nextInt() {
        return file.nextInt();
    }

    public static long nextLong() {
        return file.nextLong();
    }

    public static double nextDouble() {
        return file.nextDouble();
    }

    public static String nextLine() {
        return file.nextLine();
    }

    public static class FastIO {
        BufferedReader br;
        StringTokenizer st;
        PrintWriter out;

        public FastIO() {
            br = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

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

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

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

    }

    public static void main(String[] args) throws IOException {
        solve();
    }

}


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

public class Solution {
    //public static Vector<Vector<Integer> > g = new Vector<Vector<Integer>>();
    public static Vector<Vector<Integer> > buildGraph(int n){
        Vector<Vector<Integer> > g = new Vector<Vector<Integer>>();
        for(int i=0;i<n*n;i++)
        {
            Vector<Integer> t = new Vector<Integer>();
            g.add(t);
        }
        for(int i=0;i<n*n;i++){
            if(i/n>1){
                if(i%n>0){
                    int d = i-1-2*n;
                    g.elementAt(i).add(d);
                    //g.elementAt(d).add(i);
                }
                if(i%n<n-1){
                    int d = i+1-2*n;
                    g.elementAt(i).add(d);
                    //g.elementAt(d).add(i);
                }
            }
            if(i/n<n-2){
                if(i%n>0){
                    int d = i -1 +2*n;
                    g.elementAt(i).add(d);
                    //g.elementAt(d).add(i);
                }
                if(i%n<n-1){
                    int d = i+1+2*n;
                    g.elementAt(i).add(d);
                    //g.elementAt(d).add(i);
                }
            }
            if(i%n>1) {
                int d = i - 2;
                g.elementAt(i).add(d);
                //g.elementAt(d).add(i);
            }
            if(i%n <n-2){
                int d = i+2;
                g.elementAt(i).add(d);
                //g.elementAt(d).add(i);
            }
        }
        return g;
    }
    public static void printGraph(Vector<Vector<Integer> > g){
        for(int i=0;i<g.size();i++){
            System.out.print(""+i+": ");
            for(int j=0;j<g.elementAt(i).size();j++){
                System.out.print(g.elementAt(i).elementAt(j)+" ");
            }
            System.out.println();
        }
    }
    public static int[] vis;
    public static int[] p;
    public static int INF = (1<<31)-1;
    public static void bfs(int s,Vector<Vector<Integer>> g){
        int n = g.size();
        vis = new int[n];
        p = new int[n];
        for(int i=0;i<n;i++)
        {
            vis[i] = INF;
            p[i] = -1;
        }
        vis[s]=0;
        p[s]=-2;
        Queue<Integer> q  = new LinkedList<Integer>();
        q.add(s);
        while(!q.isEmpty()){
            int u = q.peek();
            q.remove();
            for(int i=0;i<g.elementAt(u).size();i++){
                int v = g.elementAt(u).elementAt(i);
                if(vis[v]==INF){
                    vis[v]=vis[u]+1;
                    p[v]=u;
                    q.add(v);
                }
            }
        }
    }
    public static int [] xdir ={-2,-2,0,2,2,0};
    public static int [] ydir = {-1,1,2,1,-1,-2};
    public static String [] labels = {"UL", "UR", "R", "LR", "LL", "L"};
    public static String detectDir(int s,int d,int n){
        for(int i=0;i<labels.length;i++){
            if(s+ydir[i]+n*xdir[i]==d){
                return labels[i];
            }
        }
        return "error";
    }
    public static Vector<String> printPath(int d,int s,int n){
        if(d==s) {
            return new Vector<String>();
        }
        Vector<String> res = printPath(p[d],s,n);
        res.add(detectDir(d,p[d],n));
        return res;
    }
    public static void sol(int is,int js,int id,int jd,int n){
        Vector<Vector<Integer> > g = buildGraph(n);
        bfs(id*n+jd,g);
        if(vis[is*n+js]==INF){
            System.out.println("Impossible");
        }else{
            System.out.println(vis[is*n+js]);
            Vector<String> path = printPath(is*n+js,id*n+jd,n);
            Map<String, Integer> m = new HashMap<String, Integer>();
            for (String s:path){
                if(m.containsKey(s)){
                    m.put(s,m.get(s)+1);
                }else{
                    m.put(s,1);
                }
            }
            boolean first =true;
            for(int i=0;i<labels.length;i++){
                if(m.containsKey(labels[i])){
                    for(int j=0;j<m.get(labels[i]);j++) {
                        if (!first) {
                            System.out.print(" ");
                        } else {
                            first = false;
                        }
                        System.out.print(labels[i]);
                    }
                }
            }
            System.out.println();
            /*for(int i=0;i<path.size();i++){
                if(i!=0)
                    System.out.print(" ");
                System.out.print(path.elementAt(i));
            }*/
        }
    }
    public static void main(String [] args){
       try {
           BufferedReader br  = new BufferedReader(new InputStreamReader(System.in));
           int T = Integer.parseInt(br.readLine());
           while(T!=0) {
               T--;
               String [] words = br.readLine().split(" ");
               int n = Integer.parseInt(words[0]);
               int d = Integer.parseInt(words[1]);
               int [] a = new int[n];
               String []data = br.readLine().split(" ");
               for(int i=0;i<n;i++){
                    a[i] = Integer.parseInt(data[i]);
               }
               int res = a[0];
               int i=1;
               while(d>0 && i<n){
                   int tmp = Math.min(a[i],d/i);
                   if (tmp==0 && a[i]!=0)
                       break;
                   res += tmp;
                   d-=tmp*i;
                   i++;
               }
               System.out.println(res);
           }
       }catch(Exception e){

       }
    }
}


import java.util.Scanner;
public class Cow{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        while(T-- != 0){
            int n = sc.nextInt();
            int d = sc.nextInt();
            int a[] = new int[n];
            int max;
            for(int i = 0; i< d; i++){
                a[i] = sc.nextInt();
            }
            for(int i = 1; i<n; i++){
                while(a[i]> 0){
                    d= d-i;
                    if(d>=0){
                        max = max+1;
                        a[i] = a[i] - 1;
                    }
                    else
                      break;
                }
            }
            System.out.println(a[0] + max);
        }
    }
}


import java.util.Scanner;
public class Cow{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        while(T-- != 0){
            int n = sc.nextInt();
            int d = sc.nextInt();
            int a[] = new int[n];
            int max = 0;
            for(int i = 0; i< n; i++){
                a[i] = sc.nextInt();
            }
            for(int i = 1; i<n; i++){
                while(a[i]> 0){
                    d= d-i;
                    if(d>=0){
                        max = max+1;
                        a[i] = a[i] - 1;
                    }
                    else
                      break;
                }
            }
            System.out.println(a[0] + max);
        }
    }
}


import java.util.Scanner;
public class Cow{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        while(T-- != 0){
            int n = sc.nextInt();
            int d = sc.nextInt();
            int a[] = new int[n];
            int max = 0;
            for(int i = 0; i< d; i++){
                a[i] = sc.nextInt();
            }
            for(int i = 1; i<n; i++){
                while(a[i]> 0){
                    d= d-i;
                    if(d>=0){
                        max = max+1;
                        a[i] = a[i] - 1;
                    }
                    else
                      break;
                }
            }
            System.out.println(a[0] + max);
        }
    }
}


import java.util.Scanner;

public class D1D2A {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for (int i = 0; i <t ; i++) {
            int k=0;
            int n=sc.nextInt();
            int d=sc.nextInt();
            int arr[]=new int[n];
            for (int j = 0; j <arr.length ; j++) {
                arr[j]=sc.nextInt();

            }
            for (int j = 1; j <arr.length ; j++) {
                while(true){
                    if(arr[j]>0){
                        k=k+j;
                    }
                    else{
                        break;
                    }
                    if(k<=d){
                        arr[0]++;
                        arr[j]--;
                    }
                    else
                        break;
                }
                if(k>=d)
                    break;

                }
            System.out.println(arr[0]);
            }
        }
    }


import java.io.*;
import java.util.*;
import java.time.*;
public class Solution{

	public static void main (String[] args)throws IOException {
	    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	    BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
	    int t=Integer.parseInt(br.readLine());
	    while(t-->0)
	    {
	       String str[]=br.readLine().split(" ");
	       int n=Integer.parseInt(str[0]);
	       int d=Integer.parseInt(str[1]);
	       String str1[]=br.readLine().split(" ");
	       int a[]=new int[n];
	       for(int i=0;i<n;i++)
	       {
	           a[i]=Integer.parseInt(str1[i]);
	       }

	       int dtemp=0,res=a[0];
	       for(int i=1;i<n;i++)
	       {
	           if(dtemp>=d)
	           break;
	           int min=Math.min((d-dtemp)/i,a[i]);
	           res=res+min;
	           dtemp=dtemp+min*i;
	       }

	       bw.write(res+"\n");

	    }

	    bw.close();

	}

}


import java.io.PrintWriter;
import java.util.Scanner;

public class CowAndHaybalesA extends PrintWriter {
    //this trick improves performances
    CowAndHaybalesA() {
        super(System.out);
    }

    public static void main(String[] $) {
        CowAndHaybalesA o = new CowAndHaybalesA();
        o.main();
        o.flush();
    }

    void main() {
        Scanner sc = new Scanner(System.in);
        int count = sc.nextInt();
        //use this if just a single test
        //int count = 1;
        main:
        while (count-- > 0) {
            int n = sc.nextInt();
            int d = sc.nextInt();

            int[] halybases = new int[n];
            for (int i = 0; i < n; i++) {
                halybases[i]=sc.nextInt();
            }

            loop: for (int dist = 1; dist < n ; dist++) {
                for (int j = 1; j <=halybases[dist] ; j++) {
                    if(j<=d){
                        d -=dist;
                        halybases[0]++;
                    }else{
                        break loop;
                    }
                }
            }
            println(halybases[0]);
        }
        sc.close();
    }
}


import java.io.PrintWriter;
import java.util.Scanner;

public class CowAndHaybalesA extends PrintWriter {
    //this trick improves performances
    CowAndHaybalesA() {
        super(System.out);
    }

    public static void main(String[] $) {
        CowAndHaybalesA o = new CowAndHaybalesA();
        o.main();
        o.flush();
    }

    void main() {
        Scanner sc = new Scanner(System.in);
        int count = sc.nextInt();
        //use this if just a single test
        //int count = 1;
        main:
        while (count-- > 0) {
            int n = sc.nextInt();
            int d = sc.nextInt();

            int[] halybases = new int[n];
            for (int i = 0; i < n; i++) {
                halybases[i] = sc.nextInt();
            }

            int increase;
            for (int dist = 1; dist < n; dist++) {
                if(d<dist){
                    break;
                }
                increase = Math.min(halybases[dist]*dist, d) / dist;
                d -= increase*dist;
                halybases[0] +=increase;
            }
            println(halybases[0]);
        }
        sc.close();
    }
}


import java.io.PrintWriter;
import java.util.Scanner;

public class CowAndHaybalesA extends PrintWriter {
    //this trick improves performances
    CowAndHaybalesA() {
        super(System.out);
    }

    public static void main(String[] $) {
        CowAndHaybalesA o = new CowAndHaybalesA();
        o.main();
        o.flush();
    }

    void main() {
        Scanner sc = new Scanner(System.in);
        int count = sc.nextInt();
        //use this if just a single test
        //int count = 1;
        main:
        while (count-- > 0) {
            int n = sc.nextInt();
            int d = sc.nextInt();

            int[] halybases = new int[n];
            for (int i = 0; i < n; i++) {
                halybases[i]=sc.nextInt();
            }

            loop: for (int i = 1; i < n ; i++) {
                for (int j = 1; j <=halybases[i] ; j++) {
                    if(j<=d){
                        d -=j;
                        halybases[0]++;
                    }else{
                        break loop;
                    }
                }
            }
            println(halybases[0]);
        }
        sc.close();
    }
}


import java.io.PrintWriter;
import java.util.Scanner;

public class CowAndHaybalesA extends PrintWriter {
    //this trick improves performances
    CowAndHaybalesA() {
        super(System.out);
    }

    public static void main(String[] $) {
        CowAndHaybalesA o = new CowAndHaybalesA();
        o.main();
        o.flush();
    }

    void main() {
        Scanner sc = new Scanner(System.in);
        int count = sc.nextInt();
        //use this if just a single test
        //int count = 1;
        main:
        while (count-- > 0) {
            int n = sc.nextInt();
            int d = sc.nextInt();

            int[] halybases = new int[n];
            for (int i = 0; i < n; i++) {
                halybases[i]=sc.nextInt();
            }

            loop: for (int dist = 1; dist < n ; dist++) {
                for (int j = 1; j <=halybases[dist] ; j++) {
                    if(dist<=d){
                        d -=dist;
                        halybases[0]++;
                    }else{
                        break loop;
                    }
                }
            }
            println(halybases[0]);
        }
        sc.close();
    }
}


import java.util.*;
import java.lang.*;

public class Solution{

	public static void main(String[] args) {

		Scanner in = new Scanner(System.in);
		int t = in.nextInt();

	for(int j = 0 ; j < t ; j++){

		int n = in.nextInt();
		int d = in.nextInt();

		int[] arr = new int[n];

		for(int i  = 0; i < n ; i++)
			arr[i] = in.nextInt();

		int index = 1;

		while(index < n && d > 0){

			if(arr[index] == 0)
			{
				index++;
				continue;
			}

				if(arr[index]*index <= d)
				{
					arr[0] +=arr[index];

					d -= index*arr[index];

				}else{
						//System.out.println("Enter else");
						int x = 0;
						while(index <= d && arr[index]-- > 0){
							d-=index;
							x++;
						}
						arr[0] += x;
						break;

				}

			index++;

		}

		System.out.println(arr[0]);
	}
	}
}


import java.util.*;
import java.lang.*;

public class Solution{

	public static void main(String[] args) {

		Scanner in = new Scanner(System.in);
		int t = in.nextInt();

	for(int j = 0 ; j < t ; j++){

		int n = in.nextInt();
		int d = in.nextInt();

		int[] arr = new int[n];

		for(int i  = 0; i < n ; i++)
			arr[i] = in.nextInt();

		int index = 1;

		while(index < n && d > 0){

			if(arr[index] == 0)
			{
				index++;
				continue;
			}

				if(arr[index]*index < d)
				{
					arr[0] +=arr[index];

					d -= index*arr[index];

				}else{
						//System.out.println("Enter else");
						int x = 0;
						while(index < d && arr[index]-- > 0){
							d-=index;
							x++;
						}
						arr[0] += x;
						break;

				}

			index++;

		}

		System.out.println(arr[0]);
	}
	}
}


import java.io.*;
import java.util.*;

public class longwei {
    public static void main(String[] args) throws IOException {
        Scanner lw = new Scanner(System.in);
        int t;
        t = lw.nextInt();
        int n, d;
        int[] a = new int[101];
        while (t != 0) {
            t--;
            n = lw.nextInt();
            d = lw.nextInt();
            int res = lw.nextInt();
            for (int i = 1; i < n; i++) {
                a[i] = lw.nextInt();
                if(d>=i){
                    res+=Math.min(d/i,a[i]);
                    d-=Math.min(d/i,a[i])*i;
                }
            }
            System.out.println(res);
        }
    }
}


import java.io.*;
import java.util.*;

public class Main {

    static long gcd(long a, long b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);

    }

    static long lcm(long a, long b) {
        long res = 1;
        long gcd = gcd(a, b);
        res *= a / gcd;
        return res *= b;
    }

    static long[][] mem;
    static int[] imp;
    static int[] a, b;
    static ArrayList<Long>[] presum;
    static ArrayList<Integer>[] tree;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        StringTokenizer st;
        int T=Integer.parseInt(br.readLine());
        while(T-->0){
            st=new StringTokenizer(br.readLine());
            int n=Integer.parseInt(st.nextToken());
            int d=Integer.parseInt(st.nextToken());
            int[]a=new int[n];
            st=new StringTokenizer(br.readLine());
            for (int i = 0; i <n ; i++) {
                a[i]=Integer.parseInt(st.nextToken());
            }
            int sum=a[0];
            for (int i = 1; i <n ; i++) {
                int cost=(d/(i))*i;
                cost=Math.min(cost,(i)*a[i]);
                sum+=cost/(i);
                d-=cost;
            }
            out.println(sum);
        }

        out.flush();
    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream s) {
            br = new BufferedReader(new InputStreamReader(s));
        }

        public Scanner(String s) throws FileNotFoundException {
            br = new BufferedReader(new FileReader(new File(s)));
        }

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

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

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

        public String nextLine() throws IOException {
            return br.readLine();
        }

        public boolean ready() throws IOException {
            return br.ready();
        }
    }
}


import java.util.*;
public class A1307 {
    public static void main(String[] args) {
        Scanner sc=new Scanner (System.in);
                int t;

                t=sc.nextInt();
                while(t>0){
                    int n, d;

                    n=sc.nextInt();

                    d=sc.nextInt();
                    int[] a=new int[n];
                    for(int i=0; i<n; i++){

                        a[i]=sc.nextInt();
                    }
                 int res=a[0];
               while(d>0){
                   int sum=0;
                   for(int i=1; i<n; i++){
                       sum+=a[i];
                       if(a[i]>0){
                           a[i]--;

                           d=d-i;
                           if(d>=0){
                               res++;
                           }
                           break;
                       }

                   }
                   if(sum==0){
                       break;
                   }
               }
                  System.out.println(res);
                    t--;

               }

    }
}


import java.util.*;
public class A1307 {
    public static void main(String[] args) {
        Scanner sc=new Scanner (System.in);
                int t;

                t=sc.nextInt();
                while(t>0){
                    int n, d;

                    n=sc.nextInt();

                    d=sc.nextInt();
                    int[] a=new int[n];
                    for(int i=0; i<n; i++){

                        a[i]=sc.nextInt();
                    }
                 int res=a[0];
               while(d>0){
                   int sum=0;
                   for(int i=1; i<n; i++){
                       sum+=a[i];
                       if(a[i]>0){
                           a[i]--;

                           d=d-i;
                           if(d>0){
                               res++;
                           }
                           break;
                       }

                   }
                   if(sum==0){
                       break;
                   }
               }
                  System.out.println(res);
                    t--;

               }

    }
}


public class CowandHaybales{
	public static void main(String args[]){
		java.util.Scanner scan= new java.util.Scanner(System.in);

		int t= scan.nextInt();

		while(t--!=0){
			int n= scan.nextInt();
			int d= scan.nextInt();

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

			for(int i=1;i<n;i++){
				int temp = d- arr[i]*i;
				if(temp<=0){
					arr[0]+= d/i;
					break;
				}else{
					d= d- arr[i]*i;
					arr[0]+= arr[i]*i;
				}
			}

			System.out.println(arr[0]);
		}
	}
}


public class CowandHaybales{
	public static void main(String args[]){
		java.util.Scanner scan= new java.util.Scanner(System.in);

		int t= scan.nextInt();

		while(t--!=0){
			int n= scan.nextInt();
			int d= scan.nextInt();

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

			for(int i=1;i<n;i++){
				int temp = d- arr[i]*i;
				if(temp<=0){
					arr[0]+= d/i;
					break;
				}else{
					d= d- arr[i]*i;
					arr[0]+= arr[i];
				}
			}

			System.out.println(arr[0]);
		}
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int t = in.nextInt();
            while (t-- > 0) {
                int n = in.nextInt();
                int d = in.nextInt();
                int[] a = new int[n];
                for (int i = 0; i < n; i++) {
                    a[i] = in.nextInt();
                }
                loop1:
                for (int i = 1; i < n; i++) {
                    for (int j = 0; j < a[i]; j++) {
                        if (d >= i) {
                            a[0]++;
                            d -= i;
                        } else break loop1;
                    }
                }
                out.println(a[0]);
            }
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int t = in.nextInt();
            while (t-- > 0) {
                int n = in.nextInt();
                int d = in.nextInt();
                int[] a = new int[n];
                for (int i = 0; i < n; i++) {
                    a[i] = in.nextInt();
                }
                loop1:
                for (int i = 1; i < n; i++) {
                    for (int j = 0; j < a[i]; j++) {
                        if (d > i) {
                            a[0]++;
                            d -= i;
                        } else break loop1;
                    }
                }
                out.println(a[0]);
            }
        }

    }
}


import java.util.*;
import java.io.*;
import java.math.BigInteger;

public class Codeforces {

    static class Pair {

        int x;
        int y;

        Pair(int u, int v) {
            x = u;
            y = v;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (!(o instanceof Pair)) {
                return false;
            }
            Pair key = (Pair) o;
            return x == key.x && y == key.y;
        }

        @Override
        public int hashCode() {
            int result = x;
            result = 31 * result + y;
            return result;
        }
    }

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

    static class Comb {

        static long nCr(int n, int k) {
            long C[] = new long[k + 1];

            // nC0 is 1
            C[0] = 1;

            for (int i = 1; i <= n; i++) {
                for (int j = Math.min(i, k); j > 0; j--) {
                    C[j] = C[j] + C[j - 1];
                }
            }
            return C[k];
        }
    }

    static long gcd(long a, long b) {
        if (a == 0) {
            return b;
        }
        return gcd(b % a, a);
    }

    static int search(char[] s, char[] t, int pos) {
        for (int i = pos; i < s.length; i++) {
            if (s[i] == t[pos]) {
                return i;
            }
        }
        return -1;
    }

    static boolean pal(String a, String b) {
        StringBuilder c = new StringBuilder();
        c.append(b);
        b = c.reverse().toString();
        if (a.equals(b)) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) throws IOException {
        int mod = 1000000007;
        /*BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] input = br.readLine().split(" ");
        int n = Integer.parseInt(input[0]);*/
        Reader sc=new Reader();
        int t=sc.nextInt();
        for (int i = 0; i < t; i++) {
            int n=sc.nextInt();
            int d=sc.nextInt();
            int a[]=new int[n];
            for (int j = 0; j < n; j++) {
                a[j]=sc.nextInt();
            }
            if(n==1){
                System.out.println(a[0]);
            }
            else if(d==1){
                if(a[1]!=0){
                    System.out.println(a[0]+1);
                }
                else{
                    System.out.println(a[0]);
                }
            }
            else{
                int j=1;
                while(d>1){
                    while(a[j]==0){
                        j++;
                    }
                    d=d-j;
                    if(d<1||j==n){
                        break;
                    }
                    a[j]--;
                    a[0]++;
                }
                System.out.println(a[0]);
            }
        }
    }
}


def popcount(x):
    x -= (x >> 1) & 0x55
    x = (x & 0x33) + ((x >> 2) & 0x33)
    x = (x + (x >> 4)) & 0xf
    return x & 0xf

def calc(S1, S2):
    T = set()
    for s1 in S1:
        for s2 in S2:
            T.add(s1 + s2)
    return T

D = [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
N, K = map(int, input().split())
X = [int(input(), 2) for _ in range(N)][::-1]
T = [set()]
S = [{0}]
for i, x in enumerate(X):
    s = set()
    for j, d in enumerate(D):
        if d | x == d:
            a = popcount(d) - popcount(x)
            s.add(a)
    T.append(s)
    S.append(calc(S[-1], s))

if K not in S[-1]:
    print(-1)
    exit()

ANS = []
for i in range(N, 0, -1):
    x = X[i-1]
    for j in range(9, -1, -1):
        d = D[j]
        if d | x == d:
            a = popcount(d) - popcount(x)
            if K - a in S[i-1]:
                ANS.append(j)
                K -= a
                break

print("".join(map(str, ANS)))


def popcount(x):
    x -= (x >> 1) & 0x55
    x = (x & 0x33) + ((x >> 2) & 0x33)
    x = (x + (x >> 4)) & 0xf
    return x & 0xf

D = [119, 18, 93, 91, 58, 107, 111, 82, 127, 123]
N, K = map(int, input().split())
X = [int(input(), 2) for _ in range(N)][::-1]
S = [1]
for i, x in enumerate(X):
    pre = S[-1]
    s = 0
    for j, d in enumerate(D):
        if d | x == d:
            a = popcount(d) - popcount(x)
            s |= pre << a
    S.append(s)

if S[-1] >> K & 1 == 0:
    print(-1)
    exit()

ANS = []
for i in range(N, 0, -1):
    x = X[i-1]
    for j in range(9, -1, -1):
        d = D[j]
        if d | x == d:
            a = popcount(d) - popcount(x)
            if K >= a and S[i-1] >> K - a & 1:
                ANS.append(j)
                K -= a
                break

print("".join(map(str, ANS)))


"""
Author: Q.E.D
Time: 2020-04-23 10:50:08
"""
vk = dict(zip(
    range(10),
    ["1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011"]
))
kv = {k:v for v, k in vk.items()}

def transfer(s1, s2):
    reachable = True
    dist = 0
    for x, y in zip(s1, s2):
        if y == '0' and x == '1':
            reachable = False
            break
        elif y == '1' and x == '0':
            dist += 1
    return reachable, dist

n, k = list(map(int, input().split()))
rep = []
for _ in range(n):
    rep.append(input())

target = {}
for i in range(n):
    for j in range(9, -1, -1):
        reachable, dist = transfer(rep[i], vk[j])
        if reachable and dist <= k:
            target[(i, j)] = dist

f = [[-1 for _ in range(k + 1)] for _ in range(n + 1)]
f[n][0] = 1
for j in range(9, -1, -1):
    if (i, j) in target:
        dist = target[(i, j)]
        f[n - 1][dist] = 1
# target = {}
# for i in [n - 1]:# range(n):
#     if rep[i] in kv:
#         f[i][0] = 1#kv[rep[i]] * 10 ** (n - i - 1)
#     for j in range(9, -1, -1):
#         reachable, dist = transfer(rep[i], vk[j])
#         if reachable and dist <= k:
#             target[(i, j)] = dist
#             f[i][dist] = 1#max(f[i][dist], j * 10 ** (n - i - 1))

# print([-1 if r not in kv else kv[r] for r in rep])
# print(target)
# print(f)
for i in range(n - 2, -1, -1):
    for j in range(9, -1, -1):
        # reachable, dist = transfer(rep[i], vk[j])
        # if reachable and dist <= k:
        if (i, j) in target:
            dist = target[(i, j)]
            for w in range(dist, k + 1):
                if f[i + 1][w - dist] == 1:
                    f[i][w] = 1
                #max(f[i][w], f[i - 1][w - dist] + j * 10 ** (n - i - 1))
# print(f)
if f[0][k] == -1:
    print(-1)
else:
    ans = []
    quota = k
    for i in range(n):
        for j in range(9, -1, -1):
            if (i, j) in target:
                dist = target[(i, j)]
                # print(i, j, dist, quota)
                if dist <= quota and f[i + 1][quota - dist] == 1:
                    ans.append(j)
                    quota -= dist
                    break
    print(''.join(map(str, ans)))


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

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

def cost(good, broken):
    ans = 0
    for i in range(7):
        if good[i] == '0' and broken[i] == '1':
            return -1
        if good[i] == '1' and broken[i] == '0':
            ans += 1
    return ans

s = ["{:07b}".format(i) for i in range(128)]
d = ["1110111", "0010010", "1011101", "1011011", "0111010",
     "1101011", "1101111", "1010010", "1111111", "1111011"]
f = [[-1 for i in range(8)] for j in range(128)]
g = [[] for i in range(128)]
lc = []
rc = []
for i in range(128):
    for j in range(10):
        c = cost(d[j], s[i])
        if c == -1:
            continue
        if f[i][c] == -1:
            g[i].append(c)
        f[i][c] = max(f[i][c], j)
    g[i].sort()
    lc.append(g[i][0])
    rc.append(g[i][-1])

n, k = read_ints()
nums = []
total = 0
for i in range(n):
    num = input()
    for stick in num:
        if stick == '1':
            total += 1
    nums.append(int(num, 2))

if total + k > 7 * n:
    print(-1)
else:
    lo = 0
    ls = [0]
    rs = [0]
    for i in range(n):
        ls.append(ls[-1] + lc[nums[i]])
        rs.append(rs[-1] + rc[nums[i]])
    if k < ls[n]:
        print(-1)
    else:
        ans = [-1 for i in range(n)]
        used = 0
        for i in range(n):
            rmin = ls[n] - ls[i + 1]
            rmax = rs[n] - rs[i + 1]
            u = 0
            for j in g[nums[i]]:
                if rmin <= k - used - j <= rmax:
                    if f[nums[i]][j] > ans[i]:
                        ans[i] = f[nums[i]][j]
                        u = j
            used += u
        print(int(''.join(map(str, ans))))


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

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

def cost(good, broken):
    ans = 0
    for i in range(7):
        if good[i] == '0' and broken[i] == '1':
            return -1
        if good[i] == '1' and broken[i] == '0':
            ans += 1
    return ans

s = ["{:07b}".format(i) for i in range(128)]
d = ["1110111", "0010010", "1011101", "1011011", "0111010",
     "1101011", "1101111", "1010010", "1111111", "1111011"]
f = [[-1 for i in range(8)] for j in range(128)]
g = [[] for i in range(128)]
for i in range(128):
    for j in range(10):
        c = cost(d[j], s[i])
        if c == -1:
            continue
        if f[i][c] == -1:
            g[i].append(c)
        f[i][c] = max(f[i][c], j)
    g[i].sort()

n, k = read_ints()
nums = []
total = 0
for i in range(n):
    num = input()
    for stick in num:
        if stick == '1':
            total += 1
    nums.append(int(num, 2))

if total + k > 7 * n:
    print(-1)
else:
    used = [0] * n
    lo = 0
    for i in range(n):
        for j in range(8):
            if f[nums[i]][j] != -1:
                used[i] = j
                lo += j
                break
    if k < lo:
        print(-1)
    else:
        dp = [-1 for i in range(k + 1)]
        dp[0] = 0
        for i in range(n):
            ndp = [-1 for i in range(k + 1)]
            for j in range(k + 1):
                if dp[j] == -1:
                    continue
                for h in g[nums[i]]:
                    if j + h > k:
                        break
                    ndp[j + h] = max(ndp[j + h], dp[j] * 10 + f[nums[i]][h])
            dp = ndp
        print(dp[k])


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

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

def cost(good, broken):
    ans = 0
    for i in range(7):
        if good[i] == '0' and broken[i] == '1':
            return -1
        if good[i] == '1' and broken[i] == '0':
            ans += 1
    return ans

s = ["{:07b}".format(i) for i in range(128)]
d = ["1110111", "0010010", "1011101", "1011011", "0111010",
     "1101011", "1101111", "1010010", "1111111", "1111011"]
f = [[-1 for i in range(8)] for j in range(128)]
g = [[] for i in range(128)]
lc = []
rc = []
for i in range(128):
    for j in range(10):
        c = cost(d[j], s[i])
        if c == -1:
            continue
        if f[i][c] == -1:
            g[i].append(c)
        f[i][c] = max(f[i][c], j)
    g[i].sort()
    lc.append(g[i][0])
    rc.append(g[i][-1])

n, k = read_ints()
nums = []
total = 0
for i in range(n):
    num = input()
    for stick in num:
        if stick == '1':
            total += 1
    nums.append(int(num, 2))

if total + k > 7 * n:
    print(-1)
else:
    used = [0] * n
    lo = 0
    ls = [0]
    rs = [0]
    for i in range(n):
        ls.append(ls[-1] + lc[nums[i]])
        rs.append(rs[-1] + rc[nums[i]])
    if k < ls[n]:
        print(-1)
    else:
        dp = [-1 for i in range(k + 1)]
        dp[0] = 0
        for i in range(n):
            ndp = [-1 for i in range(k + 1)]
            for j in range(k + 1):
                if dp[j] == -1 or k - j > rs[n] - rs[i] or k - j < ls[n] - ls[i]:
                    continue
                for h in g[nums[i]]:
                    if j + h > k:
                        break
                    ndp[j + h] = max(ndp[j + h], dp[j] * 10 + f[nums[i]][h])
            dp = ndp
        print(dp[k])


# ------------------- 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.copy())
    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.copy())
dict1=dp0[-1]
if k in dict1:
    print(dict1[k])
else:
    print(-1)


# ------------------- 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):
    v0=[k for k in input()]
    vals.append(v0)
#representation of n=0,...,9
rep=['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
#use a 2d DP
dict1={}
for s in range(n):
    str1=vals[s]
    if s==0:
        #initialise the dp
        for b in range(9,-1,-1):
            count=0;broke=False
            for i in range(7):
                if str1[i]!=rep[b][i]:
                    if str1[i]=="1":
                        broke=True
                        break
                    else:
                        count+=1
            if broke==False:
                if not(count in dict1):
                    dict1[count]=b*10**(n-1-s)
                else:
                    dict1[count]=max(dict1[count],b*10**(n-1-s))
    else:
        dict2={}
        for b in range(9,-1,-1):
            count=0;broke=False
            for i in range(7):
                if str1[i]!=rep[b][i]:
                    if str1[i]=="1":
                        broke=True
                        break
                    else:
                        count+=1
            if broke==False:
                for i in dict1.keys():
                    sum1=i+count
                    if sum1<=2000:
                        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)
        dict1=dict2
if k in dict1:
    print(dict1[k])
else:
    print(-1)


# ------------------- 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):
    v0=[k for k in input()]
    vals.append(v0)
#representation of n=0,...,9
rep=['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
#use a 2d DP
dict1={}
for s in range(n):
    str1=vals[s]
    if s==0:
        #initialise the dp
        for b in range(9,-1,-1):
            count=0;broke=False
            for i in range(7):
                if str1[i]!=rep[b][i]:
                    if str1[i]=="1":
                        broke=True
                        break
                    else:
                        count+=1
            if broke==False:
                if not(count in dict1):
                    dict1[count]=b*10**(n-1-s)
                else:
                    dict1[count]=max(dict1[count],b*10**(n-1-s))
    else:
        dict2={}
        for b in range(9,-1,-1):
            count=0;broke=False
            for i in range(7):
                if str1[i]!=rep[b][i]:
                    if str1[i]=="1":
                        broke=True
                        break
                    else:
                        count+=1
            if broke==False:
                for i in dict1.keys():
                    sum1=i+count
                    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)
        dict1=dict2
if k in dict1:
    print(dict1[k])
else:
    print(-1)


# ------------------- 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):
    v0=[k for k in input()]
    vals.append(v0)
#representation of n=0,...,9
rep=['1110111', '0010010', '1011101', '1011011', '0111010', '1101011', '1101111', '1010010', '1111111', '1111011']
#use a 2d DP
dict1={}
for s in range(n):
    str1=vals[s]
    if s==0:
        #initialise the dp
        for b in range(9,-1,-1):
            count=0;broke=False
            for i in range(7):
                if str1[i]!=rep[b][i]:
                    if str1[i]=="1":
                        broke=True
                        break
                    else:
                        count+=1
            if broke==False:
                if not(count in dict1):
                    dict1[count]=str(b)
                else:
                    dict1[count]=str(max(int(dict1[count]),b))
    else:
        dict2={}
        for b in range(9,-1,-1):
            count=0;broke=False
            for i in range(7):
                if str1[i]!=rep[b][i]:
                    if str1[i]=="1":
                        broke=True
                        break
                    else:
                        count+=1
            if broke==False:
                for i in dict1.keys():
                    sum1=i+count
                    if not(sum1 in dict2):
                        dict2[sum1]=dict1[i]+str(b)
                    else:
                        num1=int(dict1[i]+str(b))
                        num2=int(dict2[sum1])
                        dict2[sum1]=str(max(num1,num2))
        dict1=dict2
if k in dict1:
    print(dict1[k])
else:
    print(-1)


# ------------------- 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.copy())
        dict1.clear()
    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.copy())
        dict2.clear()
dict1=dp0[-1]
if k in dict1:
    print(dict1[k])
else:
    print(-1)


# ------------------- 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)
#the cost of turning them into some digit; the value of that digit
cost=[[] for s in range(n)];nums=[[] for s in range(n)]
for s in range(n):
    int1=vals[s];found=set([])
    for b in range(9,-1,-1):
        count=0;broke=False;int2=rep[b];joined=int1^int2
        if (joined |int2)==int2:
            count=bin(joined).count("1")
        else:
            broke=True
        if broke==False and not(count in found):
            found.add(count);cost[s].append(count);nums[s].append(b)
dp=[[0 for s in range(k+1)] for s in range(n)]
#loop from behind
dp[n-1][k]=1
previous=set([k])
broke=False
for s in range(n-2,-1,-1):
    new=set([])
    for i in range(len(cost[s+1])):
        for b in previous:
            if b-cost[s+1][i]>=0:
                new.add(b-cost[s+1][i])
                dp[s][b-cost[s+1][i]]=1
    if len(new)==0:
        broke=True
        break
    else:
        previous=new
cv=0
for s in range(len(cost[0])):
    if cost[0][s]<=k and dp[0][cost[0][s]]==1:
        continue
    else:
        cv+=1
if cv==len(cost[0]):
    broke=True
if broke==False:
    cumsum=0
    ans=[]
    for s in range(n):
        for b in range(len(cost[s])):
            if cumsum+cost[s][b]<=k and dp[s][cumsum+cost[s][b]]==1:
                ans.append(str(nums[s][b]))
                cumsum+=cost[s][b]
                break
    print("".join(ans))
else:
    print(-1)


# ------------------- 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)
#the cost of turning them into some digit; the value of that digit
cost=[[] for s in range(n)];nums=[[] for s in range(n)]
for s in range(n):
    int1=vals[s];found=set([])
    for b in range(9,-1,-1):
        count=0;broke=False;int2=rep[b];joined=int1^int2
        if (joined |int2)==int2:
            count=bin(joined).count("1")
        else:
            broke=True
        if broke==False and not(count in found):
            found.add(count);cost[s].append(count);nums[s].append(b)
dp=[[0 for s in range(k+1)] for s in range(n)]
#loop from behind
dp[n-1][k]=1
previous=set([k])
broke=False
for s in range(n-2,-1,-1):
    new=set([])
    for i in range(len(cost[s])):
        for b in previous:
            if b-cost[s][i]>=0:
                new.add(b-cost[s][i])
                dp[s][b-cost[s][i]]=1
    if len(new)==0:
        broke=True
        break
    else:
        previous=new
if broke==False:
    cumsum=0
    ans=[]
    for s in range(n):
        for b in range(len(cost[s])):
            if cumsum+cost[s][b]<=k and dp[s][cumsum+cost[s][b]]==1:
                ans.append(str(nums[s][b]))
                cumsum+=cost[s][b]
                break
    print("".join(ans))
else:
    print(-1)


# ------------------- 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={}
        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 dict1.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)
dict1=dp0[-1]
if k in dict1:
    print(dict1[k])
else:
    print(-1)


# ------------------- 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={}
        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 dict1.keys():
                    sum1=i+count
                    if sum1<=2000:
                        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)
dict1=dp0[-1]
if k in dict1:
    print(dict1[k])
else:
    print(-1)


# ------------------- 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
dict1={}
for s in range(n):
    int1=vals[s]
    if s==0:
        #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:
                if not(count in dict1):
                    dict1[count]=b*10**(n-1-s)
                else:
                    dict1[count]=max(dict1[count],b*10**(n-1-s))
    else:
        dict2={}
        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:
                for i in dict1.keys():
                    sum1=i+count
                    if sum1<=2000:
                        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)
        dict1=dict2
if k in dict1:
    print(dict1[k])
else:
    print(-1)


# ------------------- 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:
                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={}
        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:
                for i in dict1.keys():
                    sum1=i+count
                    if sum1<=2000:
                        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)
dict1=dp0[-1]
if k in dict1:
    print(dict1[k])
else:
    print(-1)


# ------------------- 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)
#the cost of turning them into some digit; the value of that digit
cost=[[] for s in range(n)];nums=[[] for s in range(n)]
for s in range(n):
    int1=vals[s];found=set([])
    for b in range(9,-1,-1):
        count=0;broke=False;int2=rep[b];joined=int1^int2
        if (joined |int2)==int2:
            count=bin(joined).count("1")
        else:
            broke=True
            break
        if broke==False and not(count in found):
            found.add(count);cost[s].append(count);nums[s].append(b)
dp=[[0 for s in range(k+1)] for s in range(n)]
#loop from behind
dp[n-1][k]=1
previous=set([k])
broke=False
for s in range(n-2,-1,-1):
    new=set([])
    for i in range(len(cost[s])):
        for b in previous:
            if b-cost[s][i]>=0:
                new.add(b-cost[s][i])
                dp[s][b-cost[s][i]]=1
    if len(new)==0:
        broke=True
        break
    else:
        previous=new
if broke==False:
    cumsum=0
    ans=[]
    for s in range(n):
        for b in range(len(cost[s])):
            if cumsum+cost[s][b]<=k and dp[s][cumsum+cost[s][b]]==1:
                ans.append(str(nums[s][b]))
                cumsum+=cost[s][b]
                break
    print("".join(ans))
else:
    print(-1)