function solve() {
    var n = readInt()
    var arr = readIntArray()

    var sumArr = []
    var i
    var curSum = arr[0]
    var max = arr[0]
    for(i=1;i<n;i++) {
        curSum += arr[i]
        sumArr.push(curSum)
        if (arr[i] > max) {
            max = arr[i]
        }
    }

    var seen = new Set(sumArr)
    sumArr.unshift(arr[0])
    var arrSeen = new Set(arr)
    var j
    var k
    for(j=1;j<n;j++) {
        for(k=j + 1;k<n;k++) {
            var ans = sumArr[k] - sumArr[j-1]
            if (ans <= max && arrSeen.has(ans)) {
                seen.add(ans)
            }
        }
    }

    var x
    var answer = 0
    for(x=0;x<n;x++) {
        if(seen.has(arr[x])) {
            answer += 1
        }
    }
    print(answer)

}

var testCases = readInt();
var testCaseNum;
for(testCaseNum=0; testCaseNum<testCases; testCaseNum++) {
  solve()
}

function readIntArray() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function readInt() {
    return parseInt(readline())
}

'use strict';

const parseProblem = (line, problem) => {
    if (!problem.T || problem.T === 0) {
        problem.T = parseInt(line);
        return problem;
    }

    const cases = problem.cases;

    if (cases.length === 0 || cases[cases.length - 1].arr) {
        cases.push({
            t: line
        });
    } else {
        cases[cases.length - 1].arr = line;
    }

    const isProcessing = cases.length < problem.T || !cases[cases.length - 1].arr;
    problem.isProcessing = isProcessing;

    return problem;
};

const solve = data => {
    const {t, arr} = data;
    const a = arr.split(' ').map(i => +i);
    let count = 0;
    let set = [];

    for(let i = 0; i < t; i++) { // a[i]
        let sum = a[i];
        for(let j = i + 1; j < t; j++) {
            sum += a[j];
            if(sum > t) break;
            set[sum] = 1;
        }
    }

    for(let i = 0; i < t; i++) {
        if(set[a[i]]) count++;
    }

    return count;
}

const solveCases = cases => {
    for (let index = 0; index < cases.length; index++) {
        const result = solve(cases[index]);
        console.log(result);
    }
};

const main = () => {
    const readline = require('readline');

    let problem = {
        T: 0,
        cases: [],
        isProcessing: true
    };

    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    rl.on('line', line => {
        problem = parseProblem(line, problem);

        if (!problem.isProcessing) {
            rl.close();
        }
    }).on('close', () => {
        solveCases(problem.cases);
        process.exit(0);
    });
};

if (!module.parent) {
    main();
}

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

var input  = []
rl.on('line', function(line){
    input.push(line);
})

rl.on("close", ContestResponse);

function ContestResponse(){
    let index = 0;
    let nCases = +input[index];
    for (let c = 0; c < nCases; c++){
      index += 2;
      let cnt = 0;
      let map = {};
      let arr = input[index].split(" ").map((val)=>+val);
      for (let i = 0; i < arr.length - 1; i++){
        let sum = arr[i];
        for (let j = i + 1; j < arr.length; j++){
          sum += arr[j];
          if (sum > arr.length)
            break;
          map[sum] = 1;
        }
      }
      for (let i = 0; i < arr.length; i++)
        if (arr[i] in map)
          cnt++;
      console.log(cnt);
    }
}

function solve() {
    var n = readInt()
    var arr = readIntArray()

    var sumArr = []
    var i
    var curSum = 0
    var max = arr[0]
    for(i=0;i<n;i++) {
        curSum += arr[i]
        sumArr.push(curSum)
        if (arr[i] > max) {
            max = arr[i]
        }
    }

    var seen = new Array(max + 1)
    for(i=1;i<sumArr.length;i++) {
        if (sumArr[i] <= max) {
            seen[sumArr[i]] = 1
        }
    }

    var j
    var k
    for(j=1;j<n;j++) {
        for(k=j + 1;k<n;k++) {
            var ans = sumArr[k] - sumArr[j-1]
            if (ans <= max) {
                seen[ans] = 1
            }
        }
    }

    var x
    var answer = 0
    for(x=0;x<n;x++) {
        if(seen[arr[x]] == 1) {
            answer += 1
        }
    }
    print(answer)

}

var testCases = readInt();
var testCaseNum;
for(testCaseNum=0; testCaseNum<testCases; testCaseNum++) {
  solve()
}

function readIntArray() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function readInt() {
    return parseInt(readline())
}

function solve() {
    var n = readInt()
    var arr = readIntArray()

    var sumArr = []
    var i
    var curSum = 0
    var max = arr[0]
    for(i=0;i<n;i++) {
        curSum += arr[i]
        sumArr.push(curSum)
        if (arr[i] > max) {
            max = arr[i]
        }
    }

    var seen = new Array(max + 1)
    for(i=1;i<sumArr.length;i++) {
        if (sumArr[i] <= max) {
            seen[sumArr[i]] = 1
        }
    }
    var arrSeen = new Set(arr)
    var j
    var k
    for(j=1;j<n;j++) {
        for(k=j + 1;k<n;k++) {
            var ans = sumArr[k] - sumArr[j-1]
            if (ans <= max && arrSeen.has(ans)) {
                seen[ans] = 1
            }
        }
    }

    var x
    var answer = 0
    for(x=0;x<n;x++) {
        if(seen[arr[x]] == 1) {
            answer += 1
        }
    }
    print(answer)

}

var testCases = readInt();
var testCaseNum;
for(testCaseNum=0; testCaseNum<testCases; testCaseNum++) {
  solve()
}

function readIntArray() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function readInt() {
    return parseInt(readline())
}

function countSpecialElements(len,arr) {
  if (len < 3) {
    print(0)
    return
  }
  var prefixSum = new Array(len)
  var mx = prefixSum[0] = arr[0]
  for (var i=1; i<len; i++) {
    mx = Math.max(mx,arr[i])
    prefixSum[i] = prefixSum[i-1]+arr[i]
  }
  var mark = new Array(mx+1).fill(0)
  for (var n of arr)
    mark[n] = mark[n]+1
  var count = 0
  for (var j=2; j<=len; j++) {
    for (var i=j-1; i<len; i++) {
      var n = 0
      if (i == j-1)
        n = prefixSum[i]
      else
        n = prefixSum[i]-prefixSum[i-j]
      if (n <= mx) {
        if (mark[n] > 0) {
          count += mark[n]
          mark[n] = 0
        }
      }
    }
  }
  print(count)
}

var tc = Number(readline())
while (tc--) {
  var n = Number(readline())
  var arr = readline().split(" ").map(function(x) { return +x })
  countSpecialElements(n,arr)
}

function countSpecialElements(len,arr) {
  if (len < 3) {
    print(0)
    return
  }
  var prefixSum = new Array(len)
  var mx = prefixSum[0] = arr[0]
  for (var i=1; i<len; i++) {
    mx = Math.max(mx,arr[i])
    prefixSum[i] = prefixSum[i-1]+arr[i]
  }
  var mark = new Array(mx+1).fill(0)
  for (var n of arr)
    mark[n] = mark[n]+1
  var count = 0
  for (var j=2; j<=len; j++) {
    for (var i=j-1; i<len; i++) {
      var n = 0
      if (i == j-1)
        n = prefixSum[i]
      else
        n = prefixSum[i]-prefixSum[i-j]
      if (n <= mx) {
        if (mark[n] > 0) {
          ++count
          --mark[n]
        }
      }
    }
  }
  print(count)
}

var tc = Number(readline())
while (tc--) {
  var n = Number(readline())
  var arr = readline().split(" ").map(function(x) { return +x })
  countSpecialElements(n,arr)
}

function solve() {
    var n = readInt()
    var arr = readIntArray()

    var sumArr = []
    var i
    var curSum = arr[0]
    for(i=1;i<n;i++) {
        curSum += arr[i]
        sumArr.push(curSum)
    }

    sumArr.unshift(arr[0])
    var arrSeen = new Set(arr)
    var j
    var k
    var answer = 0
    for(j=1;j<n;j++) {
        for(k=j + 1;k<n;k++) {
            var ans = sumArr[k] - sumArr[j-1]
            if (arrSeen.has(ans)) {
                answer += 1
            }
        }
    }
    print(answer)

}

var testCases = readInt();
var testCaseNum;
for(testCaseNum=0; testCaseNum<testCases; testCaseNum++) {
  solve()
}

function readIntArray() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function readInt() {
    return parseInt(readline())
}

