import java.io.*;
import java.util.*;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class NastyaAndScoreboard {
    static int n;
    static int[][] changes;
    static int[][][] dp;
    static StringBuilder ans = new StringBuilder();

    public static void main(String[] args)throws Exception {

        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastInput in = new FastInput(inputStream);
        FastOutput out = new FastOutput(outputStream);

        char[][] digit = new char[10][8];
        dp = new int[11][2005][2005];
        for (int[][] x : dp) {
            for (int[] y : x) {
                Arrays.fill(y, -1);
            }
        }

        for (int i = 0; i < 10; i++) {
            String str = "01111111";
            for (int j = 0; j < 8; j++) {
                digit[i] = str.toCharArray();
            }
        }
        digit[0][4] = '0';
        digit[1][1] = digit[1][2] = digit[1][4] = digit[1][5] = digit[1][7] = '0';
        digit[2][2] = digit[2][6] = '0';
        digit[3][2] = digit[3][5] = '0';
        digit[4][1] = digit[4][5] = digit[4][7] = '0';
        digit[5][3] = digit[5][5] = '0';
        digit[6][3] = '0';
        digit[7][2] = digit[7][4] = digit[7][5] = digit[7][7] = '0';
        digit[9][5] = '0';

        String[] digits = new String[10];

        for (int i = 0; i < 10; i++) {
            StringBuilder str = new StringBuilder();
            for (int j = 0; j < 8; j++) {
                str.append(digit[i][j]);
            }
            digits[i] = str.toString();
        }

        n = in.readInt();
        int k = in.readInt();
        String[] cal = new String[n];
        for (int i = 0; i < n; i++) {
            cal[i] = '0' + in.readString();
        }

        changes = new int[10][2005];

        for (int i = 9; i >= 0; i--) {
            for (int ind = 0; ind < n; ind++) {
                int cnt = 0;
                String s1 = digits[i];
                String s2 = cal[ind];

                for (int j = 0; j < 8; j++) {
                    if (s1.charAt(j) == '1' && s2.charAt(j) == '0') {
                        cnt++;
                    } else if (s1.charAt(j) == '0' && s2.charAt(j) == '1') {
                        cnt = -1;
                        break;
                    }
                }
                changes[i][ind] = cnt;
            }
        }

        int val = compute(0, k, 0);

        findans(0, k, 0);
        if (ans.length() == 0) {
            out.println("-1");
        } else {
            out.println(ans.toString());
        }
        out.flush();
    }

    public static void findans(int ind, int sum, int num) {
        if (ind == n)
            return;

        for (int i = 9; i >= 0; i--) {
            int cnt = changes[i][ind];
            if (sum - cnt >= 0 && cnt != -1 && dp[i][ind + 1][sum - cnt] == 1) {
                char c = (char) (48 + i);
                ans.append(c);
                findans(ind + 1, sum - changes[i][ind], i);
                return;
            }
        }
    }

    public static int compute(int ind, int sum, int num) {

        if (ind == n) {
            if (sum == 0) {
                return dp[num][ind][sum] = 1;
            }
            return dp[num][ind][sum] = 0;
        }

        if (sum < 0)
            return dp[num][ind][sum] = 0;

        if (dp[num][ind][sum] != -1)
            return dp[num][ind][sum];

        int maxi = 0;

        for (int i = 9; i >= 0; i--) {
            int cnt = changes[i][ind];
            char c = (char) (48 + i);
            if (cnt != -1 && cnt <= sum)
                maxi = Math.max(maxi, compute(ind + 1, sum - cnt, i));
        }
        return dp[num][ind][sum] = maxi;
    }

    static class FastInput {
        private final InputStream is;
        private StringBuilder defaultStringBuf = new StringBuilder(1 << 13);
        private byte[] buf = new byte[1 << 20];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

        public String readString(StringBuilder builder) {
            skipBlank();

            while (next > 32) {
                builder.append((char) next);
                next = read();
            }

            return builder.toString();
        }

        public String readString() {
            defaultStringBuf.setLength(0);
            return readString(defaultStringBuf);
        }

    }

    static class FastOutput implements AutoCloseable, Closeable, Appendable {
        private StringBuilder cache = new StringBuilder(1 << 20);
        private final Writer os;

        public FastOutput append(CharSequence csq) {
            cache.append(csq);
            return this;
        }

        public FastOutput append(CharSequence csq, int start, int end) {
            cache.append(csq, start, end);
            return this;
        }

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(int c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(String c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(String c) {
            return append(c).println();
        }

        public FastOutput println() {
            cache.append(System.lineSeparator());
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

    static class Bits {
        private Bits() {
        }

        public static int bitAt(int x, int i) {
            return (x >>> i) & 1;
        }

    }

}


//package Problemset.Tag.DynamicProgramming;

import java.io.*;
import java.util.*;
import java.io.IOException;
public class NastyaAndScoreboard {
    static int n;
    static int[][] changes;
    static int[][][] dp;
    static StringBuilder ans = new StringBuilder();

    public static void main(String[] args)throws Exception {

        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastInput in = new FastInput(inputStream);
        FastOutput out = new FastOutput(outputStream);

        char[][] digit = new char[10][8];
        dp = new int[11][2005][2005];
        for (int[][] x : dp) {
            for (int[] y : x) {
                Arrays.fill(y, -1);
            }
        }

        for (int i = 0; i < 10; i++) {
            String str = "01111111";
            for (int j = 0; j < 8; j++) {
                digit[i] = str.toCharArray();
            }
        }
        digit[0][4] = '0';
        digit[1][1] = digit[1][2] = digit[1][4] = digit[1][5] = digit[1][7] = '0';
        digit[2][2] = digit[2][6] = '0';
        digit[3][2] = digit[3][5] = '0';
        digit[4][1] = digit[4][5] = digit[4][7] = '0';
        digit[5][3] = digit[5][5] = '0';
        digit[6][3] = '0';
        digit[7][2] = digit[7][4] = digit[7][5] = digit[7][7] = '0';
        digit[9][5] = '0';

        String[] digits = new String[10];

        for (int i = 0; i < 10; i++) {
            StringBuilder str = new StringBuilder();
            for (int j = 0; j < 8; j++) {
                str.append(digit[i][j]);
            }
            digits[i] = str.toString();
        }

        n = in.readInt();
        int k = in.readInt();
        String[] cal = new String[n];
        for (int i = 0; i < n; i++) {
            cal[i] = '0' + in.readString();
        }

        changes = new int[10][2005];

        for (int i = 9; i >= 0; i--) {
            for (int ind = 0; ind < n; ind++) {
                int cnt = 0;
                String s1 = digits[i];
                String s2 = cal[ind];

                for (int j = 0; j < 8; j++) {
                    if (s1.charAt(j) == '1' && s2.charAt(j) == '0') {
                        cnt++;
                    } else if (s1.charAt(j) == '0' && s2.charAt(j) == '1') {
                        cnt = -1;
                        break;
                    }
                }
                changes[i][ind] = cnt;
            }
        }

        int val = compute(0, k, 0);

        findans(0, k, 0);
        if (ans.length() == 0) {
            out.println("-1");
        } else {
            out.println(ans.toString());
        }
        out.flush();
    }

    public static void findans(int ind, int sum, int num) {
        if (ind == n)
            return;

        for (int i = 9; i >= 0; i--) {
            int cnt = changes[i][ind];
            if (sum - cnt >= 0 && cnt != -1 && dp[i][ind + 1][sum - cnt] == 1) {
                char c = (char) (48 + i);
                ans.append(c);
                findans(ind + 1, sum - changes[i][ind], i);
                return;
            }
        }
    }

    public static int compute(int ind, int sum, int num) {

        if (ind == n) {
            if (sum == 0) {
                return dp[num][ind][sum] = 1;
            }
            return dp[num][ind][sum] = 0;
        }

        if (sum < 0)
            return dp[num][ind][sum] = 0;

        if (dp[num][ind][sum] != -1)
            return dp[num][ind][sum];

        int maxi = 0;

        for (int i = 9; i >= 0; i--) {
            int cnt = changes[i][ind];
            char c = (char) (48 + i);
            if (cnt != -1 && cnt <= sum)
                maxi = Math.max(maxi, compute(ind + 1, sum - cnt, i));
        }
        return dp[num][ind][sum] = maxi;
    }

    static class FastInput {
        private final InputStream is;
        private StringBuilder defaultStringBuf = new StringBuilder(1 << 13);
        private byte[] buf = new byte[1 << 20];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

        public String readString(StringBuilder builder) {
            skipBlank();

            while (next > 32) {
                builder.append((char) next);
                next = read();
            }

            return builder.toString();
        }

        public String readString() {
            defaultStringBuf.setLength(0);
            return readString(defaultStringBuf);
        }

    }

    static class FastOutput implements AutoCloseable, Closeable, Appendable {
        private StringBuilder cache = new StringBuilder(1 << 20);
        private final Writer os;

        public FastOutput append(CharSequence csq) {
            cache.append(csq);
            return this;
        }

        public FastOutput append(CharSequence csq, int start, int end) {
            cache.append(csq, start, end);
            return this;
        }

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(int c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(String c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(String c) {
            return append(c).println();
        }

        public FastOutput println() {
            cache.append(System.lineSeparator());
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

}


//package Problemset.Tag.DynamicProgramming;

import java.io.*;
import java.util.*;
import java.io.IOException;
public class NastyaAndScoreboard {
    static int n;
    static int[][] changes;
    static int[][][] dp;
    static StringBuilder ans = new StringBuilder();

    public static void main(String[] args)throws Exception {

        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastInput in = new FastInput(inputStream);
        FastOutput out = new FastOutput(outputStream);

        char[][] digit = new char[10][8];
        dp = new int[11][2005][2005];
        for (int[][] x : dp) {
            for (int[] y : x) {
                Arrays.fill(y, -1);
            }
        }

        for (int i = 0; i < 10; i++) {
            String str = "01111111";
            for (int j = 0; j < 8; j++) {
                digit[i] = str.toCharArray();
            }
        }
        digit[0][4] = '0';
        digit[1][1] = digit[1][2] = digit[1][4] = digit[1][5] = digit[1][7] = '0';
        digit[2][2] = digit[2][6] = '0';
        digit[3][2] = digit[3][5] = '0';
        digit[4][1] = digit[4][5] = digit[4][7] = '0';
        digit[5][3] = digit[5][5] = '0';
        digit[6][3] = '0';
        digit[7][2] = digit[7][4] = digit[7][5] = digit[7][7] = '0';
        digit[9][5] = '0';

        String[] digits = new String[10];

        for (int i = 0; i < 10; i++) {
            StringBuilder str = new StringBuilder();
            for (int j = 0; j < 8; j++) {
                str.append(digit[i][j]);
            }
            digits[i] = str.toString();
        }

        n = in.readInt();
        int k = in.readInt();
        String[] cal = new String[n];
        for (int i = 0; i < n; i++) {
            cal[i] = '0' + in.readString();
        }

        changes = new int[10][2005];

        for (int i = 9; i >= 0; i--) {
            for (int ind = 0; ind < n; ind++) {
                int cnt = 0;
                String s1 = digits[i];
                String s2 = cal[ind];

                for (int j = 0; j < 8; j++) {
                    if (s1.charAt(j) == '1' && s2.charAt(j) == '0') {
                        cnt++;
                    } else if (s1.charAt(j) == '0' && s2.charAt(j) == '1') {
                        cnt = -1;
                        break;
                    }
                }
                changes[i][ind] = cnt;
            }
        }

        int val = compute(0, k, 0);

        findans(0, k, 0);
        if (ans.length() == 0) {
            out.println("-1");
        } else {
            out.println(ans.toString());
        }
        out.flush();
    }

    public static void findans(int ind, int sum, int num) {
        if (ind == n)
            return;

        for (int i = 9; i >= 0; i--) {
            int cnt = changes[i][ind];
            if (sum - cnt >= 0 && cnt != -1 && dp[sum - cnt][ind + 1][i] == 1) {
                char c = (char) (48 + i);
                ans.append(c);
                findans(ind + 1, sum - changes[i][ind], i);
                return;
            }
        }
    }

    public static int compute(int ind, int sum, int num) {

        if (ind == n) {
            if (sum == 0) {
                return dp[sum][ind][num] = 1;
            }
            return dp[sum][ind][num] = 0;
        }

        if (sum < 0)
            return dp[sum][ind][num] = 0;

        if (dp[num][ind][sum] != -1)
            return dp[sum][ind][num];

        int maxi = 0;

        for (int i = 9; i >= 0; i--) {
            int cnt = changes[i][ind];
            char c = (char) (48 + i);
            if (cnt != -1 && cnt <= sum)
                maxi = Math.max(maxi, compute(ind + 1, sum - cnt, i));
        }
        return dp[sum][ind][num] = maxi;
    }

    static class FastInput {
        private final InputStream is;
        private StringBuilder defaultStringBuf = new StringBuilder(1 << 13);
        private byte[] buf = new byte[1 << 20];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

        public String readString(StringBuilder builder) {
            skipBlank();

            while (next > 32) {
                builder.append((char) next);
                next = read();
            }

            return builder.toString();
        }

        public String readString() {
            defaultStringBuf.setLength(0);
            return readString(defaultStringBuf);
        }

    }

    static class FastOutput implements AutoCloseable, Closeable, Appendable {
        private StringBuilder cache = new StringBuilder(1 << 20);
        private final Writer os;

        public FastOutput append(CharSequence csq) {
            cache.append(csq);
            return this;
        }

        public FastOutput append(CharSequence csq, int start, int end) {
            cache.append(csq, start, end);
            return this;
        }

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(int c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(String c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(String c) {
            return append(c).println();
        }

        public FastOutput println() {
            cache.append(System.lineSeparator());
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

}


import sys
t=int(sys.stdin.readline())
for _ in range(t):
    n,p,k=map(int,sys.stdin.readline().split())
    prices=list(map(int,sys.stdin.readline().split()))
    prices.sort()
    print(prices,'prices',p)
    i,j,count=n-1,0,0
    ans=0
    if n==1:
        if prices[0]<=p:
            ans=1
    if n==2:
        if prices[-1]<=p:
            ans=2
        elif prices[0]<=p:
            ans=1
    while j<=i-2:
        #print(i,j,p,'ij')
        if p>=prices[i]:
            p-=prices[i]
            z=True
            while j>=i-1 and j>=0:
                p+=prices[j]
                j-=1
                count-=1
            while j<i-1 and p>0 and z:
                if p>=prices[j]:
                    p-=prices[j]
                    j+=1
                    count+=1
                else:
                    z=False
            print(count,'count',i,'i')
            ans=max(ans,count+2)
            p+=prices[i]
        i-=1
    if ans==0:
        i=0
        while p>=prices[i]:
            count+=1
            p-=prices[i]
            i+=1
        ans=max(ans,count)
    print(ans)


import sys
t=int(sys.stdin.readline())
for _ in range(t):
    n,p,k=map(int,sys.stdin.readline().split())
    prices=list(map(int,sys.stdin.readline().split()))
    prices.sort()
    i,j,count=n-1,0,0
    ans=0
    if n==1:
        if prices[0]<=p:
            ans=1
    if n==2:
        if prices[-1]<=p:
            ans=2
        elif prices[0]<=p:
            ans=1
    while j<=i-2:
        #print(i,j,p,'ij')
        if p>=prices[i]:
            p-=prices[i]
            z=True
            while j>=i-1 and j>=0:
                p+=prices[j]
                j-=1
                count-=1
            while j<i-1 and p>0 and z:
                if p>=prices[j]:
                    p-=prices[j]
                    j+=1
                    count+=1
                else:
                    z=False
            #print(count,'count',i,'i')
            ans=max(ans,count+2)
            p+=prices[i]
        i-=1
    print(ans)


def search(nums,tar):
    #print(nums,'nums')
    #print(tar,'tar')
    l,r=0,len(nums)-2
    while l<=r:
        mid=(l+r)//2
        if nums[mid]==tar:
            return mid
        elif nums[mid]<tar:
            l=mid+1
        else:
            r=mid-1
    #print(l,'l')
    if nums[l]>tar:
        return l-1
    return l
import sys
t=int(sys.stdin.readline())
for _ in range(t):
    n,p,k=map(int,sys.stdin.readline().split())
    prices=list(map(int,sys.stdin.readline().split()))
    prices.sort()
    cost=[prices[0]]
    for i in range(1,n):
        cost.append(prices[i]+cost[i-1])
    #print(prices,'prices',p)
    #print(cost,'cost')
    if k>=n:
        #print(x)
        ans=0
        for i in range(n):
            if p>=prices[i]:
                ans+=1
        print(ans)
    else:
        i,z=k,True
        ans=0
        while i<n and z:
            #print(i,'i')
            c=0
            if p>=prices[i]:
                c+=k
                c+=search([-1]+cost[:i-k+1]+[float('inf')],p-prices[i])
                ans=max(c,ans)
                i+=1
                #print(c,'c')
            else:
                z=False
        print(ans)


def get(tar,nums):
    #print(tar,nums)
    l,r=0,len(nums)-1
    while l<=r:
        mid=(l+r)//2
        if nums[mid]==tar:
            return mid
        if nums[mid]>tar:
            r=mid-1
        if nums[mid]<tar:
            l=mid+1
    return l-1
import sys
t=int(sys.stdin.readline())
for _ in range(t):
    n,p,k=map(int,sys.stdin.readline().split())
    prices=list(map(int,sys.stdin.readline().split()))
    prices.sort()
    cost=[0]
    temp,i=p,0
    ans=0
    while i<n and temp>=prices[i]:
        temp-=prices[i]
        cost.append(prices[i]+cost[-1])
        ans+=1
        i+=1
    i=k-1
    temp=p
    #print(cost,'cost')
    while i<n and temp>=prices[i]:
        temp-=prices[i]
        x=get(temp,cost[:i-k+2])
        ans=max(ans,x+k)
        temp+=prices[i]
        i+=1
    print(ans)


import sys
t=int(sys.stdin.readline())
for _ in range(t):
    n,p,k=map(int,sys.stdin.readline().split())
    prices=list(map(int,sys.stdin.readline().split()))
    prices.sort()
    i,j,count=n-1,0,0
    ans=0
    if n==1:
        if prices[0]<=p:
            ans=1
    if n==2:
        if prices[-1]<=p:
            ans=2
        elif prices[0]<=p:
            ans=1
    while j<=i-2:
        #print(i,j,p,'ij')
        if p>=prices[i]:
            p-=prices[i]
            z=True
            while j<i-1 and p>0 and z:
                if p>=prices[j]:
                    p-=prices[j]
                    j+=1
                    count+=1
                else:
                    z=False
            #print(count,'count',i,'i')
            ans=max(ans,count+2)
            p+=prices[i]
        i-=1
    print(ans)


from collections import Counter,deque,defaultdict,OrderedDict,namedtuple
from bisect import bisect_left,bisect_right,insort
from math import sqrt,ceil,floor,factorial,gcd
from sys import stdin

t=int(stdin.readline())
while t:
    n,p,k=map(int,stdin.readline().split())
    a=list(map(int,stdin.readline().split()))
    a.sort()
    ans=0
    mx=0
    p_=p
    for i in range(n-1,-1,-2):
        if p>=a[i]:
            p-=a[i]
            mx=mx+2 if i>0 else mx+1
    ans=max(ans,mx)

    p=p_
    mx=0
    for i in range(0,n,2):
        if p>=a[i]:
            p-=a[i]
            mx=mx+2 if i>0 else mx+1
    ans=max(ans,mx)

    p=p_
    mx=0
    for i in range(n-2,-1,-2):
        if p>=a[i]:
            p-=a[i]
            mx=mx+2 if i>0 else mx+1
    ans=max(ans,mx)

    p=p_
    mx=0
    for i in range(1,n,2):
        if p>=a[i]:
            p-=a[i]
            mx=mx+2 if i>0 else mx+1
    ans=max(ans,mx)

    print(ans)

    t-=1


from collections import Counter,deque,defaultdict,OrderedDict,namedtuple
from bisect import bisect_left,bisect_right,insort
from math import sqrt,ceil,floor,factorial,gcd
from sys import stdin

t=int(stdin.readline())
while t:
    n,p,k=map(int,stdin.readline().split())
    a=list(map(int,stdin.readline().split()))
    a.sort()
    mx=0
    p_=p
    for i in range(n-1,-1,-2):
        if p>=a[i]:
            p-=a[i]
            mx=mx+2 if i>0 else mx+1
    p=p_
    ans=mx
    mx=0
    for i in range(n-2,-1,-2):
        if p>=a[i]:
            p-=a[i]
            mx=mx+2 if i>0 else mx+1
    ans=max(ans,mx)

    print(ans)

    t-=1


import sys
input = sys.stdin.readline

Q = int(input())
Query = []
for _ in range(Q):
    N, P, K = map(int, input().split())
    A = list(map(int, input().split()))
    Query.append((N, P, K, A))

for N, P, K, A in Query:
    A.sort()
    DP = [0]*N
    ans = 0
    for i, a in enumerate(A):
        if i == 0:
            DP[i] = a
        elif i < K-1:
            DP[i] = DP[i-1] + a
        else:
            DP[i] = DP[i-K] + a
        if DP[i] <= P:
            ans = i+1
    print(ans)


from math import *
from collections import *
import sys
sys.setrecursionlimit(10**9)
t = int(input())
for y in range(t):
	n,p,k = map(int,input().split())
	a = list(map(int,input().split()))
	a.sort()
	ct = 0
	for i in range(2,n,2):
		if(a[i] <= p):
			ct += 2
			p -= a[i]
	if(ct == 0 and a[1] <= p): ct = 2
	elif(a[0] <= p): ct += 1
	print(ct)


from math import *
from collections import *
import sys
sys.setrecursionlimit(10**9)
t = int(input())
for y in range(t):
	n,p,k = map(int,input().split())
	a = list(map(int,input().split()))
	a.sort()
	ct = ct1 = 0
	p1 = p
	for i in range(2,n,2):
		if(a[i] <= p):
			ct += 2
			p -= a[i]
	if(ct == 0 and a[1] <= p): ct = 2
	elif(a[0] <= p): ct += 1
	for i in range(1,n,2):
		if(a[i] <= p1):
			ct1 += 2
			p1 -= a[i]
	print(max(ct,ct1))


t = int(input())
for _ in range(t):
    n, p, k = map(int, input().split())
    a = list(map(int, input().split()))
    odd_sum = [0] * (n+2)
    even_sum = [0] * (n+2)
    for i in range(n):
        if i % 2 == 0:
            odd_sum[i+2] = a[i] + odd_sum[i]
        else:
            even_sum[i+2] += a[i] + even_sum[i]
    m = 0
    for i in range(n):
        if i % 2 == 0:
            if odd_sum[i+2] <= p:
                m = i+1
        else:
            if even_sum[i+2] <= p:
                m = i+1
    print(m)


t = int(input())
for _ in range(t):
    n, p, k = map(int, input().split())
    a = list(map(int, input().split()))
    a.sort()
    odd_sum = [0] * (n+2)
    even_sum = [0] * (n+2)
    for i in range(n):
        if i % 2 == 0:
            odd_sum[i+2] = a[i] + odd_sum[i]
        else:
            even_sum[i+2] += a[i] + even_sum[i]
    m = 0
    for i in range(n):
        if i % 2 == 0:
            if odd_sum[i+2] <= p:
                m = i+1
        else:
            if even_sum[i+2] <= p:
                m = i+1
    print(m)


t = int(input())
for i in range(t):
    n, p, k = map(int, input().split())
    mas = list(map(int, input().split()))
    mas.sort()
    l = 0
    r = n
    def check(m):
        if m % 2 != 0:
            return mas[0] + sum(mas[m//2 + 1:m ]) <= p
        else:
            return sum(mas[m // 2:m]) <= p
    while(r - l > 1):
        m = (l + r) // 2
        if check(m):
            l = m
        else:
            r = m
    if check(r):
        print(r)
        continue
    if check(l):
        print(l)
        continue
    print(0)


sas = [1,2,3]
t = int(input())
for i in range(t):
    n, p, k = map(int, input().split())
    mas = list(map(int, input().split()))
    mas.sort()
    l = 0
    r = n
    def check(m):
        if m % 2 != 0:
            sm = 0
            i = 2
            while(i < m):
                sm += mas[i]
                i += 2
            return mas[0] + sm <= p
        else:
            sm = 0
            i = 1
            while(i < m):
                sm += mas[i]
                i += 2
            return sm <= p
    while(r - l > 1):
        m = (l + r) // 2
        if check(m):
            l = m
        else:
            r = m
    if check(r):
        print(r)
        continue
    if check(l):
        print(l)
        continue
    print(0)


for t in range (int(input())) :
    n,p,k=map(int,input().split())
    a=list(map(int,input().split()))
    a.sort()
    sum1=[0,a[0]]
    for i in range (1,n) :
        sum1.append(sum1[-2]+a[i])
    for i in range (n+1) :
        if sum1[i]<=p :
            ans=i
    print(ans)


import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

for _ in range(inp()):
    n,p,k = inpl()
    a = inpl()
    a.sort()
    aa = [0] * n
    now = 0
    for i in range(n)[::2]:
        now += a[i]
        aa[i] = now
    now = 0
    for i in range(1,n)[::2]:
        now += a[i]
        aa[i] = now
    for i in range(n):
        if aa[i] > p:
            print(i)
            break
    else:
        print(n)


import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

for _ in range(inp()):
    n,p,k = inpl()
    a = inpl()
    a.sort()
    aa = list(itertools.accumulate(a))
    for i in range(n):
        if aa[i] > p:
            if i == 0:
                print(0)
            else: print(i+1)
            break
    else:
        print(n)


import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

for _ in range(inp()):
    n,p,k = inpl()
    a = inpl()
    a.sort()
    aa = list(itertools.accumulate(a))
    for i in range(1,n):
        aa[i] -= a[i-1]
    for i in range(n):
        if aa[i] > p:
            print(i)
            break
    else:
        print(n)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    a=list(map(int,input().split()))
    a=sorted(a)
    ans=0
    sm=0
    ct=0
    for i in range(k+1):
        if i>=len(a)
            break
        if sm>p:
            break
        ct=i
        pseudocost=sm
        j=i+k-1
        while j<n:
            if p>=pseudocost+a[j]:
                pseudocost+=a[j]
                ct+=k
            else:
                break
            j+=k
        sm+=a[i]
        ans=max(ans,ct)

    print(ans)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    a=list(map(int,input().split()))
    a=sorted(a)
    ans=0
    sm=0
    ct=0
    for i in range(k+1):
        if sm>p:
            break
        ct=i
        pseudocost=sm
        for j in range(i+k-1,n,k):
            if p>=pseudocost+a[j]:
                pseudocost+=a[j]
                ct+=k
            else:
                break
        sm+=a[i]
        ans=max(ans,ct)

    print(ans)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    a=list(map(int,input().split()))
    b=sorted(a)
    ans=0
    sm=0
    ct=0
    for i in range(k+1):
        if sm>p:
            break
        ct=i
        pseudocost=sm
        for j in range(i+k-1,n,k):
            if p>=pseudocost+a[j]:
                pseudocost+=a[j]
                ct+=k
            else:
                break
        sm+=a[i]
        ans=max(ans,ct)

    print(ans)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    a=list(map(int,input().split()))
    a=sorted(a)
    ans=0
    sm=0
    ct=0
    for i in range(k+1):
        if sm>p:
            break
        ct=i
        pseudocost=sm
        j=i+k-1
        while j<n:
            if p>=pseudocost+a[j]:
                pseudocost+=a[j]
                ct+=k
            else:
                break
            j+=k
        sm+=a[i]
        ans=max(ans,ct)

    print(ans)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    a=list(map(int,input().split()))
    a=sorted(a)
    ans=0
    sm=0
    ct=0
    for i in range(k+1):
        if i>=len(a):
            break
        if sm>p:
            break
        ct=i
        pseudocost=sm
        j=i+k-1
        while j<n:
            if p>=pseudocost+a[j]:
                pseudocost+=a[j]
                ct+=k
            else:
                break
            j+=k
        sm+=a[i]
        ans=max(ans,ct)

    print(ans)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    a=list(map(int,input().split()))
    a=sorted(a)
    ans=0
    sm=0
    ct=0
    for i in range(k+1):
        if i>=len(a);
            break
        if sm>p:
            break
        ct=i
        pseudocost=sm
        j=i+k-1
        while j<n:
            if p>=pseudocost+a[j]:
                pseudocost+=a[j]
                ct+=k
            else:
                break
            j+=k
        sm+=a[i]
        ans=max(ans,ct)

    print(ans)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    a=list(map(int,input().split()))
    b=sorted(a)
    ans=0
    ct=0
    sm=0
    j=0
    while sm<p and j+k<=n:
        if sm+a[j+k-1]<=p:
            ans+=k
            sm+=a[j+k-1]
            j+=k
        else:
            break
    for i in range(k):
        j=i+1
        lans=1
        lsm=a[i]
        if a[i]>p:
            continue

        while lsm<p and j+k<=n:
            if lsm+a[j+k-1]<=p:
                lans+=k
                lsm+=a[j+k-1]
                j+=k
            else:
                break
        ct=max(ct,lans)
    print(max(ans,ct))


N = int(input())
for _ in range(N):
    n, p, k = map(int, input().split())
    ap = p
    items = list(map(int, input().split()))
    items.sort()
    ans = 0
    i = 1
    while i < n:
        if items[i] <= p:
            ans += 2
            p -= items[i]
            i += 2
        else:
            break
    if i-1 < n and items[i-1] <= p:
        ans += 1
    aans = 0
    i = 2
    while i < n:
        if items[i] <= ap:
            aans += 2
            ap -= items[i]
            i += 2
        else:
            break
    if items[0] <= ap:
        aans += 1
    ans = max(ans, aans)
    print(ans)


N = int(input())
for _ in range(N):
    n, p, k = map(int, input().split())
    ap = p
    items = list(map(int, input().split()))
    items.sort()
    ans = 0
    for i in range(1,n,2):
        if items[i] <= p:
            ans += 2
            p -= items[i]
        else:
            break
    if items[i-1] <= p:
        ans += 1
    aans = 0
    for i in range(2,n,2):
        if items[i] <= ap:
            aans += 2
            ap -= items[i]
        else:
            break
    if items[0] <= ap:
        aans += 1

    ans = max(ans, aans)
    print(ans)


N = int(input())
for _ in range(N):
    n, p, k = map(int, input().split())
    ap = p
    items = list(map(int, input().split()))
    items.sort()
    ans = 0
    i = 1
    while i < n:
        if items[i] <= p:
            ans += 2
            p -= items[i]
            i += 2
        else:
            break
    if i-1 < N and items[i-1] <= p:
        ans += 1
    aans = 0
    i = 2
    while i < n:
        if items[i] <= ap:
            aans += 2
            ap -= items[i]
            i += 2
        else:
            break
    if items[0] <= ap:
        aans += 1
    ans = max(ans, aans)
    print(ans)


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
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")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=10**9+7
EPS=1e-6
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

def possible(x):

    start=x%k
    ans=sum(a[:start])

    need=x//k
    ind=start+k-1
    for i in range(need):
        ans+=a[ind]
        ind+=k

    # print(ans,x)
    return ans<=p

for _ in range(Int()):

    n,p,k=value()
    a=sorted(array())

    # print(*a)

    low=0
    high=n

    while(low<=high):

        mid=low+(high-low)//2

        if(possible(mid)):
            ans=mid
            low=mid+1
        else:
            high=mid-1

    print(ans)


t=int(input())
for _ in range(t):
    n,p,k=map(int,input().split())
    arr=sorted(list(map(int,input().split())))
    even=[]
    odd=[]
    f=0
    for i in range(n):
        if arr[i]>p:
            n=i+1
            break
        if i %2==0:
            even+=[arr[i]]
        else:
            odd+=[arr[i]]

    if n%2==0:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()

    else:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()

    if f==1:
        print(ans)
    else:
        if even!=[]:
            even1=sum(even)
            if even1<=p:
                print(1)
            else:
                print(0)
        else:
            print(0)


t=int(input())
for _ in range(t):
    n,p,k=map(int,input().split())
    arr=sorted(list(map(int,input().split())))
    even=[]
    odd=[]
    f=0
    for i in range(n):
        if arr[i]>p:
            break
        if i %2==0:
            even+=[arr[i]]
        else:
            odd+=[arr[i]]
    if even==[] and odd==[]:
        print(0)
        continue
    if n%2==0:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()
            if even<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
    else:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()

    if f==1:
        print(ans)
    else:
        if odd!=[]:
            odd1=sum(odd)
            if odd1<=p:
                print(1)
            else:
                print(0)
        elif even!=[]:
            even1=sum(even)
            if even1<=p:
                print(1)
            else:
                print(0)
        else:
            print(0)


t=int(input())
for _ in range(t):
    n,p,k=map(int,input().split())
    arr=sorted(list(map(int,input().split())))
    even=[]
    odd=[]
    f=0
    for i in range(n):
        if arr[i]>p:
            break
        if i %2==0:
            even+=[arr[i]]
        else:
            odd+=[arr[i]]

    if n%2==0:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
    else:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()

    if f==1:
        print(ans)
    else:
        if even!=[]:
            even1=sum(even)
            if even1<=p:
                print(2)
            else:
                print(0)
        else:
            print(0)


t=int(input())
for _ in range(t):
    n,p,k=map(int,input().split())
    arr=sorted(list(map(int,input().split())))
    even=[]
    odd=[]
    f=0
    for i in range(n):
        if arr[i]>p:
            break
        if i %2==0:
            even+=[arr[i]]
        else:
            odd+=[arr[i]]

    if n%2==0:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
    else:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()

    if f==1:
        print(ans)
    else:
        if odd!=[]:
            odd1=sum(odd)
            if odd1<=p:
                print(1)
            else:
                print(0)
        elif even!=[]:
            even1=sum(even)
            if even1<=p:
                print(1)
            else:
                print(0)
        else:
            print(0)


t=int(input())
for _ in range(t):
    n,p,k=map(int,input().split())
    arr=sorted(list(map(int,input().split())))
    even=[]
    odd=[]
    f=0
    for i in range(n):
        if arr[i]>p:
            break
        if i %2==0:
            even+=[arr[i]]
        else:
            odd+=[arr[i]]

    if n%2==0:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
    else:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()

    if f==1:
        print(ans)
    else:
        if even!=[]:
            even1=sum(even)
            if even1<=p:
                print(1)
            else:
                print(0)
        else:
            print(0)


t=int(input())
for _ in range(t):
    n,p,k=map(int,input().split())
    arr=sorted(list(map(int,input().split())))
    even=[]
    odd=[]
    f=0
    for i in range(n):
        if arr[i]>p:
            n=i+1
            break
        if i %2==0:
            even+=[arr[i]]
        else:
            odd+=[arr[i]]

    if n%2==0:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
            print([odd,even])
    else:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()

    if f==1:
        print(ans)
    else:
        if even!=[]:
            even1=sum(even)
            if even1<=p:
                print(1)
            else:
                print(0)
        else:
            print(0)


t=int(input())
for _ in range(t):
    n,p,k=map(int,input().split())
    arr=sorted(list(map(int,input().split())))
    even=[]
    odd=[]
    f=0
    for i in range(n):
        if arr[i]>p:
            break
        if i %2==0:
            even+=[arr[i]]
        else:
            odd+=[arr[i]]

    if n%2==0:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
    else:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()

    if f==1:
        if ans==1:
            print(2)
        else:
            print(ans)
    else:
        if even!=[]:
            even1=sum(even)
            if even1<=p:
                print(1)
            else:
                print(0)
        else:
            print(0)


t=int(input())
for _ in range(t):
    n,p,k=map(int,input().split())
    arr=sorted(list(map(int,input().split())))
    even=[]
    odd=[]
    f=0
    for i in range(n):
        if arr[i]>p:
            break
        if i %2==0:
            even+=[arr[i]]
        else:
            odd+=[arr[i]]

    if n%2==0:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
    else:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()

    if f==1:
        print(ans)
    else:
        if odd!=[]:
            odd1=sum(odd)
            if odd1<=p:
                print(2)
            else:
                print(1)
        elif even!=[]:
            even1=sum(even)
            if even1<=p:
                print(1)
            else:
                print(0)
        else:
            print(0)


t=int(input())
for _ in range(t):
    n,p,k=map(int,input().split())
    arr=sorted(list(map(int,input().split())))
    even=[]
    odd=[]
    f=0
    for i in range(n):
        if arr[i]>p:
            n=i
            break
        if i %2==0:
            even+=[arr[i]]
        else:
            odd+=[arr[i]]

    if n%2==0:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()

    else:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()

    if f==1:
        print(ans)
    else:
        if even!=[]:
            even1=sum(even)
            if even1<=p:
                print(1)
            else:
                print(0)
        else:
            print(0)


t=int(input())
for _ in range(t):
    n,p,k=map(int,input().split())
    arr=sorted(list(map(int,input().split())))
    even=[]
    odd=[]
    f=0
    for i in range(n):
        if arr[i]>p:
            break
        if i %2==0:
            even+=[arr[i]]
        else:
            odd+=[arr[i]]
    if even==[] and odd==[]:
        print(0)
        continue
    if n%2==0:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()
            if even<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
    else:
        odd1=sum(odd)
        even1=sum(even)
        while(even!=[] and odd!=[]):
            f=0
            if even1<=p:
                f=1
                ans=len(even)*2-1
                break
            even1-=even.pop()
            if odd1<=p:
                f=1
                ans=len(odd)*2
                break
            odd1-=odd.pop()

    if f==1:
        print(ans)
    else:
        if odd!=[]:
            odd1=sum(odd)
            if odd1<=p:
                print(1)
            else:
                print(0)
        if even!=[]:
            even1=sum(even)
            if even1<=p:
                print(1)
            else:
                print(0)


#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=tf-8
#

"""
"""

from operator import itemgetter

t = int(input())

def solve(n,p,k,a):
    cnt = [0 for i in range(k)]
    remain = [p for i in range(k)]
    for i in range(1,k):
        remain[i] = remain[i] - a[i-1]
        if remain[i] >= 0:
            cnt[i] += 1
    for i in range(k,n+1):
        b = i % k
        remain[b] = remain[b] - a[i-1]
        if remain[b] >= 0:
            cnt[b] += k
    print(max(cnt))

for i in range(t):
    n, p, k = map(int,input().split())
    a = list(map(int,input().split()))
    a.sort()
    solve(n,p,k,a)


#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=tf-8
#

"""
"""

from operator import itemgetter

t = int(input())

def solve(n,p,k,a):
    cnt = [0 for i in range(k)]
    remain = [p for i in range(k)]
    for i in range(1,k):
        remain[i] = remain[i] - a[i-1]
        if remain[i] >= 0:
            cnt[i] += 1
    for i in range(k,n+1):
        b = i % k
        remain[b] = remain[b] - a[i-1]
        if remain[b] >= 0:
            cnt[b] += k
    print(max(cnt))

for i in range(t):
    n, p, k = map(int,input().split())
    a = list(map(int,input().split()))
    solve(n,p,k,a)


def find(a,s,c):
    n = len(a)
    for i in range(1,n,2):
        if a[i]<=s:
            s-=a[i]
            c+=2
        else:
            break
    return c

t = int(input())
while(t>0):
    n,s,k  =[int(i) for i in input().split()]
    a = [int(i) for i in input().split()]
    a = sorted(a)
    if a[0]>s:
        print(0)
    else:
        m  = max(find(a[1:],s-a[0],1),find(a,s,0))
        print(m)
    t-=1


t  = int(input())
while(t>0):
    n,p,k= [int(i) for i in input().split()]
    a= [int(i) for i in input().split()]
    a = sorted(a)
    c = 0
    f  =0
    for i in range(n):
        if a[i]<=p:
            c+=1
            p-=a[i]
            f  = 1
        else:
            if f==1:
                if p+a[i-1]>=a[i]:
                    c+=1
            break
    print(c)
    t-=1


t  = int(input())
while(t>0):
    n,p,k= [int(i) for i in input().split()]
    a= [int(i) for i in input().split()]
    a = sorted(a)
    c = 0
    f  =0
    for i in range(n):
        if a[i]<=p:
            c+=1
            p-=a[i]
            f  = 1
        else:
            break
    if f==1:
        if i!=n-1:
            c+=1
    else:
        c = 0
    print(c)
    t-=1


t  = int(input())
while(t>0):
    n,p,k= [int(i) for i in input().split()]
    a= [int(i) for i in input().split()]
    a = sorted(a)
    c = 0
    f  =0
    d = 0
    for i in range(n):
        if a[i]<=p:
            c+=1
            p-=a[i]
            f  = 1
        else:
            d= 1
            break
    if f==1:
        if d==1:
            c+=1
    else:
        c = 0
    print(c)
    t-=1


t  = int(input())
while(t>0):
    n,p,k= [int(i) for i in input().split()]
    a= [int(i) for i in input().split()]
    a = sorted(a)
    c = 0
    f  =0
    for i in range(n):
        if a[i]<=p:
            c+=1
            p-=a[i]
            f  = 1
        else:
            if f==1:
                if p+a[i-1]>=a[i]:
                    if i+1!= n and p+a[i-1]>=a[i+1]:
                        c+=2
                    else:
                        c+=1
            break
    print(c)
    t-=1


t  = int(input())
while(t>0):
    n,p,k= [int(i) for i in input().split()]
    a= [int(i) for i in input().split()]
    a = sorted(a)
    c = 0
    f  =0
    d = 0
    for i in range(n):
        if a[i]<=p:
            c+=1
            p-=a[i]
            f  = 1
        else:
            if f==1:
                c+=1
            break
    print(c)
    t-=1


t  = int(input())
while(t>0):
    n,p,k= [int(i) for i in input().split()]
    a= [int(i) for i in input().split()]
    a = sorted(a)
    c = 0
    f  =0
    d = 0
    for i in range(n):
        if a[i]<=p:
            c+=1
            p-=a[i]
            f  = 1
        else:
            c+=1
            break
    print(c)
    t-=1


for _ in range(int(input())):
    n,p,k = (int(x) for x in input().strip().split())
    arr = [int(x) for x in input().strip().split()]
    if p<min(arr):
        print(0)
        continue
    arr = sorted(arr)
    cnt = 0
    if k<n:
        if p>arr[k]:
            cnt += k
            for i in range(k,n):
                p = p - arr[k]
                if p>0:
                    cnt += 1
                else:
                    break
        elif p==arr[k]:
            cnt += k + 1
        else:
            for i in arr:
                p = p - i
                if p>=0:
                    cnt += 1
                else:
                    break
    else:
        for i in arr:
            p = p - i
            if p>=0:
                cnt += 1
                if cnt<k:
                    p = p + i
            else:
                break
    print(cnt)


for _ in range(int(input())):
    n,p,k = (int(x) for x in input().strip().split())
    arr = [int(x) for x in input().strip().split()]
    if p<min(arr):
        print(0)
        continue
    arr = sorted(arr)
    cnt = 0
    if k<n:
        if p>arr[k]:
            cnt += k
            for i in range(k,n):
                p = p - arr[k]
                if p>0:
                    cnt += 1
                else:
                    break
        elif p==arr[k]:
            cnt += k + 1
        else:
            for i in arr:
                p = p - i
                if p>=0:
                    cnt += 1
                    if cnt<k:
                        p = p + i
                else:
                    break
    else:
        for i in arr:
            p = p - i
            if p>=0:
                cnt += 1
                if cnt<k:
                    p = p + i
            else:
                break
    print(cnt)


for _ in range(int(input())):
    n,p,k = (int(x) for x in input().strip().split())
    arr = [int(x) for x in input().strip().split()]  # 2 3 4 5 7
    if p<min(arr):
        print(0)
        continue
    arr.sort()
    cnt = 0
    temp = p
    t = []
    for i in range(k):
        for j in range(i,n,k):
            p = p - arr[j]
            if p>=0:
                if j==0:
                    cnt += 1
                else:
                    cnt += 2
            else:
                break
        t.append(cnt)
        cnt = 0
        p = temp
    print(max(t))


for _ in range(int(input())):
    n,p,k = (int(x) for x in input().strip().split())
    arr = [int(x) for x in input().strip().split()]
    if p<min(arr):
        print(0)
        continue
    arr = sorted(arr)
    cnt = 0
    if k<n:
        if p>arr[k]:
            cnt += k
            for i in range(k,n):
                p = p - arr[k]
                if p>0:
                    cnt += 1
                else:
                    break
        elif p==arr[k]:
            cnt += k + 1
        else:
            for i in arr:
                p = p - i
                if p>=0:
                    cnt += 1
                else:
                    break
    else:
        for i in arr:
            p = p - i
            if p>=0:
                cnt += 1
            else:
                break
    print(cnt)


t=int(input())
ans=[]
for kk in range(t):
    n,p,k=[int(a) for a in input().split()]
    goods=[int(a) for a in input().split()]
    goods.sort()
    i=0
    while 1:
        t=sum(goods[i::-2])
        if p-t<0:
            break
        i+=1
    t=len(goods[i-1::-1])
    ans.append(t)

for i in ans:
    print(i)


t=int(input())
ans=[]
for kk in range(t):
    n,p,k=[int(a) for a in input().split()]
    goods=[int(a) for a in input().split()]
    goods.sort()
    i=0
    while 1:
        t=sum(goods[i::-2])
        if p-t<0:
            break
        i+=1
    t=len(goods[i-1::-1])
    print(t)


t=int(input())
ans=[]
for kk in range(t):
    n,p,k=list(map(int,input().split()))
    goods=list(map(int,input().split()))
    goods.sort()

    for i in range(n+1):
        t=sum(goods[i::-2])
        if p-t<0:
            break
    t=i
    ans.append(t)

for i in ans:
    print(i)


t=int(input())
ans=[]
for kk in range(t):
    n,p,k=list(map(int,input().split()))
    goods=list(map(int,input().split()))
    goods.sort()

    for i in range(0,n+1,2):
        t=sum(goods[i::-2])
        if p-t<0:
            break
    if p-sum(goods[i-1::-2])>=0:
        t=i
    else:
        t=i-1
    print(t)


t=int(input())
ans=[]
for kk in range(t):
    n,p,k=[int(a) for a in input().split()]
    goods=[int(a) for a in input().split()]
    goods.sort()

    for i in range(n+1):
        t=sum(goods[i::-2])
        if p-t<0:
            break
        i+=1
    t=i
    ans.append(t)

for i in ans:
    print(i)


t=int(input())
ans=[]
for kk in range(t):
    n,p,k=list(map(int,input().split()))
    goods=list(map(int,input().split()))
    goods.sort()
    flag=0
    for i in range(0,n+1,3):
        k=sum(goods[i::-2])
        if p-k<0:
            flag=1
            break

    if flag==1:
        k=0
        if p-sum(goods[i-1::-2])>=0:
            k=i
        elif p-sum(goods[i-2::-2])>=0:
            k=i-1
        elif p-sum(goods[i-3::-2])>=0:
            k=i-2
    else:
        k=n
    print(k)


t=int(input())
ans=[]
for kk in range(t):
    n,p,k=[int(a) for a in input().split()]
    goods=[int(a) for a in input().split()]
    goods.sort()

    for i in range(n+1):
        t=sum(goods[i::-2])
        if p-t<0:
            break
    t=i
    ans.append(t)

for i in ans:
    print(i)


t=int(input())
ans=[]
for kk in range(t):
    n,p,k=list(map(int,input().split()))
    goods=list(map(int,input().split()))
    goods.sort()
    flag=0
    for i in range(0,n+1,2):
        k=sum(goods[i::-2])
        if p-k<0:
            flag=1
            break

    if flag==1:
        k=0
        if p-sum(goods[i-1::-2])>=0:
            k=i
        elif p-sum(goods[i-2::-2])>=0:
            k=i-1
    else:
        k=n
    print(k)


t=int(input())
ans=[]
for kk in range(t):
    n,p,k=[int(a) for a in input().split()]
    goods=[int(a) for a in input().split()]
    goods.sort()
    i=0
    while 1:
        t=sum(goods[i::-2])
        if p-t<0:
            break
        i+=1
    t=i
    ans.append(t)

for i in ans:
    print(i)


t=int(input())
ans=[]
for kk in range(t):
    n,p,k=list(map(int,input().split()))
    goods=list(map(int,input().split()))
    goods.sort()

    for i in range(n+1):
        t=sum(goods[i::-2])
        if p-t<0:
            break
    t=i
    print(t)


t=int(input())
ans=[]
for kk in range(t):
    n,p,k=list(map(int,input().split()))
    goods=list(map(int,input().split()))
    goods.sort()

    for i in range(0,n+1,2):
        t=sum(goods[i::-2])
        if p-t<0:
            break
    if p-sum(goods[i-1::-2])>=0:
        t=i
    else:
        t=i-1

    print(t)


t=int(input())
ans=[]
for kk in range(t):
    n,p,k=list(map(int,input().split()))
    goods=list(map(int,input().split()))
    goods.sort()
    l=0
    h=n-1
    m=(l+h)//2
    while l<=h:
        t=sum(goods[m::-2])
        if p-t<0:
            h=m-1
            m=(l+h)//2
        else:
            l=m+1
            m=(l+h)//2

    print(m+1)


t=int(input())

for kk in range(t):
    n,p,k=[int(a) for a in input().split()]
    goods=[int(a) for a in input().split()]
    goods.sort()

    for i in range(n+1):
        t=sum(goods[i::-2])
        if p-t<0:
            break
    t=i
    print(t)


import os
import sys
from io import BytesIO, IOBase
from itertools import accumulate
from bisect import bisect

def solution(arr, n, p, k):
    arr.sort()
    prices = [0] * (n + 1)
    res = 0

    for i in range(k - 1):
        prices[i] = prices[i - 1] + arr[i]
        if prices[i] <= p:
            res = i + 1

    for i in range(k - 1, n):
        prices[i] = prices[i - k] + arr[i]
        if prices[i] <= p:
            res = i + 1

    write(res)

def main():
    for _ in range(r_int()):
        n, p, k = r_array()
        arr = r_array()
        solution(arr, n, p, k)

# fast-io region

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

def input():
    return sys.stdin.readline().rstrip("\r\n")

def write(*args, end='\n'):
    for x in args:
        sys.stdout.write(str(x) + ' ')
    sys.stdout.write(end)

def r_array():
    return [int(x) for x in input().split()]

def r_int():
    return int(input())

if __name__ == "__main__":
    main()


import os
import sys
from io import BytesIO, IOBase
from itertools import accumulate
from bisect import bisect

def solution(arr, n, p, k):
    arr.sort()
    prices = list(accumulate(arr))
    res = bisect(prices, p)

    if res == 0:
        write(res)
    elif res == n:
        write(res)
    else:
        write(res + 1)

def main():
    for _ in range(r_int()):
        n, p, k = r_array()
        arr = r_array()
        solution(arr, n, p, k)

# fast-io region

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

def input():
    return sys.stdin.readline().rstrip("\r\n")

def write(*args, end='\n'):
    for x in args:
        sys.stdout.write(str(x) + ' ')
    sys.stdout.write(end)

def r_array():
    return [int(x) for x in input().split()]

def r_int():
    return int(input())

if __name__ == "__main__":
    main()


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    arr=list(map(int,input().split()))
    arr.sort()
    i=0
    while i<n and p>=arr[i]:
        p-=arr[i]
        i+=1
    if i==0:
        print(0)
    elif i==n:
        print(n)
    else:
        print(i+1)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    arr=list(map(int,input().split()))
    arr.sort()
    i=0
    while i<n and p>=arr[i]:
        p-=arr[i]
        i+=1
    if i==0:
        print(0)
    elif i==n:
        print(n)
    elif p+arr[i-1]>=arr[i]:
        print(i+1)
    else:
        print(i)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    arr=list(map(int,input().split()))
    arr.sort()
    dp=[0]*n
    ans=0
    for i in range(n):
        if i>k-1:
            dp[i]=dp[i-k]+arr[i]
        else:
            dp[i]=arr[i]
        if dp[i]>p:
            ans=i
            break
    print(ans)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    arr=list(map(int,input().split()))
    arr.sort()
    dp=[0]*n
    ans=0
    for i in range(n):
        if i>k-1:
            dp[i]=dp[i-k]+arr[i]
        else:
            dp[i]=arr[i]
        if dp[i]>p:
            ans=i
            break
        if i==n-1:
            ans=n
            break
    print(ans)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    arr=list(map(int,input().split()))
    arr.sort()
    i=0
    while p>=arr[i]:
        p-=arr[i]
        i+=1
    if i==0:
        print(0)
    else:
        print(i+2)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    arr=list(map(int,input().split()))
    arr.sort()
    dp=[0]*n
    ans=0
    for i in range(n):
        if i>k-1:
            dp[i]=dp[i-k]+arr[i]
        else:
            dp[i]=arr[i]
        if dp[i]>p or i==n-1:
            ans=i
            break
    print(ans)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    arr=list(map(int,input().split()))
    arr.sort()
    i=0
    while i<n-1:
        if arr[i+1]<=p:
            p-=arr[i+1]
            i+=2
            if p<0:
                p+=arr[i+1]
                i-=2
        elif arr[i]<=p:
            p-=arr[i]
            i+=1
            break
    print(i)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    arr=list(map(int,input().split()))
    arr.sort()
    i=0
    while i<n-1:
        if arr[i+1]<=p:
            p-=arr[i+1]
            i+=2
        elif arr[i]<=p:
            p-=arr[i]
            i+=1
            break
        else:
            break
    print(i)


for _ in range(int(input())):
    n,p,k=map(int,input().split())
    arr=list(map(int,input().split()))
    arr.sort()
    i=0
    while i<n and p>=arr[i]:
        p-=arr[i]
        i+=1
    if i==0:
        print(0)
    elif i==n:
        print(n)
    else:
        print(i+2)


def buy(arr, n, money):
    if n >= len(arr) or arr[n] > money:
        return n
    if n+1 < len(arr) and arr[n+1] <= money:
        return(max(buy(arr,n+1,money-arr[n]), buy(arr,n+2,money-arr[n+1])))
    return n+1

for _ in range(int(inpit())):
    n,p,k = map(int, input().split())
    arr = sorted(map(int, input().split()))
    print(buy(arr,0,p))


def buy(arr, n, money):
    if n >= len(arr) or arr[n] > money:
        return n
    if n+1 < len(arr) and arr[n+1] <= money:
        return(max(buy(arr,n+1,money-arr[n]), buy(arr,n+2,money-arr[n+1])))
    return n+1

for _ in range(int(input())):
    n,p,k = map(int, input().split())
    arr = sorted(map(int, input().split()))
    print(buy(arr,0,p))


def buy(arr, n, money):
    while n < len(arr):
        if arr[n] > money:
            return n
        if n+1 < len(arr) and arr[n+1] <= money:
            money -= arr[n+1]
            n += 2
        else:
            money -= arr[n]
            n += 1
    return n

for _ in range(int(input())):
    n,p,k = map(int, input().split())
    arr = sorted(map(int, input().split()))
    first = 0
    if arr[0] <= p:
        first = (buy(arr, 1, p - arr[0]))
    print(max(buy(arr,0,p), first))


for _ in range(int(input())):
    n,p,k=map(int, input().strip().split())
    arr=list(map(int, input().strip().split()))
    arr=sorted(arr)

    off=n%k
    ans=0
    flg=0
    for i in range(off+k-1,n,k):
        if(p<arr[i]):
            ind=i
            flg=1
            break
        ans+=k
        p-=arr[i]

    for i in range(0,off):
        if(p<arr[i]):
            break
        ans+=1
        p-=arr[i]

    if(flg==1):
        for i in range(max(0,ind-k+1),ind):
            if(p<arr[i]):
                break
            ans+=1
            p-=arr[i]

    print(ans)


for _ in range(int(input())):
    n,p,k=map(int, input().strip().split())
    arr=list(map(int, input().strip().split()))
    dup=p
    arr=sorted(arr)

    ans=0
    for i in range(1,n,2):
        if(p<arr[i]):
            break
        p-=arr[i]
        ans+=2

    p=dup
    raj=0
    for i in range(2,n,2):
        if(p<arr[i]):
            break
        p-=arr[i]
        raj+=2

    if(p>=arr[0]):
        raj+=1

    print(max(ans,raj))


T = int(input())
for t in range(T):
    n, p, k = map(int, input().split(' '))
    v = list(map(int, input().split(' ')))
    v.sort()
    dp = [-1] * n
    for i in range(n):
        if (i < 2):
            dp[i] = v[i]
        else:
            dp[i] = v[i] + dp[i-2]
    dp = list(filter(lambda a: a <= p, dp))
    print(len(dp))


for _ in [0]*int(input()):
    n, p, k = map(int, input().split())
    a = sorted(list(map(int, input().split())))
    a.append(2000000001)
    n += 1
    P = p
    gifts = 0
    #print(a)
    for i in range(1, n, 2):
        if P - a[i] < 0:
            if P - a[i-1] >= 0:
                P -= a[i-1]
                gifts += 1
            break
        P -= a[i]
        gifts += 2
    gifts_ = min(gifts, 1)
    p -= a[0]
    for i in range(2, n, 2):
        if p - a[i] < 0:
            if p - a[i-1] >= 0:
                p -= a[i-1]
                gifts_ += 1
            break
        p -= a[i]
        gifts_ += 2
    print(max(gifts, gifts_))


for _ in [0]*int(input()):
    n, p, k = map(int, input().split())
    a = sorted(list(map(int, input().split())))
    a.append(10001)
    n += 1
    P = p
    gifts = 0
    #print(a)
    for i in range(1, n, 2):
        if P - a[i] < 0:
            if P - a[i-1] >= 0:
                P -= a[i-1]
                gifts += 1
            break
        P -= a[i]
        gifts += 2
    gifts_ = min(gifts, 1)
    p -= a[0]
    for i in range(2, n, 2):
        if p - a[i] < 0:
            if p - a[i-1] >= 0:
                p -= a[i-1]
                gifts_ += 1
            break
        p -= a[i]
        gifts_ += 2
    print(max(gifts, gifts_))


#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def main():
    t = int(input())

    for _ in range(t):
        n, p, k = map(int, input().split())
        a = sorted([int(i) for i in input().split()])

        u = 0
        s1 = 0

        for i in range(k - 1, n, k):
            if u + a[i] > p:
                break
            u += a[i]
            s1 += k

        while s1 < n and a[s1] + u <= p:
            u += a[s1]
            s1 += 1

        u = 0
        s2 = 0

        for i in range(k, n, k):
            if u + a[i] > p:
                break
            u += a[i]
            s2 += k

        s2 += a[0] + u <= p

        print(max(s1, s2))

# region fastio

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

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


for _ in range(int(input())):

    n,p,k = map(int,input().split())

    a = list(map(int,input().split()))
    a.sort()

    ch = 1
    mx = -1

    if(n%2 == 0):
        ch =1
    else:
        ch = 0

    if(ch == 1):
        cn = 0
        mn = p
        for i in range(1,n,2):
            if(mn>=a[i]):
                cn += 2
                mn -= a[i]

        mx = max(mx,cn)

    else:
        cn = 0
        mn = p
        for i in range(1,n,2):
            if(mn>=a[i]):
                cn += 2
                mn -= a[i]
        # print(cn)
        mx = max(mx,cn)

        cn = 0
        mn = p
        if(mn>=a[0]):
            cn += 1
            mn -= a[0]
        for i in range(2,n,2):
            if(mn>=a[i]):
                cn += 2
                mn -= a[i]
        # print(cn)
        mx = max(mx,cn)

    print(mx)


for _ in range(int(input())):

    n,p,k = map(int,input().split())

    a = list(map(int,input().split()))
    a.sort()

    ch = 1
    mx = -1

    if(n%2 == 0):
        ch =1
    else:
        ch = 0

    cn = 0
    mn = p
    for i in range(1,n,2):
        if(mn>=a[i]):
            cn += 2
            mn -= a[i]
    # print(cn)
    mx = max(mx,cn)

    cn = 0
    mn = p
    if(mn>=a[0]):
        cn += 1
        mn -= a[0]
    for i in range(2,n,2):
        if(mn>=a[i]):
            cn += 2
            mn -= a[i]
    # print(cn)
    mx = max(mx,cn)

    print(mx)


for _ in range(int(input())):
    n, coins, k = map(int, input().split())
    a = sorted(map(int, input().split()))
    a += [float('inf')] * (4 - (n % 4))
    ret = 0
    for i in range(len(a) // 4):
        sub = a[i * 4 : i * 4 + 4]
        if coins >= sub[1] + sub[3]:
            coins -= sub[1] + sub[3]
            ret += 4
        elif coins >= sub[0] + sub[2]:
            coins -= sub[0] + sub[2]
            ret += 3
        elif coins >= sub[1]:
            coins -= sub[1]
            ret += 2
        elif coins >= sub[0]:
            coins -= sub[0]
            ret += 1
        else:
            break
    print(ret)


for _ in range(int(input())):
    n, coins, k = map(int, input().split())
    a = sorted(map(int, input().split()))
    dp = [float('inf')] * (n + 1)
    dp[0] = 0
    for i in range(1, n + 1):
        dp[i] = a[i - 1] + dp[i - 1]
        if i - 2 >= 0:
            dp[i] = min(dp[i], a[i - 1] + dp[i - 2])
    ret = 0
    for i in range(n + 1):
        if dp[i] <= coins:
            ret = i
        else:
            break
    print(ret)


for _ in range(int(input())):
    n, coins, k = map(int, input().split())
    a = sorted(map(int, input().split()))
    dp = [float('inf')] * (n + 1)
    dp[0] = 0
    for i in range(1, n + 1):
        dp[i] = a[i - 1] + dp[i - 1]
        if i - 2 >= 0:
            dp[i] = min(dp[i], a[i - 1] + dp[i - 2])
    ret = 0
    for i in range(n + 1):
        if dp[i] <= coins:
            ret = i
    print(ret)


from sys import stdin
R=lambda:map(int,stdin.readline().split())
for _ in range(int(input())):
	n,p,k=R()
	a=sorted(R());mx1=mx2=0;v1=v2=p
	if a[0]<=p:mx1=1;v1-=a[0]
	if a[1]<=p:mx2=2;v2-=a[1]
	if mx1:
		for i in range(2,n,2):
			if a[i]<=v1:mx1+=2;v1-=a[i]
			else:break
		for i in range(3,n,2):
			if a[i]<=v2:mx2+=2;v2-=a[i]
			else:break
	print(max(mx1,mx2))


for case in range(int(input())):
	n,p,k = map(int,input().split())
	arr = list(map(int,input().split()))
	arr.sort()

	dp = []
	for i in range(n):
		dp.append([1000000000]*n)
		dp[i][i] = arr[i]
		if(i!=n-1):
			dp[i][i+1] = max(arr[i],arr[i+1])

	for i in range(n):
		for j in range(i+1,n):
			for k in range(i,j):
				dp[i][j] = min(dp[i][j],dp[i][k] + dp[k+1][j])
	#print(dp)
	x =0
	count =0
	for y in range(n):
		if(dp[x][y]<=p):
			count+=1
	print(count)


for case in range(int(input())):
	n,p,k = map(int,input().split())
	arr = list(map(int,input().split()))
	arr.sort()

	dp = [1000000000]*n
	dp[0] = arr[0]
	dp[1] = max(arr[0],arr[1])

	for i in range(2,n):
		dp[i] = min(dp[i-2] + max(arr[i-i],arr[i]),dp[i-1]+arr[i])
	#print(dp)
	count=0
	for y in range(n):
		if(dp[y]<=p):
			count+=1
	print(count)


def maxgoods(arr,coins,k):
	if(coins <0):
		return -k
	if(coins==0):
		return 0
	if(len(arr)==0):
		return 0
	if(len(arr)==1):
		if(coins<arr[0]):
			return 0
		else:
			return 1

	if(coins< arr[0]):
		return 0
	else:
		return max(1+maxgoods(arr[1:],coins-arr[0],1),2+maxgoods(arr[2:],coins-max(arr[0],arr[1]),2))

for case in range(int(input())):
	n,p,k = map(int,input().split())
	arr = list(map(int,input().split()))
	arr.sort()
	print(maxgoods(arr,p,0))


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right

from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0

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

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

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

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

import time
start_time = time.time()

import collections as col
import math, string
from functools import reduce

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

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

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

def getStr():
    return input()

def listStr():
    return list(input())

MOD = 10**9+7

"""
j=K-1,...,2*K-2 as first index for freebie
Then index j-(K-1) to j are all free, so indices up to j are up for grabs

"""

def solve():
    N, P, K = getInts()
    A = getInts()
    A.sort()
    if P < A[0]:
        return 0
    ans = 0
    prefs = [0]
    for a in A:
        prefs.append(prefs[-1]+a)
    prefs = prefs[1:]
    #print(N,P,K,A,prefs)
    for idx in range(K-1,2*K-1):
        if idx > N-1:
            break
        if A[idx] > P:
            right = idx-1
            if right < 0:
                continue
            elif prefs[right] <= P:
                ans = max(ans,right+1)
            elif prefs[0] > P:
                continue
            else:
                left = 0
                while right-left > 1:
                    middle = (left+right)//2
                    if prefs[middle] <= P:
                        left = middle
                    else:
                        right = middle
                ans = max(ans,right)
            continue
        start = idx
        money = P
        while idx < N and A[idx] <= money:
            money -= A[idx]
            idx += K
        idx -= K
        tmp = idx-start+K
        extra = 0
        right = start-K
        if right < 0:
            extra = 0
        elif prefs[right] <= money:
            extra = right+1
        elif prefs[0] > money:
            extra = 0
        else:
            left = 0
            while right-left > 1:
                middle = (left+right)//2
                if prefs[middle] <= money:
                    left = middle
                else:
                    right = middle
            extra = right
        #print(start,tmp,extra)
        ans = max(ans,extra+tmp)

    return ans

for _ in range(getInt()):
    print(solve())


def pos(l, i, k, p):
    sub = l[:i+1:][::-1]

    parts = []

    while True:
        #print("SUB", sub)
        part = sub[:k]
        parts.append(part)
        sub = sub[k:]
        if len(part) != k:
            break

    c = 0
    el = 0
    for z in parts:
        if len(z) == k:
            c += max(z)
            el += k
        else:
            el += len(z)
            c += sum(z)

    #print(c, el)
    #print(sub, parts)
    return 0 if c > p else el

t = int(input())
for _ in range(t):
    n, p, k = map(int, input().split(' '))
    a = list(map(int, input().split(' ')))

    s = sorted(a)

    g = max([pos(s, i, k, p) for i in range(len(s))])

    print(g)
    #break


def pos(l, i, k, p):
    sub = l[:i+1:][::-1]

    parts = []

    j = 0
    c = 0
    el = 0
    #print(sub)
    while j < len(sub):
        #print(j)
        if len(sub)-j >= k:
            c += max(sub[j:j+k])
            #print("PARTS", sub[j:j+k])
            el += k
            j += k

        else:
            #print("F", j, len(sub),len(sub)-j)
            c += sum(sub[j:])
            el += len(sub)-j
            j += len(sub)-j

    #print(c, el,-1 if c > p else el)

    return -1 if c > p else el

t = int(input())
for _ in range(t):
    n, p, k = map(int, input().split(' '))
    a = list(map(int, input().split(' ')))

    s = sorted(a)

    q = 0
    for i in range(len(s)):
        r = pos(s, i, k, p)
        if r == -1: break
        q = max(r,q)

    print(q)


//#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=2e5+10;
int a[maxn];
char inp[maxn];
int n;
int main()
{
    int i,j,tmp,flag=0;
    cin>>n;
    for(i=1;i<=n;i++){scanf("%d",&a[i]);}
    scanf("%s",inp);
    for(i=1;i<n;i++)
    {
        if(inp[i-1]=='1'&&flag==0){flag=1;tmp=i;}
        if((inp[i-1]=='0'&&flag==1)||i==n-1){flag=0;sort(a+tmp,a+i+1);}

    }
    for(i=1;i<=n;i++){if(a[i]!=i){cout<<"NO\n";return 0;}}
    cout<<"YES\n";
    //for(i=1;i<=n;i++){cout<<a[i]<<" ";}cout<<endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define maxn 200010
int a[maxn];
int n;
char c[maxn];
int l[maxn],r[maxn];
bool vis[maxn];
main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    scanf("%s",c+1);
    c[0]='0';
    int cur=0;
    for(int i=1;i<n;i++)
    {
        if(c[i]=='1' && c[i-1]=='0')l[++cur]=i;
        if((c[i]=='0' && c[i-1]=='1') || (c[i]=='1' && i==n-1))r[cur]=(i==n-1) ? i+1 : i;
    }
    //printf("%d\n",cur);
    //for(int i=1;i<=cur;i++)printf("%d %d\n",l[i],r[i]);
    for(int i=1;i<=cur;i++)
    {
        for(int j=l[i];j<=r[i];j++)vis[a[j]]=1;
        for(int j=l[i];j<=r[i];j++)if(!vis[j])return 0*puts("NO");
        for(int j=l[i];j<=r[i];j++)vis[a[j]]=0;
    }
    l[cur+1]=n+1;
    for(int i=1;i<=cur+1;i++)
    {
        for(int j=r[i-1]+1;j<l[i];j++)if(a[j]!=j)return 0*puts("NO");
    }
    puts("YES");
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define maxn 200010
int a[maxn];
int n;
char c[maxn];
int l[maxn],r[maxn];
bool vis[maxn];
main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    scanf("%s",c+1);
    c[0]='0';
    int cur=0;
    for(int i=1;i<n;i++)
    {
        if(c[i]=='1' && c[i-1]=='0')l[++cur]=i;
        if((c[i]=='0' && c[i-1]=='1') || i==n-1)r[cur]=(i==n-1) ? i+1 : i;
    }
    //printf("%d\n",cur);
    //for(int i=1;i<=cur;i++)printf("%d %d\n",l[i],r[i]);
    for(int i=1;i<=cur;i++)
    {
        for(int j=l[i];j<=r[i];j++)vis[a[j]]=1;
        for(int j=l[i];j<=r[i];j++)if(!vis[j])return 0*puts("NO");
        for(int j=l[i];j<=r[i];j++)vis[a[j]]=0;
    }
    l[cur+1]=n+1;
    for(int i=1;i<=cur+1;i++)
    {
        for(int j=r[i-1]+1;j<l[i];j++)if(a[j]!=j)return 0*puts("NO");
    }
    puts("YES");
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define maxn 200010
int a[maxn];
int n;
char c[maxn];
int l[maxn],r[maxn];
bool vis[maxn];
main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    scanf("%s",c+1);
    c[0]='0';
    c[n]='0';
    int cur=0;
    for(int i=1;i<=n;i++)
    {
        if(c[i]=='1' && c[i-1]=='0')l[++cur]=i;
        if(c[i]=='0' && c[i-1]=='1')r[cur]= i;
    }
    //printf("%d\n",cur);
    //for(int i=1;i<=cur;i++)printf("%d %d\n",l[i],r[i]);
    for(int i=1;i<=cur;i++)
    {
        for(int j=l[i];j<=r[i];j++)vis[a[j]]=1;
        for(int j=l[i];j<=r[i];j++)if(!vis[j])return 0*puts("NO");
        for(int j=l[i];j<=r[i];j++)vis[a[j]]=0;
    }
    l[cur+1]=n+1;
    for(int i=1;i<=cur+1;i++)
    {
        for(int j=r[i-1]+1;j<l[i];j++)if(a[j]!=j)return 0*puts("NO");
    }
    puts("YES");
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define maxn 200010
int a[maxn];
int n;
char c[maxn];
int l[maxn],r[maxn];
bool vis[maxn];
main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    scanf("%s",c+1);
    c[0]='0';
    int cur=0;
    for(int i=1;i<n;i++)
    {
        if((c[i]=='0' || i==n-1) && c[i-1]=='1')r[cur]=(i==n-1) ? i+1 : i;
        else if(c[i]=='1' && c[i-1]=='0')l[++cur]=i;
    }
    //printf("%d\n",cur);
    //for(int i=1;i<=cur;i++)printf("%d %d\n",l[i],r[i]);
    for(int i=1;i<=cur;i++)
    {
        for(int j=l[i];j<=r[i];j++)vis[a[j]]=1;
        for(int j=l[i];j<=r[i];j++)if(!vis[j])return 0*puts("NO");
        for(int j=l[i];j<=r[i];j++)vis[a[j]]=0;
    }
    l[cur+1]=n+1;
    for(int i=1;i<=cur+1;i++)
    {
        for(int j=r[i-1]+1;j<l[i];j++)if(a[j]!=j)return 0*puts("NO");
    }
    puts("YES");
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define maxn 200010
int a[maxn];
int n;
char c[maxn];
int l[maxn],r[maxn];
bool vis[maxn];
main()
{
    scanf("%d",&n);//
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    scanf("%s",c+1);
    c[0]='0';
    int cur=0;
    for(int i=1;i<n;i++)
    {
        if((c[i]=='0' || i==n-1) && c[i-1]=='1')r[cur]=(i==n-1) ? i+1 : i;
        else if(c[i]=='1' && c[i-1]=='0')l[++cur]=i;
    }
    //printf("%d\n",cur);
    //for(int i=1;i<=cur;i++)printf("%d %d\n",l[i],r[i]);
    for(int i=1;i<=cur;i++)
    {
        for(int j=l[i];j<=r[i];j++)vis[a[j]]=1;
        for(int j=l[i];j<=r[i];j++)if(!vis[j])return 0*puts("NO");
        for(int j=l[i];j<=r[i];j++)vis[a[j]]=0;
    }
    l[cur+1]=n+1;
    for(int i=1;i<=cur+1;i++)
    {
        for(int j=r[i-1]+1;j<l[i];j++)if(a[j]!=j)return 0*puts("NO");
    }
    puts("YES");
    return 0;
}


#include <bits/stdc++.h>

using namespace std;
const int maxn = 2e5 + 7;

int n, arr[maxn];
char str[maxn];

int main()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++ ) {
        scanf("%d", &arr[i]);
    }
    scanf("%s", str + 1);
    for(int i = 1; i <= n; i ++ ) {
        if(str[i] == '1') {
            int j = i;
            while(str[j] == '1') {
                j ++;
            }
            sort(arr + 1 + i, arr + 1 + j);
            i = j - 1;
        }
    }
    bool ok = 1;
    for(int i = 1; i <= n - 1; i ++ ) {
        if(arr[i] > arr[i + 1]) {
            ok = 0;
            break;
        }
    }
    printf("%s\n", ok ? "YES" : "NO");

    return 0;
}


#include <bits/stdc++.h>

using namespace std;
const int maxn = 2e5 + 7;

int n, arr[maxn];
char str[maxn];

int main()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++ ) {
        scanf("%d", &arr[i]);
    }
    scanf("%s", str + 1);
    for(int i = 1; i <= n; i ++ ) {
        if(str[i] == '1') {
            int j = i;
            while(str[j] == '1') {
                j ++;
            }
            sort(arr + 1 + i, arr + 1 + j);
            i = j;
        }
    }
    bool ok = 1;
    for(int i = 1; i <= n - 1; i ++ ) {
        if(arr[i] >= arr[i + 1]) {
            ok = 0;
            break;
        }
    }
    printf("%s\n", ok ? "YES" : "NO");

    return 0;
}


#include <bits/stdc++.h>

using namespace std;
const int maxn = 2e5 + 7;

int n, arr[maxn];
char str[maxn];

int main()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++ ) {
        scanf("%d", &arr[i]);
    }
    scanf("%s", str + 1);
    for(int i = 1; i <= n; i ++ ) {
        if(str[i] == '1') {
            int j = i;
            while(str[j] == '1') {
                j ++;
            }
            sort(arr + i, arr + 1 + j);
            i = j;
        }
    }
    bool ok = 1;
    for(int i = 1; i <= n - 1; i ++ ) {
        if(arr[i] >= arr[i + 1]) {
            ok = 0;
            break;
        }
    }
    printf("%s\n", ok ? "YES" : "NO");

    return 0;
}