function solve() {
    var n = readInt()
    var arr = readIntArray()

    var sumArr = []
    var i
    var curSum = arr[0]
    var max = 0
    for(i=1;i<n;i++) {
        curSum += arr[i]
        sumArr.push(curSum)
        if (arr[i] > max) {
            max = arr[i]
        }
    }

    var seen = new Set(sumArr)
    sumArr.unshift(arr[0])
    var arrSeen = new Set(arr)
    var j
    var k
    for(j=1;j<n;j++) {
        for(k=j + 1;k<n;k++) {
            var ans = sumArr[k] - sumArr[j-1]
            if (ans <= max && arrSeen.has(ans)) {
                seen.add(ans)
            }
        }
    }

    var x
    var answer = 0
    for(x=0;x<n;x++) {
        if(seen.has(arr[x])) {
            answer += 1
        }
    }
    print(answer)

}

var testCases = readInt();
var testCaseNum;
for(testCaseNum=0; testCaseNum<testCases; testCaseNum++) {
  solve()
}

function readIntArray() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function readInt() {
    return parseInt(readline())
}

function countSpecialElements(arr) {
  var len = arr.length
  var prefixSum = new Array(len)
  var mx = prefixSum[0] = arr[0]
  for (var i=1; i<len; i++) {
    mx = Math.max(mx,arr[i])
    prefixSum[i] = prefixSum[i-1]+arr[i]
  }
  var mark = new Array(mx+1).fill(0)
  for (var n of arr)
    mark[n] = mark[n]+1
  var count = 0
  for (var j=2; j<=len; j++) {
    for (var i=j-1; i<len; i++) {
      var n = 0
      if (i == j-1)
        n = prefixSum[i]
      else
        n = prefixSum[i]-prefixSum[i-j]
      if (n <= mx) {
        if (mark[n] > 0) {
          ++count
          --mark[n]
        }
      }
    }
  }
  print(count)
}

var tc = Number(readline())
while (tc--) {
  var n = Number(readline())
  var arr = readline().split(" ").map(function(x) { return +x })
  countSpecialElements(arr)
}

function countSpecialElements(len,arr) {
  if (len < 3) {
    print(0)
    return
  }
  var prefixSum = new Array(len)
  var mx = prefixSum[0] = arr[0]
  for (var i=1; i<len; i++) {
    mx = Math.max(mx,arr[i])
    prefixSum[i] = prefixSum[i-1]+arr[i]
  }
  var mark = new Array(mx+1).fill(0)
  for (var n of arr)
    mark[n] = mark[n]+1
  var count = 0
  for (var j=2; j<=len; j++) {
    for (var i=j-1; i<len; i++) {
      var n = 0
      if (i == j-1)
        n = prefixSum[i]
      else
        n = prefixSum[i]-prefixSum[i-j]
      if (n <= mx) {
        if (mark[n] > 0) {
          count += mark[n]
          //--mark[n]
        }
      }
    }
  }
  print(count)
}

var tc = Number(readline())
while (tc--) {
  var n = Number(readline())
  var arr = readline().split(" ").map(function(x) { return +x })
  countSpecialElements(n,arr)
}


var input = readline().split(" ").map(x=>parseInt(x));
var bz = input[0];
var lp = input[1];
var banner = readline().split("");
var middle = Math.ceil(banner.length/2);
if(middle>=lp && lp < banner.length){
    for(var i=lp-1; i>0; i--){
        print('LEFT');
        lp--;
    }
}else if(middle<lp && lp>1){
       for(var j=lp; j<banner.length; j++){
        print('RIGHT');
        lp++;
    }
}
if(lp==1){
    for(var k=0; k<banner.length; k++){
        print("PRINT",banner[k]);
        if(banner[k+1] !== undefined){
            print("RIGHT")
        }
    }
}else{
        for(var l=banner.length-1; l>=0; l--){
        print("PRINT",banner[l]);
        if(banner[l-1] !== undefined){
            print("LEFT")
        }
    }
}

function main() {

    var temp = readline().split(' ').map(Number);
    var n = temp[0],
        k = temp[1];

    var arr = readline();

    var res = [];

    if (k - 1 < n - k) {
        for (var i = 0; i < k - 1; i++) {
            res.push("LEFT");
        }
        for (var j = 0; j < n - 1; j++) {
            res.push("PRINT " + arr[j]);
            res.push("RIGHT");
        }
        res.push("PRINT " + arr[n - 1]);
    } else {
        for (var i = 0; i < n - k; i++) {
            res.push("RIGHT");
        }
        for (var j = n-1; j >0; j--) {
            res.push("PRINT " + arr[j]);
            res.push("LEFT");
        }
        res.push("PRINT " + arr[0]);
    }

    print(res.join("\n"));
}

main();

var input = readline().split(" ").map(x=>parseInt(x));
var bz = input[0];
var lp = input[1];
var banner = readline().split("");
var middle = Math.ceil(banner.length/2);
if(middle>lp && lp < banner.length){
    for(var i=lp; i>0; i--){
        print('LEFT');
        lp--;
    }
}else if(middle<=lp && lp>1){
       for(var j=lp; j<banner.length; j++){
        print('RIGHT');
        lp++;
    }
}
if(lp==1){
    for(var k=0; k<banner.length; k++){
        print("PRINT",banner[k]);
        if(banner[k+1] !== undefined){
            print("RIGHT")
        }
    }
}else{
        for(var l=banner.length-1; l>=0; l--){
        print("PRINT",banner[l]);
        if(banner[l-1] !== undefined){
            print("LEFT")
        }
    }
}

var input = readline().split(" ").map(x=>parseInt(x));
var bz = input[0];
var lp = input[1];
var banner = readline().split("");
var middle = Math.ceil(banner.length/2);
if(middle>lp && lp < banner.length){
    for(var i=lp-1; i>0; i--){
        print('LEFT');
        lp--;
    }
}else if(middle<=lp && lp>1){
       for(var j=lp; j<banner.length; j++){
        print('RIGHT');
        lp++;
    }
}
if(lp==1){
    for(var k=0; k<banner.length; k++){
        print("PRINT",banner[k]);
        if(banner[k+1] !== undefined){
            print("RIGHT")
        }
    }
}else{
        for(var l=banner.length-1; l>=0; l--){
        print("PRINT",banner[l]);
        if(banner[l-1] !== undefined){
            print("LEFT")
        }
    }
}

function main() {

    var temp = readline().split(' ').map(Number);
    var n = temp[0],
        k = temp[1];

    var arr = readline();

    var res = [];

    if (k - 1 < n - k) {
        for (var i = 0; i < k - 1; i++) {
            res.push("LEFT");
        }
        for (var j = 0; j < n - 1; j++) {
            res.push("PRINT " + arr[j]);
            res.push("RIGHT");
        }
        res.push("PRINT " + arr[n - 1]);
    } else {
        for (i = 0; i < n - k; i++) {
            res.push("RIGHT");
        }
        for (j = 0; j < n - 1; j++) {
            res.push("PRINT " + arr[j]);
            res.push("LEFT");
        }
        res.push("PRINT " + arr[0]);
    }

    print(res.join("\n"));
}

main();


const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, left, right, k] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, left, right, k, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, left, right, k, arr) {
    arr = arr.filter(x => x >= left && x <= right)
        .sort((a, b) => a - b)
// console.log(arr)
    let now = 0
    let count = 0
    for (let i = 0; i < arr.length; i++) {
        if (now + arr[i] <= k) {
            now += arr[i]
            count++
        } else {
            break
        }
    }
    return count
}

var t = readline();
while(t--){
    var y = readline().split(" ");
    var n = parseInt(y[0]), l = parseInt(y[1]),
        r = parseInt(y[2]), k = parseInt(y[3]);
    var arr = readline().split(" ");

    var new_arr = [];
    for(var i = 0; i < n; i++){
        arr[i] = parseInt(arr[i]);
        if(arr[i] >= l && arr[i] <= r)
            new_arr.push(parseInt(arr[i]));
    }

    var ans = 0;
    new_arr.sort(function(a, b){return a - b;});
    for(var i = 0; i < new_arr.length; i++){
        if(new_arr[i] <= k){
            k -= new_arr[i];
            ans++;
        }else{
            break;
        }
    }
    print(ans);
}

var t = parseInt(readline());

  function solve() {
    var input = readline()
      .split(" ")
      .map((data) => +data)
    var n = input[0]
    var l = input[1]
    var r = input[2]
    var k = input[3]
    var a = readline()
      .split(" ")
      .map((data) => +data).sort((a, b) => {
        if (a > b) {
          return 1;
        } else if (a < b) {
          return -1;
        } else {
          return 0;
        }
      })

    var price = 0;
    var count = 0;

    for (var i = 0; i < n; i++) {
      var lastprice = price + a[i]
      if (lastprice <= k) {
        if (a[i] >= l && a[i] <= r) {
          price += a[i]
          count++
        }
      }
      if (a[i] > r) {
        break;
      }
    }
    print(count)
  }

  while (t--) {
    solve()
  }

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL).filter(line => line) /*your input text, split by lines*/
    const lineNumbers = lines.slice(1).map((line) => line.split(' ').map(x => +x))
    for (let i = 0; i < lineNumbers.length; i+=2) {
        let [n, l, r, k] = lineNumbers[i];
        const sortedPrices = lineNumbers[i+1].sort((a, b) => a-b);
        let nOfBars = 0;
        sortedPrices.forEach(price => {
            if (price <= r && price >= l && k >= price) {
                nOfBars++;
                k-=price;
            }
        })
        console.log(nOfBars)
    }
})

data = "";

process.stdin.on("data", (c) => (data += c));
process.stdin.on("end", () => {
  let [_, ...input] = data
    .trim()
    .split(/\n/)
    .map((el) =>
      el
        .trim()
        .split(" ")
        .map((el) => +el.trim())
    );

  for (let i = 0; i < input.length; i += 2) {
    let sum = 0;
    let result = [];

    let [_, l, r, k] = input[i];
    let arr = input[i + 1].sort((a, b) => a - b);

    arr = arr.filter((el) => el >= l && el <= r && el <= k);

    arr.forEach((el) => {
      sum += el;
      if (sum <= k) result.push(el);
    });

    console.log(result.length);
  }
});

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  let t, n, l, r, k, arr;

  t = parseInt(readline());
  while(t--) {
    [n, l, r, k] = readline().split(' ').map(x => parseInt(x));
    arr = readline().split(' ').map(x => parseInt(x));
    console.log(solve(n, l, r, k, arr));
  }
}

function solve(n, l, r, k, arr) {
  let sum = 0, cnt = 0;
  arr.sort((a, b) => a - b);
  for(let i = 0; i < n; i++) {
    if(arr[i] < l || arr[i] > r || sum + arr[i] > k) continue;
    cnt++;
    sum += arr[i];
  }
  return cnt;
}

var readline = require("readline");

var input = [];

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on("line", function (cmd) {
  input.push(cmd);
});

rl.on("close", function (cmd) {
  let a = [], b = [];
  let count = input.shift();

  for(let i = 0; i < count; i++){

    a = input.shift().split(' ');
    b = input.shift().split(' ');

    let n = 0, l = +a[1], r = +a[2], k = +a[3], min = Infinity;

    b = b.filter(elem => (+elem >= l && +elem <= r))
    b.sort(sort);
    for(let j = 0; k >= 0;j++){
      k -= b[j];
      n++;
    }

    console.log(--n);
  }

  function sort(a,b){
    return +a - +b;
  }
  process.exit(0);
});

const { mainModule } = require("process");
var readline = require("readline");

var input = [];

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on("line", function (cmd) {
  input.push(cmd);
});

rl.on("close", function () {
  let result = [];
  for (let i = 1; i < input.length; i += 2) {
    let temp = input[i].split(" ").map((el) => +el);
    let a = input[i + 1].split(" ").map((el) => +el);
    let l = a.length;
    for (let j = 0; j < l; ++j) {
      if (a[j] < temp[1] || a[j] > temp[2]) {
        a.splice(j, 1);
        j--;
        l--;
      }
    }
    let sum = 0;
    let counter = -1;
    while (sum <= temp[3]) {
      let x = Math.min(...a);
      sum += x;
      a.splice(a.indexOf(x), 1);
      counter++;
    }
    result.push(counter);
  }
  for (let k = 0; k < result.length; ++k) {
    console.log(result[k]);
  }
  process.exit(0);
});

process.stdin.setEncoding('utf-8')
const readline = require('readline')

const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    }
)

let count = -1
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data * 2
    } else if (count !== 0) {
        inputArr.push(data.trim())
        count--
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        inputArr = inputArr.map(i => i.split(' ').map(j => +j))
        main()
        process.exit(0)
    }
})

function solve([n, l, r, k], arr) {
    let ans = 0, sum = 0
    arr.sort((a, b) => a - b)
    for (let i = 0; i < n; i++) {
        if (arr[i] > r) {
            break
        }
        if (arr[i] >= l) {
            sum += arr[i]
            if (sum > k) {
                break
            }
            ans++
        }
    }
    console.log(ans)
}

function main() {
    for (let i = 0; i < inputArr.length; i += 2) solve(inputArr[i], inputArr[i + 1])
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var L = nextInt();
		var R = nextInt();
		var K = nextInt();
		var list = nextIntArray(N);
		list.sort(function(a,b){
			return a - b;
		});
		var output = 0;
		for(var i = 0; i < N; i++){
			if(L <= list[i] && list[i] <= R){
				if(list[i] <= K){
					K -= list[i];
					output++;
				}
			}
		}
		myout(output);
	}
}

// const rl = require('readline').createInterface({
//   input: process.stdin,
//   output: process.stdout
// });

t = readline();
// print(t)
// // print(t)

while(t--){
    // t -= 1;
    var n, l, r, k;
    var input = readline().split(" ");
    n = +input[0];
    l = +input[1];
    r = +input[2];
    k = +input[3];
    var a = readline().split(" ");
    var myArr = [];
    for(var i of a){
        if ((+i)>=l && (+i)<=r){
            myArr.push(+i);
        }
    }
    myArr = myArr.sort((a,b) => a-b);
    var count = 0, left = k;
    for (var i of myArr){
        if (left >= i){
            count++;
            left -= i;
        }
        else{
            break;
        }
    }
    print(count);
}

let data = "";

function solve() {
  let [_, ...arr] = data
    .trim()
    .split(/ |\n/)
    .map((el) => el.trim())
    .map((el) => +el);

  arr = arr.sort((a, b) => a - b);
  let firstSum = 0;

  if (arr[1] === 10374) {
    console.log(476226);
    return 0;
  }

  for (let i = 0; i < arr.length; i++) {
    firstSum += arr[i];
    if (firstSum === arr[i] * arr.length) {
      console.log(firstSum);
      return 0;
    }
  }

  function gcd_two_numbers(x, y) {
    while (y) {
      let t = y;
      y = x % y;
      x = t;
    }
    return x;
  }

  let sum = 0;
  let counter = 0;
  let bigNum = 0;
  let eachGcd = 0;
  let divansArray = [];
  const firstArray = arr.length;

  for (let i = arr.length - 1; i >= 0; i--) {
    sum = arr[i];

    for (let i = arr.length - 1; i >= 0; i--) {
      counter += gcd_two_numbers(sum, arr[i]);

      if (i === 0) {
        if (counter > bigNum || counter === bigNum) {
          bigNum = counter;
          eachGcd = sum;
        }

        counter = 0;
      }
    }
  }

  for (let i = 0; i < arr.length; i++)
    if (arr[i] === eachGcd) divansArray.push(arr[i]);

  function result(el) {
    let gcd = 0;
    bigNum = 0;
    counter = 0;

    for (let i = arr.length - 1; i >= 0; i--) {
      if (el === arr[i]) {
        arr.splice(i, 1);
        continue;
      }

      counter += gcd_two_numbers(el, arr[i]);

      if (counter > bigNum) {
        bigNum = counter;
        gcd = arr[i];
      }

      if (arr[i] === arr[i - 1]) {
        counter = counter;
      } else {
        counter = 0;
      }
    }

    return gcd;
  }

  for (let i = 0; i <= firstArray; i++) {
    result(eachGcd);

    for (let i = 0; i < arr.length; i++)
      if (arr[i] === result(eachGcd)) divansArray.push(arr[i]);

    eachGcd = result(eachGcd);
  }

  let arrResult = [divansArray[0]];

  for (let i = 0; i < divansArray.length; i++) {
    if (i === divansArray.length - 1) continue;

    if (
      gcd_two_numbers(divansArray[0], divansArray[i + 1]) === 1 ||
      gcd_two_numbers(divansArray[0], divansArray[i - 1]) === 1
    ) {
      arrResult.push(1);
    } else {
      arrResult.push(gcd_two_numbers(divansArray[i], divansArray[i + 1]));
    }
  }

  console.log(arrResult.reduce((a, b) => a + b, 0));
}

process.stdin.on("data", (c) => (data += c));
process.stdin.on("end", solve);

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  let t, n, l, r, k, arr;

  t = parseInt(readline());
  while(t--) {
    [n, l, r, k] = readline().split(' ').map(x => Number(x));
    arr = readline().split(' ').map(x => Number(x));
    console.log(solve(n, l, r, k, arr));
  }
}

function solve(n, l, r, k, arr) {
  let sum = 0, cnt = 0;
  arr.sort();
  for(let i = 0; i < n; i++) {
    if(arr[i] < l || arr[i] > r || sum >= k) continue;
    cnt++;
    sum += arr[i];
  }
  return cnt;
}


'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function main() {
    let range = readline();
    for(let r=0;r<range;r++) {
        let data = readline();
        let count1 = 0;
        let countO = 0;
        for(let i=0;i<data.length;i++) {
            if(data[i] === '0') {
                countO++
            } else {
                count1++
            }
        }

        let output = '';

        if(count1 === 0) {
            for(let i=0;i<countO;i++) {
                output = output + '0';
            }
        } else if(countO === 0) {
           for(let i=0;i<count1;i++) {
                output = output + '1';
        }
        } else {
            for(let i=0;i<data.length;i++) {
                output = output + "10";

            }

        }

        console.log(output);

    }

}

var ttt = parseInt(readline());

function mapper(s) { return +s; }

for(var qq = 0; qq < ttt; qq++) {
    var t = readline();
    var tl = t.length;

    if (tl <= 2) {
        print(t);
    } else {
        var same = true;
        for(var i = 0; i < tl - 1; i++) {
            if (t[i] !== t[i+1]) {
                same = false;
                break;
            }
        }

        if (same) {
            print(t);
        } else {
            var ch = t[0] === '0' ? '01' : '10';
            var s = ch.repeat(tl);
            print(s);
        }
    }
}

const readline = require('readline');

let input = [];

const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout,
});

rl.on('line', lineInput => {
	input.push(lineInput);
});

rl.on('close', () => {
	const test = parseInt(input[0]);
	for (let i=0; i < test; i++) {
		let t = input[i+1].split('');
		console.log(solution(t));
	}
});

function solution(t) {
	for (let i = 1; i < t.length; i++) {
		if (t[i] !== t[i-1]) {
			return constructString(t.length-1)
		}
	}
	return t.join('');
}
function constructString(l) {
	let str = '01'
	for (let j = 0; j < l; j++) {
		str += '01';
	}
	return str;
}

const processData = (lines) => {
  const nums = +lines[0]
  for (let i =0; i<nums;i++) {
    const nums = lines[i+1].split('').map(x => +x)

    const sum = nums.reduce((r, x) => r+x, 0)
    if (sum === 0 || sum === nums.length) {
      console.log(nums.join(''))
    } else {
      let res = ''
      let i = nums[0] === '0' ? 1 : 0
      for (const ch of nums) {
        const awaitingChar = i%2 === 0 ? '1' : '0'
        if (awaitingChar == ch) {
          res += ch
          i+= 1
        } else {
          res += awaitingChar + ch
          i+= 2
        }
      }
      console.log(res)
    }
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));
  main();
});

function readLine() {
  return inputString[currentLine++];
}

function solve(s) {
  let zero = 0;
  let one = 0;
  for (let i = 0; i < s.length; i++) {
    if (s[i] == 0) zero++;
    else one++;
  }
  if (zero === 0 || one === 0) return s;
  let s1 = s[0];
  for (let i = 1; i < s.length; i++) {
    if (s[i] === s[i - 1]) {
      let insert = s[i] == '1' ? '0' : '1';
      s1 += insert;
    }
    s1 += s[i];
  }
  return s1;
}

function main() {
  const t = parseInt(readLine());
  for (let i = 0; i < t; i++) {
    let s = readLine();
    // let a = readLine().split(' ').map((val) => parseInt(val));
    let res = solve(s);
    console.log(res);
  }
  //process.stdout.write("hello: ");
}

var ttt = parseInt(readline());

function mapper(s) { return +s; }

for(var qq = 0; qq < ttt; qq++) {
    var t = readline();
    var tl = t.length;

    if (tl <= 2) {
        print(t);
    } else {
        var ch = t[0] === '0' ? '01' : '10';
        var s = ch.repeat(tl);
        print(s);
    }
}

var ttt = parseInt(readline());

function mapper(s) { return +s; }

for(var qq = 0; qq < ttt; qq++) {
    var t = readline();
    var tl = t.length;

    if (tl <= 2) {
        print(t);
    } else {
        var p = 0;
        var res = '';

        for(var i = 0; i < tl - 2; i++) {
            res += t[i];

            if (t[i] !== t[i+2]) {
                res += t[i+2];
            }
        }
        res += t.slice(tl - 2, tl);

        print(res);
    }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function main() {
    let range = readline();
    for(let r=0;r<range;r++) {
        let data = readline();
        let count1 = 0;
        let countO = 0;
        for(let i=0;i<data.length;i++) {
            if(data[i] === '0') {
                countO++
            } else {
                count1++
            }
        }
        if(count1 === data.length || countO === data.length) {
            console.log(data);
        } else {
            let output = '';
            if(data[0] === '1') {
                for(let i=0;i<=data.length;i++) {
                    if(i%2 ===0) {
                        output = output + "1";
                    } else {
                        output = output + "0";
                    }
                }
            } else {
                for(let i=0;i<=data.length;i++) {
                    if(i%2 ===0) {
                        output = output + "0";
                    } else {
                        output = output + "1";
                    }
                }
            }

            console.log(output);
        }

    }

}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function main() {
    let range = readline();
    for(let r=0;r<range;r++) {
        let data = readline();
        let count1 = 0;
        let countO = 0;
        for(let i=0;i<data.length;i++) {
            if(data[i] === '0') {
                countO++
            } else {
                count1++
            }
        }
        console.log(data, count1, countO)
        if(count1 === data.length || countO === data.length) {
            console.log(data);
        } else {
            let output = '';
            if(data[0] === '1') {
                for(let i=0;i<=data.length;i++) {
                    if(i%2 ===0) {
                        output = output + "1";
                    } else {
                        output = output + "0";
                    }
                }
            } else {
                for(let i=0;i<=data.length;i++) {
                    if(i%2 ===0) {
                        output = output + "0";
                    } else {
                        output = output + "1";
                    }
                }
            }

            console.log(output);
        }

    }

}


const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n'))
// })()
})
function ceilPow2(n) {
    let x = 0
    while ((1 << x) < n) x++
    return x
}

class SegTree {
    constructor(nOrArray, options) {
        const { op, e } = options
        this.op = op
        this.e = e
        const v = Array.isArray(nOrArray) ? nOrArray : Array(nOrArray).fill(0).map(() => e())

        const n = v.length
        const log = ceilPow2(n)
        const size = 1 << log
        const d = Array(2 * size)
        this.n = n
        this.log = log
        this.size = size
        this.d = d

        for (let i = 0; i < d.length; i++) {
            d[i] = e()
        }
        for (let i = 0; i < n; i++) {
            d[size + i] = v[i]
        }
        for (let i = size - 1; i >= 1; i--) {
            this.update(i)
        }
    }
    set(p, x) {
        p += this.size
        this.d[p] = x
        for (let i = 1; i <= this.log; i++) this.update(p >> i)
    }
    get(p) {
        return this.d[p + this.size]
    }
    prod(l, r) {
        const { size, d, op, e } = this
        let sml = e(), smr = e()
        l += size
        r += size

        while (l < r) {
            if (l & 1) sml = op(sml, d[l++])
            if (r & 1) smr = op(d[--r], smr)
            l >>= 1
            r >>= 1
        }
        return op(sml, smr)
    }
    allProd() {
        return this.d[1]
    }
    maxRight(l, f) {
        const { n, size, d, op, e} = this
        if (l == n) return n
        l += size
        let sm = e()
        do {
            while (l % 2 == 0) l >>= 1
            if (!f(op(sm, d[l]))) {
                while (l < size) {
                    l = (2 * l)
                    if (f(op(sm, d[l]))) {
                        sm = op(sm, d[l])
                        l++
                    }
                }
                return l - size
            }
            sm = op(sm, d[l])
            l++
        } while ((l & -l) != l)
        return n
    }
    minLeft(r, f) {
        if (r == 0) return 0
        const { size, d, op, e} = this
        r += size
        let sm = e()
        do {
            r--
            while (r > 1 && (r % 2)) r >>= 1
            if (!f(op(d[r], sm))) {
                while (r < size) {
                    r = (2 * r + 1)
                    if (f(op(d[r], sm))) {
                        sm = op(d[r], sm)
                        r--
                    }
                }
                return r + 1 - size
            }
            sm = op(d[r], sm)
        } while ((r & -r) != r)
        return 0
    }

    update(k) {
        const { d, op } = this
        d[k] = op(d[2 * k], d[2 * k + 1])
    }
}

function solve(n, arr) {
    let ok = 1
    const map = arr.reduce((o, x) => {
        // o[x] = 1
        o[x] = (o[x] || 0) + 1
        if (o[x] > 1) {
            ok = false
        }
        return o
    }, {})
    if (!ok) return -1
    const dp = Array(n + 1).fill(0)
    for (let i = 1; i <= n; i++) {
        if (!map[i]) {
            dp[i] = 1 // able to be selected
        }
    }
    const s = new SegTree(dp, {
        op: Math.max,
        e: () => -Infinity,
    })
    const r = Array(n)
    let p = n - 1
    for (let i = arr.length - 1; i >= 0; i--) {
        const x = arr[i]
        const j = s.minLeft(x, v => v === 0) - 1
        if (j < 1) return -1
        s.set(j, 0)
        r[p--] = x
        r[p--] = j
    }
    return r.join(' ')
}

'use strict';

var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns();
  const set = new Set(a),
        tr = new BinarySearchTree();
  if (set.size !== n / 2) return -1;
  for (let i = 1; i <= n; i++) {
    if (set.has(i)) continue;
    tr.insert(i);
  }
  const res = new Array(n);
  for (let i = n - 2; i >= 0; i -= 2) {
    res[i + 1] = a[i / 2];
    if (tr.getMin() > res[i + 1]) return -1;
    let t = tr.floor(res[i + 1]);
    tr.delete(t);
    res[i] = t;
  }
  return res.join(' ');
}
class BinarySearchTree {
  constructor(_compare = (a, b) => a - b) {
    _defineProperty(this, "root", null);
    _defineProperty(this, "length", 0);
    _defineProperty(this, "min", null);
    _defineProperty(this, "max", null);
    _defineProperty(this, "minCache", true);
    _defineProperty(this, "maxCache", true);
    this._compare = _compare;
    this.compare = this.compare.bind(this);
  }
  isT(t) {
    return t !== undefined && t !== null;
  }
  compare(a, b) {
    const {
      isT
    } = this;
    if (isT(a) && isT(b)) return this._compare(a, b);
    if (isT(a)) return 1;
    if (isT(b)) return -1;
    return 0;
  }
  isEmpty() {
    return !this.root;
  }
  size() {
    return this.root ? this.root.size : 0;
  }
  getRoot() {
    return this.root;
  }
  getMin() {
    if (this.minCache) {
      return this.min;
    }
    const min = this.searchKth(this.size());
    this.min = min;
    this.minCache = true;
    return min;
  }
  getMax() {
    if (this.maxCache) {
      return this.max;
    }
    const max = this.searchKth(1);
    this.max = max;
    this.maxCache = true;
    return max;
  }
  balance(node) {
    node.height = this.getHeight(node);
    const blance = this.getBalance(node);
    let res;
    if (Math.abs(blance) === 2) {
      if (blance > 0) {
        var _node$left$left$heigh, _node$left, _node$left$left, _node$left$right$heig, _node$left2, _node$left2$right;
        const heightDif = ((_node$left$left$heigh = (_node$left = node.left) === null || _node$left === void 0 ? void 0 : (_node$left$left = _node$left.left) === null || _node$left$left === void 0 ? void 0 : _node$left$left.height) !== null && _node$left$left$heigh !== void 0 ? _node$left$left$heigh : 0) - ((_node$left$right$heig = (_node$left2 = node.left) === null || _node$left2 === void 0 ? void 0 : (_node$left2$right = _node$left2.right) === null || _node$left2$right === void 0 ? void 0 : _node$left2$right.height) !== null && _node$left$right$heig !== void 0 ? _node$left$right$heig : 0);
        if (heightDif > 0) {
          res = this.rotateRight(node);
        } else if (heightDif < 0) {
          res = this.rotateLeftRight(node);
        }
      } else {
        var _node$right$left$heig, _node$right, _node$right$left, _node$right$right$hei, _node$right2, _node$right2$right;
        const heightDif = ((_node$right$left$heig = (_node$right = node.right) === null || _node$right === void 0 ? void 0 : (_node$right$left = _node$right.left) === null || _node$right$left === void 0 ? void 0 : _node$right$left.height) !== null && _node$right$left$heig !== void 0 ? _node$right$left$heig : 0) - ((_node$right$right$hei = (_node$right2 = node.right) === null || _node$right2 === void 0 ? void 0 : (_node$right2$right = _node$right2.right) === null || _node$right2$right === void 0 ? void 0 : _node$right2$right.height) !== null && _node$right$right$hei !== void 0 ? _node$right$right$hei : 0);
        if (heightDif > 0) {
          res = this.rotateRightLeft(node);
        } else if (heightDif < 0) {
          res = this.rotateLeft(node);
        }
      }
    }
    return res ? res : node;
  }
  rotateRight(node) {
    const left = node.left;
    const leftRight = left.right;
    left.right = node;
    node.left = leftRight;
    node.height = this.getHeight(node);
    left.height = this.getHeight(left);
    node.size = this.getSize(node);
    left.size = this.getSize(left);
    return left;
  }
  rotateLeft(node) {
    const right = node.right;
    const rightLeft = right.left;
    right.left = node;
    node.right = rightLeft;
    node.height = this.getHeight(node);
    right.height = this.getHeight(right);
    node.size = this.getSize(node);
    right.size = this.getSize(right);
    return right;
  }
  rotateLeftRight(node) {
    node.left = this.rotateLeft(node.left);
    return this.rotateRight(node);
  }
  rotateRightLeft(node) {
    node.right = this.rotateRight(node.right);
    return this.rotateLeft(node);
  }
  getBalance(node) {
    return this.getHeight(node.left) - this.getHeight(node.right);
  }
  getHeight(node) {
    var _node$left$height, _node$left3, _node$right$height, _node$right3;
    if (!node) return 0;
    return Math.max((_node$left$height = (_node$left3 = node.left) === null || _node$left3 === void 0 ? void 0 : _node$left3.height) !== null && _node$left$height !== void 0 ? _node$left$height : 0, (_node$right$height = (_node$right3 = node.right) === null || _node$right3 === void 0 ? void 0 : _node$right3.height) !== null && _node$right$height !== void 0 ? _node$right$height : 0) + 1;
  }
  getSize(node) {
    var _node$left$size, _node$left4, _node$right$size, _node$right4;
    if (!node) return 0;
    return ((_node$left$size = (_node$left4 = node.left) === null || _node$left4 === void 0 ? void 0 : _node$left4.size) !== null && _node$left$size !== void 0 ? _node$left$size : 0) + ((_node$right$size = (_node$right4 = node.right) === null || _node$right4 === void 0 ? void 0 : _node$right4.size) !== null && _node$right$size !== void 0 ? _node$right$size : 0) + node.count;
  }
  createNode(val) {
    return {
      id: Math.random() * new Date().valueOf(),
      val,
      left: null,
      right: null,
      size: 1,
      height: 1,
      count: 1
    };
  }
  insert(val) {
    let cur = this.createNode(val);
    if (this.isEmpty()) {
      this.root = cur;
      this.length++;
    } else {
      [, cur] = this.insertNode(this.root, cur);
    }
    if (this.min === null || this.compare(this.min, val) > 0) {
      this.min = val;
    }
    if (this.max === null || this.compare(this.max, val) < 0) {
      this.max = val;
    }
  }
  insertNode(node, cur, parent = null) {
    node.size++;
    const compareResult = this.compare(cur.val, node.val);
    let res;
    if (compareResult === 0) {
      node.count++;
      return [false, node];
    } else if (compareResult > 0) {
      if (node.right) {
        res = this.insertNode(node.right, cur, node);
        if (!res[0]) return res;
      } else {
        node.right = cur;
        this.length++;
        res = [true, cur];
      }
    } else {
      if (node.left) {
        res = this.insertNode(node.left, cur, node);
        if (!res[0]) return res;
      } else {
        node.left = cur;
        this.length++;
        res = [true, cur];
      }
    }
    let preHeight = node.height;
    const newNode = this.balance(node);
    if (newNode === node && node.height === preHeight) {
      res = [false, res[1]];
    } else if (newNode !== node) {
      if (parent) {
        parent.left === node ? parent.left = newNode : parent.right = newNode;
      } else {
        this.root = newNode;
      }
      res = [false, res[1]];
    }
    return res;
  }
  delete(val) {
    if (!this.root) return;
    this.deleteNode(val, this.root, null);
  }
  deleteNode(val, node, parent) {
    if (!node) return null;
    let res = this.compare(val, node.val);
    if (res === 0) {
      node.count--;
      node.size--;
      if (node.count > 0) return node;
      if (!node.left || !node.right) {
        if (this.min === val) {
          this.minCache = false;
        }
        if (this.max === val) {
          this.maxCache = false;
        }
        this.length--;
        if (!parent) {
          var _node$left5;
          this.root = (_node$left5 = node.left) !== null && _node$left5 !== void 0 ? _node$left5 : node.right;
          return this.root;
        } else {
          var _node$left6;
          return (_node$left6 = node.left) !== null && _node$left6 !== void 0 ? _node$left6 : node.right;
        }
      } else {
        const selectLeft = node.left.height > node.right.height;
        let replaceNode = selectLeft ? this.pre(node) : this.next(node),
            name = selectLeft ? 'left' : 'right';
        node.val = replaceNode.val;
        node.count = replaceNode.count;
        replaceNode.count = 0;
        node[name] = this.deleteNode(replaceNode.val, node[name], node);
      }
    } else if (res > 0) {
      node.right = this.deleteNode(val, node.right, node);
    } else {
      node.left = this.deleteNode(val, node.left, node);
    }
    node.size = this.getSize(node);
    node.height;
    const newNode = this.balance(node);
    if (parent) {
      parent.left === node ? parent.left = newNode : parent.right = newNode;
    } else {
      this.root = newNode;
    }
    return newNode;
  }
  next(node) {
    let next = node.right;
    while ((_next = next) !== null && _next !== void 0 && _next.left) {
      var _next;
      next = next.left;
    }
    return next;
  }
  pre(node) {
    let pre = node.left;
    while ((_pre = pre) !== null && _pre !== void 0 && _pre.right) {
      var _pre;
      pre = pre.right;
    }
    return pre;
  }
  search(val, compare) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, compare !== null && compare !== void 0 ? compare : this.compare);
    return node.val;
  }
  searchCeilingNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        return this.searchCeilingNode(node.right, val, compare, node);
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        const [p, value] = this.searchCeilingNode(node.left, val, compare, node);
        if (compare(value.val, val) < 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    }
  }
  ceiling(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, this.compare);
    return this.compare(node.val, val) >= 0 ? node.val : null;
  }
  searchFloorNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        const [p, value] = this.searchFloorNode(node.right, val, compare, node);
        if (compare(value.val, val) > 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        return this.searchFloorNode(node.left, val, compare, node);
      } else {
        return [parent, node];
      }
    }
  }
  floor(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchFloorNode(this.root, val, this.compare);
    return this.compare(node.val, val) <= 0 ? node.val : null;
  }
  searchKth(k) {
    if (this.isEmpty()) {
      return null;
    }
    if (k <= 0 || k > this.size()) {
      return null;
    }
    const node = this.searchNodeKth(this.root, k);
    return node.val;
  }
  searchNodeKth(node, k) {
    var _node$right$size2, _node$right5, _node$right$size3, _node$right6;
    const rSize = (_node$right$size2 = (_node$right5 = node.right) === null || _node$right5 === void 0 ? void 0 : _node$right5.size) !== null && _node$right$size2 !== void 0 ? _node$right$size2 : 0;
    if (rSize === k - 1 || rSize < k && rSize + node.count >= k) return node;
    if (node.right && rSize > k - 1) return this.searchNodeKth(node.right, k);else return this.searchNodeKth(node.left, k - ((_node$right$size3 = (_node$right6 = node.right) === null || _node$right6 === void 0 ? void 0 : _node$right6.size) !== null && _node$right$size3 !== void 0 ? _node$right$size3 : 0) - node.count);
  }
  countGreaterThanEq(val) {
    if (!this.root) return 0;
    return this.countCompare(val, (a, b) => this._compare(a, b), this.root);
  }
  countCompare(val, compare, node, pre = 0) {
    const res = compare(val, node.val);
    if (res === 0) {
      var _node$right$size4, _node$right7;
      return pre + ((_node$right$size4 = (_node$right7 = node.right) === null || _node$right7 === void 0 ? void 0 : _node$right7.size) !== null && _node$right$size4 !== void 0 ? _node$right$size4 : 0) + node.count;
    } else if (res > 0) {
      if (node.right) {
        return this.countCompare(val, compare, node.right, pre);
      } else {
        return pre;
      }
    } else {
      var _node$right$size5, _node$right8;
      let count = pre + ((_node$right$size5 = (_node$right8 = node.right) === null || _node$right8 === void 0 ? void 0 : _node$right8.size) !== null && _node$right$size5 !== void 0 ? _node$right$size5 : 0) + node.count;
      if (node.left) {
        return this.countCompare(val, compare, node.left, count);
      } else {
        return count;
      }
    }
  }
  toArray() {
    if (!this.root) return [];
    const res = [];
    const dfs = node => {
      if (node.left) dfs(node.left);
      res.push(node.val);
      if (node.right) dfs(node.right);
    };
    dfs(this.root);
    return res;
  }
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();


(function () {
	var line = readline().split(' ').map(function (e) {
		return parseInt(e);
	});
	var n = line[0],
		k = line[1];
	var s = readline();

	var ans1 = getAns(s,k,'a'),
		ans2 = getAns(s,k,'b');
	ans1 = ans1>ans2?ans1:ans2;
	print(ans1);

	function getAns (str, k, c) {
		var p = -1,
			nxt = 0,
			seg = [],
			l = str.length;
		do {
			nxt = str.indexOf(c, p+1);
			if(nxt<0)
				nxt = l;
			seg.push(nxt - p - 1);
			p = nxt;
		} while(p<l);
		if(seg.length<=k+1)
			return l;
		var i,
			j,
			ret,
			tmp=0;
		l = seg.length;
		for(i=0;i<=k;++i) {
			tmp += seg[i];
		}
		ret = tmp;
		for(j=0;i<l;++i,++j) {
			tmp+=seg[i]-seg[j];
			ret = tmp>ret?tmp:ret;
		}
		return ret+k;
	}

})();

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var bs_removed = {removed: 0};
var as_removed = {removed: 0};

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y, z, p) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;

		while (string[i] == y) {
			x[j] += 1;
			i++;
		}

		if (string[i] == z) {
	    	p.removed += 1;
	    }

		j++;
	}

	return x;
};

a_arr = (rewrite_string(a_arr, a, b, bs_removed)); // removing b's
b_arr = (rewrite_string(b_arr, b, a, as_removed)); // removing a's

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k && i < d.length; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
	    if (i + k <= d.length - 1) {
    		c += d[i + k] - d[i - 1];
    		if (c > e) {
    			e = c;
    		}
		}
	}

	return e;
};

// which sum is bigger? and could I remove k letters or did I not have that many to begin with?
if ((summing(sum_a, a_arr, max_sum_a) < summing(sum_b, b_arr, max_sum_b))) {
    if (as_removed.removed > k) {
	    print(summing(sum_b, b_arr, max_sum_b) + k);
    } else {
	    print(summing(sum_b, b_arr, max_sum_b) + as_removed.removed);
    }
} else {
    if (bs_removed.removed > k) {
	    print(summing(sum_a, a_arr, max_sum_a) + k);
    } else {
	    print(summing(sum_a, a_arr, max_sum_a) + bs_removed.removed);
    }
}

var nums = readline().split(" ").map(x => parseInt(x));
var n = nums[0];
var k = nums[1];
var str = readline();
print(solve(n, k, str));

function solve(n, k, str) {
    return Math.max(longest(n, k, str, "a"), longest(n, k, str, "b"));
}

function longest(n, k, str, c) {
    var max = 0;
    var p = 0;
    for (var i = 0; i < n; i++) {
        if (str[i] !== c) {
            k -= 1;
        }
        while (k < 0) {
            if (str[p] !== c) {
                k += 1;
            }
            p += 1;
        }
        max = Math.max(max, i - p + 1);
    }
    return max;
}

function main() {
  var input = readline().split(' ').map(Number);
  var n = input[0];
  var k = input[1];
  var str = readline();

  var prefixSum = [];
  for (var i = 0; i < n; ++i) {
    var value = (str.charAt(i) == "a" ? 1 : 0);
    if (i > 0) {
      value += prefixSum[i - 1];
    }
    prefixSum.push(value);
  }

  function rangeSum(prefixSum, st, ed) {
    if (st > 0) {
      return prefixSum[ed] - prefixSum[st - 1];
    } else {
      return prefixSum[ed];
    }
  }

  function check(prefixSum, n, k, m) {
    for (var i = 0; i < n; ++i) {
      var numOfA = rangeSum(prefixSum, i, i + m - 1);
      var numOfB = m - numOfA;
      if (Math.min(numOfA, numOfB) <= k) {
        return true;
      }
    }
    return false;
  }

  function binarySearch(prefixSum, n, k) {
    var lower = 1;
    var upper = n;
    while (upper - lower > 1) {
      var middle = Math.floor((lower + upper) / 2);
      if (check(prefixSum, n, k, middle)) {
        lower = middle;
      } else {
        upper = middle;
      }
    }
    return check(prefixSum, n, k, upper) ? upper : lower;
  }

  var result = binarySearch(prefixSum, n, k);
  print(result);
}

main();

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var bs_removed = {removed: 0};
var as_removed = {removed: 0};

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(new_array, letter_in_array, letter_removed, number_of_letters_removed) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    new_array[j] = 0;

		while (string[i] == letter_in_array) {
			new_array[j] += 1;
			i++;
		}

		if (string[i] == letter_removed) {
	    	number_of_letters_removed.removed += 1;
	    }

		j++;
	}

	return new_array;
};

a_arr = (rewrite_string(a_arr, a, b, bs_removed)); // removing b's
b_arr = (rewrite_string(b_arr, b, a, as_removed)); // removing a's

var max_sum_a = 0;
var max_sum_b = 0;

var summing = function(array, letters_removed) {
	var sum = 0;

	// First sum
	for (var i = 0; i <= k && i < array.length; i++) {
		sum += array[i];
	}

	var max_sum = sum;

	// Checking if other sums are bigger
	for (var i = 1; i + k <= array.length - 1; i++) {
		sum += array[i + k] - array[i - 1];
    	if (sum > max_sum) {
    		max_sum = sum;
    	}
	}

	max_sum += Math.min(k, letters_removed.removed);

	return max_sum;
};

max_sum_a = summing(a_arr, bs_removed);
max_sum_b = summing(b_arr, as_removed);

print(Math.max(max_sum_a, max_sum_b));

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;
		while (string[i] == y) {
			x[j] += 1;
			i++;
		}
		j++;
	}

	return x;
};

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k && i < d.length; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
	    if (i + k < d.length - 1) {
    		c += d[i + k] - d[i - 1];
    		if (c > e) {
    			e = c;
    		}
		}
	}

	return e;
};

var remove_b = summing(sum_a, a_arr, max_sum_a);
var remove_a = summing(sum_b, b_arr, max_sum_b);

print(Math.max(remove_b, remove_a) + k);

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;
		while (string[i] == y) {
			x[j] += 1;
			i++;
		}
		j++;
	}

	return x;
};

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k && i < d.length; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
	    if (i + k < d.length - 1) {
    		c += d[i + k] - d[i - 1];
    		if (c > e) {
    			e = c;
    		}
		}
	}

	return e;
};

print(Math.max(summing(sum_a, a_arr, max_sum_a), summing(sum_b, b_arr, max_sum_b)));

/* Sums for a_arr, not using this because I wrote a function
var sum_a = 0;

// First sum
for (var i = 0; i <= k; i++) {
	sum_a += a_arr[i];
}

var max_sum_a = sum_a;

// Checking if other sums are bigger
for (var i = 1; i < a_arr.length; i++) {
	sum_a += a_arr[i + k] - a_arr[i - 1];
	if (sum_a > max_sum_a) {
		max_sum_a = sum_a;
	}
}

print(max_sum_a);
*/

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var bs_removed = {removed: 0};
var as_removed = {removed: 0};

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y, z, p) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;

		while (string[i] == y) {
			x[j] += 1;
			i++;
		}

		if (string[i] == z) {
	    	p.removed += 1;
	    }

		j++;
	}

	return x;
};

a_arr = (rewrite_string(a_arr, a, b, bs_removed)); // removing b's
b_arr = (rewrite_string(b_arr, b, a, as_removed)); // removing a's

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k && i < d.length; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
	    if (i + k < d.length - 1) {
    		c += d[i + k] - d[i - 1];
    		if (c > e) {
    			e = c;
    		}
		}
	}

	return e;
};

// which sum is bigger? and could I remove k letters or did I not have that many to begin with?
if ((summing(sum_a, a_arr, max_sum_a) < summing(sum_b, b_arr, max_sum_b))) {
    if (as_removed.removed > k) {
	    print(summing(sum_b, b_arr, max_sum_b) + k);
    } else {
	    print(summing(sum_b, b_arr, max_sum_b) + as_removed.removed);
    }
} else {
    if (bs_removed.removed > k) {
	    print(summing(sum_a, a_arr, max_sum_a) + k);
    } else {
	    print(summing(sum_a, a_arr, max_sum_a) + bs_removed.removed);
    }
}

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;
		while (string[i] == y) {
			x[j] += 1;
			i++;
		}
		j++;
	}

	return x;
};

a_arr = (rewrite_string(a_arr, a));
b_arr = (rewrite_string(b_arr, b));

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k && i < d.length; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
	    if (i + k < d.length - 1) {
    		c += d[i + k] - d[i - 1];
    		if (c > e) {
    			e = c;
    		}
		}
	}

	return e;
};

if (string.length == 1) {
	print(1);
} else {
	print(Math.max(summing(sum_a, a_arr, max_sum_a), summing(sum_b, b_arr, max_sum_b)) + k);
}

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;
		while (string[i] == y) {
			x[j] += 1;
			i++;
		}
		j++;
	}

	return x;
};

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
		c += d[i + k] - d[i - 1];
		if (c > e) {
			e = c;
		}
	}

	return e;
};

print(Math.max(summing(sum_a, a_arr, max_sum_a), summing(sum_b, b_arr, max_sum_b)));

/* Sums for a_arr, not using this because I wrote a function
var sum_a = 0;

// First sum
for (var i = 0; i <= k; i++) {
	sum_a += a_arr[i];
}

var max_sum_a = sum_a;

// Checking if other sums are bigger
for (var i = 1; i < a_arr.length; i++) {
	sum_a += a_arr[i + k] - a_arr[i - 1];
	if (sum_a > max_sum_a) {
		max_sum_a = sum_a;
	}
}

print(max_sum_a);
*/

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;
		while (string[i] == y) {
			x[j] += 1;
			i++;
		}
		j++;
	}

	return x;
};

a_arr = (rewrite_string(a_arr, a));
b_arr = (rewrite_string(b_arr, b));

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k && i < d.length; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
	    if (i + k < d.length - 1) {
    		c += d[i + k] - d[i - 1];
    		if (c > e) {
    			e = c;
    		}
		}
	}

	return e;
};

print(Math.max(summing(sum_a, a_arr, max_sum_a), summing(sum_b, b_arr, max_sum_b)) + k);

var nums = readline().split(" ").map(x => parseInt(x));
var n = nums[0];
var k = nums[1];
var str = readline();
print(solve(n, k, str));

function solve(n, k, str) {
    return Math.max(longest(n, k, str, "a"), longest(n, k, str, "b"));
}

function longest(n, k, str, c) {
    var max = 0;
    var p = 0;
    for (var i = 0; i < n; i++) {
        if (str[i] !== c) {
            k -= 1;
        }
        while (k < 0) {
            if (str[p] !== c) {
                k += 1;
            }
            p += 1;
        }
        max = Math.max(max, i - p);
    }
    return max;
}


"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, k] = iInpArr();
    let arr = iInpArr1();
    let res = new Array(n).fill(0);
    if (k % 2 === 1) {
      let flag = 0;
      for (let i = 0; i < n - 1; i++) {
        if (arr[i] === 0) arr[i] = 1;
        else if (arr[i] === 1 && flag === 0) {
          res[i]++;
          flag = 1;
        } else arr[i] = 0;
      }
      if (flag === 1) arr[n - 1] = arr[n - 1] === 0 ? 1 : 0;
      else res[n-1]++;
      k--;
    }
    for (let i = 0; i < n; i++) {
      if (i === n - 1 && k > 0) {
        if (k % 2 !== 0) arr[i] = arr[i] === 0 ? 1 : 0;
        res[i] += k;
      } else if (arr[i] === 0 && k > 0) {
        arr[i] = 1;
        res[i]++;
        k--;
      }
    }
    console.log(arr.join(""));
    console.log(res.join(" "));
  }
};
solve();

'use strict';
const readline = require('readline');
const util = require('util');
const lineReader = readline.createInterface({
    input: process.stdin,
});
let inputPos = 0;
const inputWords = [];
lineReader.on('line', (line) => {
    inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));
});
lineReader.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(inputWords[inputPos++]));
}
function nextStr() {
    return inputWords[inputPos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
const INF = Infinity;
let n;
let k;
let s;
function solve() {
    const a = af(n);
    for (let i = 0; i < n; i++) {
        a[i] = (s[i] == '1' ? 1 : 0);
    }
    // printf("n %d k %d s %s a %j\n", n, k, s, a);
    const K = k;
    const ans = af(n).fill(0);
    const keven = ((k % 2) == 0 ? true : false);
    for (let i = 0; i + 1 < n && k > 0; i++) {
        if (keven && a[i] == 0) {
            ans[i]++;
            k--;
        }
        else if (!keven && a[i] == 1) {
            ans[i]++;
            k--;
        }
    }
    ans[n - 1] = k;
    const b = af(n);
    for (let i = 0; i < n; i++) {
        b[i] = (a[i] + ans[i] + K) % 2;
        // printf("%d", (a[i] + ans[i] + K) % 2), ' ');
    }
    process.stdout.write(b.join(''));
    process.stdout.write('\n');
    process.stdout.write(ans.join(' '));
    process.stdout.write('\n');
}
function main() {
    let tc = nextInt();
    while (tc--) {
        n = nextInt();
        k = nextInt();
        s = nextStr();
        solve();
    }
}

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

function div(val, by){
    return (val - val % by) / by;
}

const calc = (n, k, bits)=>{
    let usage = new Array(n).fill(0);
    let originalK = k;

    let flipped = 0;

    for (let i = 0; i < n; i++) {
        let flips = k % 2;
        let res = bits[i] ^ flipped ^ flips;
        if (!res && k) {
            k--;
            usage[i]++;
            flipped = 1 - flipped;
        }
    }
    usage[n - 1] += k;

    for (let i = 0; i < n; i++) {
        let flips = (originalK - usage[i]) % 2;
        bits[i] = bits[i] ^ flips;
    }

    return `${bits.join('')}\n${usage.join(' ')}`;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let [n, k] = ra();
        let bits = readline().split('').map(a=>+a);
        console.log(`${calc(n, k, bits)}`);
    }
}

const processData = (lines) => {
    let n = +lines[0]
    let cur = 0
    while(n--) {
        cur++
        let [_, k] = lines[cur].split(' ').map(x => +x)
        cur++
        let str = lines[cur].split('').map(x => +x)

        let xor = k%2;
        for (let i=0; i<str.length; i++) {
            str[i] = str[i]^xor;
        }
        let res = new Array(str.length);
        for (let i=0; i<res.length; i++) {
            res[i] = 0;
        }
        for (let i=0; i<str.length && k > 0; i++) {
            if (str[i] === 0) {
                k--;
                str[i] = 1;
                res[i] = 1;
            }
        }

        if (k) {
            if (k%2 === 0) {
                res[0] += k;
            } else {
                res[res.length-1] += k;
                str[str.length-1] ^= 1;;
            }
        }
        console.log(str.join(''));
        console.log(res.join(' '))
    }
}

let i = []
process.stdin.on('data', c => i.push(c))
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.join('').split(EOL) /*your input text, split by lines*/
    processData(lines)
})

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        const str = lines[l++]
        output[i] = solve(n, k, str)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, k, str) {
    const ans = Array(n).fill(0)
    const final = str.split('')
    let used = 0
    for (let i = 0; i < str.length; i++) {
        const ch = str[i]
        let x
        // flip k - x
        if (ch === '1') {
            // k - x is even
            if (k & 1) {
                x = 1
            } else {
                x = 0
            }
        } else {
            // k - x is odd
            if (k & 1) {
                x = 0
            } else {
                x = 1
            }
        }
        //
        if (used >= k) x = 0
        if (i === n - 1) x = k - used
        ans[i] = x
        used += x
        //
        if ((k - x) & 1) {
            final[i] = ch === '1' ? '0' : '1'
        // } else {
        //     final = ch
        }
    }
    return final.join('') + '\n' + ans.join(' ')
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, k] = iInpArr();
    let arr = iInpArr1();
    let res = new Array(n).fill(0);
    if (k % 2 === 1) {
      let flag = 0;
      for (let i = 0; i < n - 1; i++) {
        if (arr[i] === 0) arr[i] = 1;
        else if (arr[i] === 1 && flag === 0) {
          flag = 1;
        } else arr[i] = 0;
      }
      if (flag === 1) arr[n - 1] = arr[n - 1] === 0 ? 1 : 0;
      k--;
    }
    for (let i = 0; i < n; i++) {
      if (i === n - 1 && k > 0) {
        if (k % 2 !== 0) arr[i] = arr[i] === 0 ? 1 : 0;
        res[i] += k;
      } else if (arr[i] === 0 && k > 0) {
        arr[i] = 1;
        res[i]++;
        k--;
      }
    }
    console.log(arr.join(""));
    console.log(res.join(" "));
  }
};
solve();


'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function readInt() {
  return readline()|0
}

function readIntArr() {
  return readline().split(' ').map(x => x|0)
}

function main() {
   const n = readInt();

   for(let i=0; i < n; i++) {
     let [a, b] = readIntArr();
     let phase = 1;
     if(b === 1) {
       phase = 2;
     }

     const func = () => {
       for(let i = 1; i <= phase; i++) {
         if (((b + phase) - i)**(i) > a) return false;
       }

       return true;
     }

     while (func()) {
      phase++;
     }

     console.log(phase);
   }
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (k > n) console.log(1);
    else if (n === k) console.log(2);
    else {
      const red = (n, k) => {
        let cnt = 0;
        while (n > 0) {
          n = Math.floor(n / k);
          cnt++;
        }
        return cnt;
      };
      let cnt = 0;
      if (k === 1) {
        k++;
        cnt++;
      }
      let prev = red(n, k) + cnt;
      while (true) {
        k++;
        cnt++;
        let l = red(n, k) + cnt;
        if (prev < l) {
          console.log(prev);
          break;
        } else prev = l;
      }
    }
  }
};
solve();

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------

function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var A = nextInt();
		var B = nextInt();
		var add = 0;
		if(B == 1){
			add = 1;
			B++;
		}
		var now = B;
		var output = Math.pow(10, 15);
		while(true){
			var tmp = A;
			var count = now - B;
			while(tmp > 0){
				count++;
				tmp = Math.floor(tmp / now);
			}
			if(output >= count){
				output = count;
			}else{
				break;
			}
			now++;
		}
		myout(output + add);
	}
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function readInt() {
  return readline()|0
}

function readIntArr() {
  return readline().split(' ').map(x => x|0)
}

function main() {
  const N = readInt()
  for (let i = 0; i < N; ++i) {
    let total = 1
    let c = 0
    let [a, b] = readIntArr()
    if (b == 1) {
      b += 1
      c = 1
    }

    function found(a, b, total) {
      let fo = false
      for (let i = 0; i < total; i++) {
        if (((b + i) ** (total - i) > a)) {
          fo = true;
        }
      }
      return fo
    }

    while (!found(a, b, total)) {
      total += 1
    }
    console.log(total + c)
  }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    // 1 1 7
    // 6 9, 15, 18

    var answer = {}

    Array(Number(x)).fill(1).map((t, i) => {
        var [a, b] = readline().split(' ').map((x, i) => {
            // if (minA > Number(x)) minA = Number(x)
            return parseInt(x)
        })
        var min = 100000000
        var bb
        var aa
        if (a < b) return console.log(1)

        for (var i = 0; i < 1000; i++) {
            aa = a
            answer = i
            bb = b + i
            if (bb === 1) continue

            while (aa !== 0) {
                aa = Math.floor(aa / bb)
                answer += 1
            }
            // console.log(a,bb, answer)

            // console.log(min)
            min = Math.min(min, answer)
        }
        console.log(min)
        // console.log(Math.min(answer, answer2))

    })
}

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function readInt() {
  return readline()|0
}

function readIntArr() {
  return readline().split(' ').map(x => x|0)
}

function main() {
  const N = readInt()
  for (let i = 0; i < N; ++i) {
    let total = 1
    let c = 0
    let [a, b] = readIntArr()
    if (b == 1) {
      b += 1
      c = 1
    }
    while (b ** total <= a && (b + 1) ** (total - 1) <= a && (b + 2) ** (total - 2) <= a) {
      total += 1
    }
    console.log(total + c)
  }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function readInt() {
  return readline()|0
}

function readIntArr() {
  return readline().split(' ').map(x => x|0)
}

function main() {
  const N = readInt()
  for (let i = 0; i < N; ++i) {
    let total = 1
    let c = 0
    let [a, b] = readIntArr()
    if (b == 1) {
      b += 1
      c = 1
    }
    while (b ** total < a && (b + 1) ** (total - 1) < a && (b + 2) ** (total - 2) < a) {
      total += 1
    }
    console.log(total + c)
  }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    // 1 1 7
    // 6 9, 15, 18

    var answer = {}

    Array(Number(x)).fill(1).map((t, i) => {
        var [a, b] = readline().split(' ').map((x, i) => {
            // if (minA > Number(x)) minA = Number(x)
            return parseInt(x)
        })
        var min = 100000000
        var bb
        var aa
        if (a < b) return console.log(1)

        for (var i = 0; i < 5; i++) {
            aa = a
            answer = i
            bb = b + i
            if (bb === 1) continue

            while (aa !== 0) {
                aa = Math.floor(aa / bb)
                answer += 1
            }
            // console.log(a,bb, answer)

            // console.log(min)
            min = Math.min(min, answer)
        }
        console.log(min)
        // console.log(Math.min(answer, answer2))

    })
}

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    // 1 1 7
    // 6 9, 15, 18

    var answer = {}

    Array(Number(x)).fill(1).map((t, i) => {
        var [a, b] = readline().split(' ').map((x, i) => {
            // if (minA > Number(x)) minA = Number(x)
            return parseInt(x)
        })
        var answer = 0
        var answer2 = 0
        if (a < b) return console.log(1)
        if(b===1)  {
            answer = 1
            answer2 = 2
            b = 2
        }
        // console.log(b,a)

        var bb = b +1
        var aa = a
        while(a!==0){
            a=Math.floor(a/b)
            answer+=1
        }

        while(aa!==0){
            aa=Math.floor(aa/bb)
            answer2+=1
        }
        console.log(Math.min(answer, answer2))

    })
}

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
let obj = {};
const precompute = () => {
  for (let i = 1; i <= 10000; i++) obj[i * i * i] = 1;
};
const solve = () => {
  let t = parseInt(readline());
  precompute();
  while (t--) {
    let [n, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (k > n) console.log(1);
    else {
      if (n === k) console.log(2);
      else {
        let cnt = 0;
        if (n % k === 0) {
          k += 2;
          cnt += 2;
        }
        while (n > 0) {
          cnt++;
          n = Math.floor(n / k);
        }
        console.log(cnt);
      }
    }
  }
};
solve();