let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    const str = readLine();
    const w = +readLine();
    const len = str.length;

    const arr = [...Array(str.length).fill(1)];
    let flag = true;

    if (w >= len) {
      console.log(-1);
      continue;
    }
    for (let i = 0; i < len; i++) {
      if (str[i] === "0") {
        if (i - w >= 0) {
          arr[i - w] = 0;
        }
        if (i + w < len) {
          arr[i + w] = 0;
        }
      }
    }

    for (let i = 0; i < len; i++) {
      if (str[i] === "1") {
        if (arr[i - w] !== 1 && arr[i + w] !== 1) {
          flag = false;
          break;
        }
      }
    }

    if (flag) console.log(arr.join(""));
    else console.log(-1);
  }
}

'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() {
  const t = parseInt(readline());
  for (var i=0; i<t; i++) {
    const s = readline();
    const x = parseInt(readline());

    let w = new Array(s.length).fill("1");
    for (let j=0; j<s.length; j++) {
      if (s[j] == "0") {
        if (j+x<s.length) w[j+x]="0";
        if (j-x >= 0) w[j-x]="0";
      }
    }
    let ok = true;
    for (let j=0; j<s.length; j++) {
      if (s[j] == "1") {
        if (!(j+x<s.length && w[j+x] == "1") &&
          !(j-x >=0 && w[j-x] == "1")) {
          ok = false;
        }
      }
    }
    console.log(ok ? w.join('') : "-1");
  }
}

const readline = require('readline');
const fs = require('fs');

const rl = readline.createInterface({
  input: process.env.TEST ? fs.createReadStream('input.txt') : process.stdin,
  output: process.stdout,
});
/** @type {Array<String>} */
const lines = [];

rl.on('line', (line) => lines.push(line));

rl.on('close', task);

function nextNumber() {
  return Number(lines.shift());
}
function nextNumbers() {
  return lines
    .shift()
    .split(' ')
    .map((x) => Number(x));
}

function nextString() {
  return lines.shift();
}

function task() {
  let t = nextNumber();
  while (t--) {
    let s = nextString().split('');
    let x = nextNumber();
    let arr = new Array(s.length).fill('1');
    s.forEach((n, i) => {
      if (n === '0') {
        if (i - x >= 0) {
          arr[i - x] = '0';
        }
        if (i + x < arr.length) {
          arr[i + x] = '0';
        }
      }
    });
    const success = s.every((n, i) => {
      let c1 = i - x >= 0 && arr[i - x] === '1';
      let c2 = i + x <= s.length && arr[i + x] === '1';
      if (c1 || c2) {
        return n === '1';
      }
      return n === '0';
    });
    if (!success) {
      console.log('-1');
    } else {
      console.log(arr.join(''));
    }
  }
}

const readline = require('readline');
const fs = require('fs');

const rl = readline.createInterface({
  input: process.env.TEST ? fs.createReadStream('input.txt') : process.stdin,
  output: process.stdout,
});
/** @type {Array<String>} */
const lines = [];

rl.on('line', (line) => lines.push(line));

rl.on('close', task);

function nextNumber() {
  return Number(lines.shift());
}
function nextNumbers() {
  return lines
    .shift()
    .split(' ')
    .map((x) => Number(x));
}

function nextString() {
  return lines.shift();
}

function task() {
  let t = nextNumber();
  while (t--) {
    let s = nextString().split('');
    let x = nextNumber();
    let arr = new Array(s.length).fill('1');
    s.forEach((n, i) => {
      if (n === '0') {
        if (i - x >= 0) {
          arr[i - x] = '0';
        }
        if (i + x < arr.length) {
          arr[i + x] = '0';
        }
      }
    });
    const success = arr.every((n, i) => {
      let c1 = i - x >= 0 && arr[i - x] === '1';
      let c2 = i + x <= s.length && arr[i + x] === '1';
      if (c1 || c2) {
        return s[i] === '1';
      }
      return s[i] === '0';
    });
    // let success = true;
    // s.forEach((n, i) => {
    //   if (n === '1') {
    //     let any = false;
    //     if (i - x >= 0 && arr[i - x] !== '0') {
    //       arr[i - x] = '1';
    //       any = true;
    //     }
    //     // console.log(n, i, i + x, arr[i + x]);
    //     if (i + x < arr.length && arr[i + x] !== '0') {
    //       arr[i + x] = '1';
    //       any = true;
    //     }
    //     if (!any) {
    //       success = false;
    //     }
    //   }
    // });
    // console.log(arr.join(''));
    if (!success) {
      console.log('-1');
    } else {
      console.log(arr.join(''));
    }
    // 2
    // 10110110
    // ??00?00?
  }
}

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

    probC();
});

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

function probA(){
    let t = parseInt(readline());
    while(t > 0){
        t--;

        let n = parseInt(readline());
        let s = readline().split('');
        let c = s[n-1];
        let res = '';
        for(let i = 0;  i< n; i++){
            res += c;
        }

        console.log(res);
    }
}

function probB(){
    let t = parseInt(readline());

    while(t > 0){
        t--;
        let [p,f] = readline().split(' ');
        let cap = parseInt(p) + parseInt(f);

        let [cs, cw] = readline().split(' ');
        let [s, w] = readline().split(' ');

        let ava = (parseInt(cs) * parseInt(s)) + (parseInt(cw) * parseInt(w));

        let tot = parseInt(cs) + parseInt(cw);
        if(cap > ava){
            console.log(tot);
            continue;
        }

        let x = Math.min(parseInt(s), parseInt(w));
        if(parseInt(s) === x){
            if(parseInt(cs) * x > cap){
                console.log(Math.floor(cap / parseInt(cs)));
            }else{
                let rem = cap - (x * parseInt(cs));
                console.log(parseInt(cs) + Math.floor(rem/parseInt(w)));
            }
        }else{
            if(parseInt(cw) * x > cap){
                console.log(Math.floor(cap / parseInt(cw)));
            }else{
                let rem = cap - (x * parseInt(cw));
                console.log(parseInt(cw) + Math.floor(rem/parseInt(s)));
            }
        }
    }
}

function probC(){
    let t = parseInt(readline());
    while(t > 0){
        t--;

        let s = readline().split('');
        let x = parseInt(readline());
        let isPossible = true;

        let w = new Array(s.length);
        for(let i = 0; i < s.length; i++){
            if(s[i] === '0'){
                if(i+x < s.length)
                    w[i+x] = '0';

                if(i-x >= 0)
                    w[i-x] = '0';
            }
        }

        if(!isPossible){
            console.log(-1);
            continue;
        }

        for(let i = 0; i < s.length; i++){
            if(w[i] !== '0')
                w[i] = '1';
        }

        for(let i = 0; i < s.length; i++){
            if(s[i] === '1'){
                if(i+x < s.length && i-x >= 0){
                    if(w[i+x] === '0' && w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }
                else if(i+x < s.length){
                    if(w[i+x] === '0'){
                        isPossible = false;
                        break;
                    }
                }else if(i-x >= 0){
                    if(w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }else{
                    isPossible = false;
                    break;
                }
            }
        }

        if(!isPossible){
            console.log(-1);
            continue;
        }

        console.log(w.join(''));
    }
}

var numCases = parseInt(readline());
for (var i = 0; i < numCases; i ++) {
    var str = readline();
    var x = parseInt(readline());
    var output = [];
    for (var j = 0; j < str.length; j ++) output.push('1');
    for (var j = 0; j < str.length; j ++) {
        if (str[j] === '0') {
            if (j - x >= 0) {
                output[j - x] = '0';
            }
            if (j + x < str.length) {
                output[j + x] = '0';
            }
        }
    }
    for (var j = 0; j < str.length; j ++) {
        if (str[j] === '1') {
            if ((j - x < 0 || output[j - x] === '0')
            && (j + x >= str.length || output[j + x] === '0')) {
                output = ['-1'];
            }
        }
    }
    print(output.join(''));
}

var numCases = parseInt(readline());
for (var i = 0; i < numCases; i ++) {
    var str = readline();
    var x = parseInt(readline());
    var output = '';
    for (var j = 0; j < str.length; j ++) output += '1';
    for (var j = 0; j < str.length; j ++) {
        if (str[j] === '0') {
            if (j - x >= 0) {
                output[j - x] = '0';
            }
            if (j + x < str.length) {
                output[j + x] = '0';
            }
        }
    }
    for (var j = 0; j < str.length; j ++) {
        if (str[j] === '1') {
            if ((j - x < 0 || output[j - x] === '0') && (j + x >= str.length || output[j + x] === '0')) {
                output = '-1';
            }
        }
    }
    print(output);
}

var numCases = parseInt(readline());
for (var i = 0; i < numCases; i ++) {
    var str = readline();
    var x = parseInt(readline());
    var output = [];
    for (var j = 0; j < str.length; j ++) output.push('1');
    for (var j = 0; j < str.length; j ++) {
        if (str[j] === '0') {
            if (j - x >= 0) {
                output[j - x] = '0';
            }
            if (j + x < str.length) {
                output[j + x] = '0';
            }
        }
    }
    for (var j = 0; j < str.length; j ++) {
        if (str[j] === '1') {
            if ((j - x < 0 || output[j - x] === '0')
            && (j + x >= str.length || output[j + x] === '0')) {
                output = ['-1'];
            }
        }
    }
    print(output.join());
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    const str = readLine();
    const w = +readLine();
    const len = str.length;

    const arr = [...Array(str.length).fill(-1)];
    let flag = true;

    for (let i = 0; i < len; i++) {
      if (str[i] === "1") {
        if (i - w >= 0) {
          if (arr[i - w] === 0) {
            flag = false;
            break;
          } else {
            arr[i - w] = 1;
          }
        }
        if (i + w < len) {
          if (arr[i + w] === 0) {
            flag = false;
            break;
          } else {
            arr[i + w] = 1;
          }
        }
      } else {
        if (i - w >= 0) {
          if (arr[i - w] === 1) {
            flag = false;
            break;
          } else {
            arr[i - w] = 0;
          }
        }
        if (i + w < len) {
          if (arr[i + w] === 1) {
            flag = false;
            break;
          } else {
            arr[i + w] = 0;
          }
        }
      }
    }

    if (flag) console.log(arr.join(""));
    else console.log(-1);
  }
}

const readline = require('readline');
const fs = require('fs');

const rl = readline.createInterface({
  input: process.env.TEST ? fs.createReadStream('input.txt') : process.stdin,
  output: process.stdout,
});
/** @type {Array<String>} */
const lines = [];

rl.on('line', (line) => lines.push(line));

rl.on('close', task);

function nextNumber() {
  return Number(lines.shift());
}
function nextNumbers() {
  return lines
    .shift()
    .split(' ')
    .map((x) => Number(x));
}

function nextString() {
  return lines.shift();
}

function task() {
  let t = nextNumber();
  while (t--) {
    let s = nextString().split('');
    let x = nextNumber();
    let arr = new Array(s.length).fill('?');
    s.forEach((n, i) => {
      if (n === '0') {
        if (i - x >= 0) {
          arr[i - x] = '0';
        }
        if (i + x < arr.length) {
          arr[i + x] = '0';
        }
      }
    });
    let success = true;
    s.forEach((n, i) => {
      if (n === '1') {
        let any = false;
        if (i - x >= 0 && arr[i - x] !== '0') {
          arr[i - x] = '1';
          any = true;
        }
        // console.log(n, i, i + x, arr[i + x]);
        if (i + x < arr.length && arr[i + x] !== '0') {
          arr[i + x] = '1';
          any = true;
        }
        if (!any) {
          success = false;
        }
      }
    });
    // console.log(arr.join(''));
    if (!success) {
      console.log('-1');
    } else {
      console.log(arr.join(''));
    }
    // 2
    // 10110110
    // ??00?00?
  }
}

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

    probC();
});

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

function probA(){
    let t = parseInt(readline());
    while(t > 0){
        t--;

        let n = parseInt(readline());
        let s = readline().split('');
        let c = s[n-1];
        let res = '';
        for(let i = 0;  i< n; i++){
            res += c;
        }

        console.log(res);
    }
}

function probB(){
    let t = parseInt(readline());

    while(t > 0){
        t--;
        let [p,f] = readline().split(' ');
        let cap = parseInt(p) + parseInt(f);

        let [cs, cw] = readline().split(' ');
        let [s, w] = readline().split(' ');

        let ava = (parseInt(cs) * parseInt(s)) + (parseInt(cw) * parseInt(w));

        let tot = parseInt(cs) + parseInt(cw);
        if(cap > ava){
            console.log(tot);
            continue;
        }

        let x = Math.min(parseInt(s), parseInt(w));
        if(parseInt(s) === x){
            if(parseInt(cs) * x > cap){
                console.log(Math.floor(cap / parseInt(cs)));
            }else{
                let rem = cap - (x * parseInt(cs));
                console.log(parseInt(cs) + Math.floor(rem/parseInt(w)));
            }
        }else{
            if(parseInt(cw) * x > cap){
                console.log(Math.floor(cap / parseInt(cw)));
            }else{
                let rem = cap - (x * parseInt(cw));
                console.log(parseInt(cw) + Math.floor(rem/parseInt(s)));
            }
        }
    }
}

function probC(){
    let t = parseInt(readline());
    while(t > 0){
        t--;

        let s = readline().split('');
        let x = parseInt(readline());
        let isPossible = true;

        let w = new Array(s.length);
        for(let i = 0; i < s.length; i++){
            if(s[i] === '0'){
                if(i+x < s.length)
                    w[i+x] = '0';

                if(i-x >= 0)
                    w[i-x] = '0';

                if(i+x >= s.length && i-x < 0){
                    isPossible = false;
                    break;
                }
            }
        }

        if(!isPossible){
            console.log(-1);
            continue;
        }

        for(let i = 0; i < s.length; i++){
            if(w[i] !== '0')
                w[i] = '1';
        }

        for(let i = 0; i < s.length; i++){
            if(s[i] === '1'){
                if(i+x < s.length && i-x >= 0){
                    if(w[i+x] === '0' && w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }
                else if(i+x < s.length){
                    if(w[i+x] === '0'){
                        isPossible = false;
                        break;
                    }
                }else if(i-x >= 0){
                    if(w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }
            }
        }

        if(!isPossible){
            console.log(-1);
            continue;
        }

        console.log(w.join(''));
    }
}

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

    probC();
});

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

function probA(){
    let t = parseInt(readline());
    while(t > 0){
        t--;

        let n = parseInt(readline());
        let s = readline().split('');
        let c = s[n-1];
        let res = '';
        for(let i = 0;  i< n; i++){
            res += c;
        }

        console.log(res);
    }
}

function probB(){
    let t = parseInt(readline());

    while(t > 0){
        t--;
        let [p,f] = readline().split(' ');
        let cap = parseInt(p) + parseInt(f);

        let [cs, cw] = readline().split(' ');
        let [s, w] = readline().split(' ');

        let ava = (parseInt(cs) * parseInt(s)) + (parseInt(cw) * parseInt(w));

        let tot = parseInt(cs) + parseInt(cw);
        if(cap > ava){
            console.log(tot);
            continue;
        }

        let x = Math.min(parseInt(s), parseInt(w));
        if(parseInt(s) === x){
            if(parseInt(cs) * x > cap){
                console.log(Math.floor(cap / parseInt(cs)));
            }else{
                let rem = cap - (x * parseInt(cs));
                console.log(parseInt(cs) + Math.floor(rem/parseInt(w)));
            }
        }else{
            if(parseInt(cw) * x > cap){
                console.log(Math.floor(cap / parseInt(cw)));
            }else{
                let rem = cap - (x * parseInt(cw));
                console.log(parseInt(cw) + Math.floor(rem/parseInt(s)));
            }
        }
    }
}

function probC(){
    let t = parseInt(readline());
    while(t > 0){
        t--;

        let s = readline().split('');
        let x = parseInt(readline());
        let isPossible = true;

        let w = new Array(s.length);
        for(let i = 0; i < s.length; i++){
            if(s[i] === '0'){
                if(i+x < s.length)
                    w[i+x] = '0';

                if(i-x >= 0)
                    w[i-x] = '0';
            }
        }

        if(!isPossible){
            console.log(-1);
            continue;
        }

        for(let i = 0; i < s.length; i++){
            if(w[i] !== '0')
                w[i] = '1';
        }

        for(let i = 0; i < s.length; i++){
            if(s[i] === '1'){
                if(i+x < s.length && i-x >= 0){
                    if(w[i+x] === '0' && w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }
                else if(i+x < s.length){
                    if(w[i+x] === '0'){
                        isPossible = false;
                        break;
                    }
                }else if(i-x >= 0){
                    if(w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }
            }
        }

        if(!isPossible){
            console.log(-1);
            continue;
        }

        console.log(w.join(''));
    }
}

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

    probC();
});

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

function probA(){
    let t = parseInt(readline());
    while(t > 0){
        t--;

        let n = parseInt(readline());
        let s = readline().split('');
        let c = s[n-1];
        let res = '';
        for(let i = 0;  i< n; i++){
            res += c;
        }

        console.log(res);
    }
}

function probC(){
    let t = parseInt(readline());
    while(t > 0){
        t--;

        let s = readline().split('');
        let x = parseInt(readline());
        let isPossible = true;

        let w = new Array(s.length);
        for(let i = 0; i < s.length; i++){
            if(s[i] === '0'){
                if(i+x < s.length)
                    w[i+x] = '0';

                if(i-x >= 0)
                    w[i-x] = '0';

                if(i+x > s.length && i-x < 0){
                    isPossible = false;
                    break;
                }
            }
            else{
                if(i+x < s.length && i-x >= 0){
                    if(w[i+x] === '0' && w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }
                else if(i+x < s.length){
                    if(w[i+x] === '0'){
                        isPossible = false;
                        break;
                    }
                }else if(i-x >= 0){
                    if(w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }
            }
        }

        if(!isPossible){
            console.log(-1);
            continue;
        }

        for(let i = 0; i < s.length; i++){
            if(w[i] !== '0')
                w[i] = '1';
        }

        for(let i = 0; i < s.length; i++){
            if(s[i] === '1'){
                if(i+x < s.length && i-x >= 0){
                    if(w[i+x] === '0' && w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }
                else if(i+x < s.length){
                    if(w[i+x] === '0'){
                        isPossible = false;
                        break;
                    }
                }else if(i-x >= 0){
                    if(w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }
            }
        }

        if(!isPossible){
            console.log(-1);
            continue;
        }

        console.log(w.join(''));
    }
}

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

    probC();
});

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

function probA(){
    let t = parseInt(readline());
    while(t > 0){
        t--;

        let n = parseInt(readline());
        let s = readline().split('');
        let c = s[n-1];
        let res = '';
        for(let i = 0;  i< n; i++){
            res += c;
        }

        console.log(res);
    }
}

function probC(){
    let t = parseInt(readline());
    while(t > 0){
        t--;

        let s = readline().split('');
        let x = parseInt(readline());
        let isPossible = true;

        let w = new Array(s.length);
        for(let i = 0; i < s.length; i++){
            if(s[i] === '0'){
                if(i+x < s.length)
                    w[i+x] = '0';

                if(i-x >= 0)
                    w[i-x] = '0';

                if(i+x >= s.length && i-x < 0){
                    isPossible = false;
                    break;
                }
            }
            else{
                if(i+x < s.length && i-x >= 0){
                    if(w[i+x] === '0' && w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }
                else if(i+x < s.length){
                    if(w[i+x] === '0'){
                        isPossible = false;
                        break;
                    }
                }else if(i-x >= 0){
                    if(w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }
            }
        }

        if(!isPossible){
            console.log(-1);
            continue;
        }

        for(let i = 0; i < s.length; i++){
            if(w[i] !== '0')
                w[i] = '1';
        }

        for(let i = 0; i < s.length; i++){
            if(s[i] === '1'){
                if(i+x < s.length && i-x >= 0){
                    if(w[i+x] === '0' && w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }
                else if(i+x < s.length){
                    if(w[i+x] === '0'){
                        isPossible = false;
                        break;
                    }
                }else if(i-x >= 0){
                    if(w[i-x] === '0'){
                        isPossible = false;
                        break;
                    }
                }
            }
        }

        if(!isPossible){
            console.log(-1);
            continue;
        }

        console.log(w.join(''));
    }
}


var n = Number(readline().split());
var s = readline();
var ats = 0;

var R = -1;
var L = -1;

for(var i=0; i<n; i++)
if(s.slice(i,i+1)=='R')
{
	if(L==-1)ats+=i;
	else ats+=i-L-1;
	R=i;
}
else if(s.slice(i,i+1)=='L')
{
	if(R!=-1 && (i-R+1)%2==1)ats++;
	L=i;
}

if(L > R)ats+=n-L-1;
if(L==-1 && R==-1)ats = n;

print(ats);

;(function () {

	print(function (n, s) {
		return -2 +
			(s.match(/R\.*L/g)||['']).reduce(function (p, e) { return p + (e.length % 2); }, 0) +
			(s.match(/L\.*R/g)||['  ']).reduce(function (p, e) { return p + (e.length - 2); }, 0) +
			(s.match(/^\.*R/)||[' '])[0].length +
			(s.match(/L\.*$/)||[' '])[0].length +
			(s.match(/^\.*$/)||[''])[0].length;
	}(+readline(), readline()));

}).call(this);

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i]);
	};
	return tokens;
}

function main() {
	var n = parseInt(readline());
	var s = trim(readline()).split('');

	var standing = 0;

	var pos = 0;
	while (pos < n && s[pos] == '.') {
		pos += 1;
	}
	if (pos == n) {
		print(n);
		return;
	}
	if (s[pos] == 'R') {
		standing += pos;
	}

	while (true) {
		var seek = pos+1;
		while (seek < n && s[seek] == '.') {
			seek += 1;
		}
		if (seek == n) {
			if (s[pos] == 'L') {
				standing += n-1-pos;
			}
			break;
		}

		if (s[pos] == 'L') {
			standing += seek-pos-1;
		}
		else {
			standing += (seek-pos-1)%2;
		}

		pos = seek;
	}

	print(standing);
}

main();

readline();

var s = readline(),
    j,
    ans = 0;

s = 'L' + s + 'R';

for (var i=0, len=s.length; i<len; i++) {
    var cur = s.charAt( i )

    if ('.' !== cur) {
        var pr = s.charAt( j );

        if ('R' === cur && 'L' === pr) {
            ans += i - j - 1;
        } else if ('L' === cur && 'R' === pr) {
            0 === (i-j)%2 && ans++;
        }

        j = i;
    }
}

print( ans );

var n = +readline();
var s = readline();
count = 0;
count1 = 0;
countr = 0;
countl = 0;
for (var i=0; i<n; i++)	{
	if (s[i]=='.') {
		count1++;
		if (countl == 1 && i == n-1) count += count1;
	}
	if (s[i]=='R') {
		count += count1;
		count1 = 0;
		countr = 1;
		countl = 2;
	}
	if (s[i]=='L') {
		if (countr == 1 && count1%2 != 0) count++;
		count1 = 0;
		countl = 1;
	}
}
if (countl == 0 && countr == 0) count += count1;
print(count);

var n = Number(readline().split());
var s = readline();
var ats = 0;

var R = -1;
var L = -1;

for(var i=0; i<n; i++)
if(s.slice(i,i+1)=='R')
{
	if(L==-1)ats+=i;
	else if((R-L+1)%2==1)ats++;
	R=i;
}
else if(s.slice(i,i+1)=='L')
{
	if(R!=-1 && (R-L+1)%2==1)ats++;
	L=i;
}

if(L > R)ats+=n-L;
if(L==-1 && R==-1)ats = n;

print(ats);

var n = Number(readline().split());
var s = readline();
var ats = 0;

var R = -1;
var L = -1;

for(var i=0; i<n; i++)
if(s.slice(i,i+1)=='R')
{
	if(L==-1)ats+=i;
	else if((R-L+1)%2==1)ats++;
	R=i;
}
else if(s.slice(i,i+1)=='L')
{
	if(R!=-1 && (R-L+1)%2==1)ats++;
	L=i;
}

if(L > R)ats+=n-L-1;
if(L==-1 && R==-1)ats = n;

print(ats);

var n = Number(readline().split());
var s = readline().split();
var ats = 0;

var R = -1;
var L = -1;

for(var i=0; i<n; i++)
if(s.slice(i,1)=='R')
{
	if(L==-1)ats+=i;
	else if((R-L+1)%2==1)ats++;
	R=i;
}
else if(s.slice(i,1)=='L')
{
	if(R!=-1 && (R-L+1)%2==1)ats++;
	L=i;
}

if(L > R)ats+=n-L-1;

print(ats);


const fs = require('fs');
const stdinBuffer = fs.readFileSync(0);
const inputString = stdinBuffer.toString();

const [count, ...data] = inputString.split('\n');

data.length = parseInt(count, 10);

function find(dataString) {
  const [n, x, a, b] = dataString.split(' ').map(x => { return parseInt(x, 10) });
  const maxLeft = Math.min(a,b) - 1, maxRight = n - Math.max(a,b);
  const max = maxLeft + maxRight;

  return Math.min(max, x) + Math.abs(b - a);
}

process.stdout.write(`${data.map(find).join('\n')}`);

let fs = require('fs');
let txt = fs.readFileSync(0, 'utf-8').split("\r\n").filter(data=>{return data.length>0});
txt.shift()
txt.forEach((data) => {
    let info = data.split(" ")
    rival(info[0] * 1, info[1] * 1, info[2] * 1, info[3] * 1);
})

function rival(n, x, a, b) {
    if(b>a){
        let i=a;
        a=b;
        b=i;
    }
    while (x > 0) {
        if (a + 1 <= n) {
            ++a;
        } else if (b - 1 > 0) {
            --b;
        } else {
            break;
        }
        --x;
    }

    console.log(Math.abs(a - b));

}

var count = Number(readline());
for(var i=0; i<count; i++){
    var args = readline().split(" ");
    var n = Number(args[0]);
    var x = Number(args[1]);
    var a = Number(args[2]);
    var b = Number(args[3]);
    print(Math.min(n-1, Math.abs(a-b)+x));
}

let data = '';
process.stdin.on('data', c => data += c);

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	let t = nl.num();
  let ans = [];
  for(let i = 0; i < t; i++){
    let [n, x, a, b] = nl.nums();
    let ab = Math.abs(a - b);
    ans.push((ab + x > n - 1)?n-1:ab + x);
  }
	console.log(ans.join('\n'));

};

process.stdin.on('end', sol);

var num = +readline();
for (var i = 0; i < num; i++) {
  var nums = readline().split(' ').map(i => parseInt(i));
  write(Math.min(Math.abs(nums[2] - nums[3]) + nums[1], nums[0] - 1))
  write("\n")
}

// Don't look here. Just some reading API
function onReadable(a,b,c){return()=>{const d=a.read();d&&(b.val=Buffer.concat([b.val,d]));let e=b.val.indexOf("\n");if(d||(e=b.val.length),-1!==e){const a=b.val.slice(0,e);return b.val=b.val.slice(e+1),c(a.toString("utf-8"))}return a.once("readable",onReadable(a,b,c))}}
function IO(a,b){const c={val:Buffer.from([])};return{async rl(){const b=c.val.indexOf("\n");if(-1!==b){const a=c.val.slice(0,b);return c.val=c.val.slice(b+1),a.toString("ascii")}return new Promise(b=>a.once("readable",onReadable(a,c,b)))},wr(a){return b.write(a)},wl(a){return b.write(a+"\n")}}}
(async()=>{const a=IO(process.stdin,process.stdout);return sol(a)})();

async function sol({ rl, wr, wl }) {
  const t = Number(await rl());

  for(let i = 0; i < t; i += 1) {
    let [n, x, a, b] = (await rl()).split(' ').map(Number);

    if (b < a) { [b, a] = [a, b]; }

    wl(Math.min(a + (n - b) + (b - a) - 1, (b - a) + x));
  }
}

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  const t = parseInt(arr.shift())

  for(let i = 0; i < t; i++) {
    const arrT = arr[i].split(' ').map(a => parseInt(a))
    const n = arrT[0]
    let x = arrT[1]
    let a = arrT[2]
    let b = arrT[3]

    if(x == 0) {
      console.log(Math.abs(a - b))
    }

    else {
      if(a > b) {
        const temp = a
        a = b
        b = temp
      }
      if((a - x) < 1){
        x = x - a + 1
        a = 1

        if(b + x >= n) b = n
        else b = b + x
        // console.log(a,b)
      }
      else {
        a = a - x
        // console.log('sf')
      }
      console.log(Math.abs(a - b))
    }
  }
})

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
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';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//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();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var n = one[0];
    var x = one[1];
    var a = one[2];
    var b = one[3];
    output[i] = Math.min(n - 1, Math.abs(a - b) + x);
  }
  myout(myconv(output, 9));
}

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  const [n, x, a, b] = d.split(' ').map(Number);
  const min = Math.min(a, b);
  const max = Math.max(a, b);
  const ans = Math.min(n - 1, max - min + x);

  console.log(ans);
  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++];
}

// thats all what you have to write to get input from stdin, using readLine.

// Main code runs in main();

function main() {
    const t = +readline();
    for (let i = 0; i < t; i++) {
        const [n, x, a, b] = readline().split(" ").map(x => parseInt(x));
        console.log(students(n, x, a, b));
    }
}

const students = (n, x, a, b) => {
    let p1 = Math.min(a, b);
    let p2 = Math.max(a, b);
    while (x) {
        if (p1 > 1) {
            --p1;
        } else if (p2 < n) {
            ++p2;
        }
        --x;
    }
    return p2 - p1;
}

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  const t = parseInt(arr.shift())

  for(let i = 0; i < t; i++) {
    const arrT = arr[i].split(' ').map(a => parseInt(a))
    const n = arrT[0]
    let x = arrT[1]
    let a = arrT[2]
    let b = arrT[3]

    if(x == 0) {
      console.log(Math.abs(a - b))
    }

    else {
      if(a > b) {
        const temp = a
        a = b
        b = temp
      }
      if(a - x < 1){
        a = 1
        x = x - (a - 1)

        if(b + x >= n) b = n
      }
      else {
        a = a - x
        // console.log('sf')
      }
      console.log(Math.abs(a - b))
    }
  }
})

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  const t = parseInt(arr.shift())

  for(let i = 0; i < t; i++) {
    const arrT = arr[i].split(' ').map(a => parseInt(a))
    const n = arrT[0]
    let x = arrT[1]
    let a = arrT[2]
    let b = arrT[3]

    if(x == 0) {
      console.log(Math.abs(a - b))
    }

    else {
      if(a > b) {
        const temp = a
        a = b
        b = temp
      }
      if(a - x < 1){
        a = 1
        x = x - (a - 1)

        if(b + x >= n) b = n
        else b = b + x
      }
      else {
        a = a - x
        // console.log('sf')
      }
      console.log(Math.abs(a - b))
    }
  }
})

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  const [n, x, a, b] = d.split(' ').map(Number);
  const min = Math.min(a, b);
  const max = Math.max(a, b);
  const ans = Math.min(99, max - min + x);

  console.log(ans);
  c++;
});

let fs = require('fs');
let txt = fs.readFileSync(0, 'utf-8').split("\r\n");
txt.forEach((data) => {
    let info = data.split(" ").filter(data => {
        return data.length > 0
    })
    rival(info[0] * 1, info[1] * 1, info[2] * 1, info[3] * 1);
})

function rival(n, x, a, b) {
    if(b>a){
        let i=a;
        a=b;
        b=i;
    }
    while (x > 0) {
        if (a + 1 <= n) {
            ++a;
        } else if (b - 1 > 0) {
            --b;
        } else {
            break;
        }
        --x;
    }

    console.log(Math.abs(a - b));

}

let fs=require('fs');
let txt=fs.readFileSync(0,'utf-8').split("\r\n");
txt.forEach((data)=>{
     rival(data.split(" ").filter(data=>{return data.length>0}).map(data=>{return data*1}));
})

function rival(arr){
     let smallest=Infinity;
     arr.forEach(data=>{
          arr.forEach(data1=>{
               if(Math.abs(data-data1)>0 && Math.abs(data-data1)<smallest){
                    smallest=Math.abs(data-data1);
               }
          })
     })
     console.log(smallest)
}

let fs = require('fs');
let txt = fs.readFileSync(0, 'utf-8').split("\r\n");
txt.shift()
txt.forEach((data) => {
    let info = data.split(" ").filter(data => {
        return data.length > 0
    })
    rival(info[0] * 1, info[1] * 1, info[2] * 1, info[3] * 1);
})

function rival(n, x, a, b) {
    if(b>a){
        let i=a;
        a=b;
        b=i;
    }
    while (x > 0) {
        if (a + 1 <= n) {
            ++a;
        } else if (b - 1 > 0) {
            --b;
        } else {
            break;
        }
        --x;
    }

    console.log(Math.abs(a - b));

}

let fs = require('fs');
let txt = fs.readFileSync(0, 'utf-8').split("\r\n");
txt.shift()
txt.forEach((data) => {
    let info = data.split(" ")
    rival(info[0] * 1, info[1] * 1, info[2] * 1, info[3] * 1);
})

function rival(n, x, a, b) {
    while (x > 0) {
        if (a + 1 <= n) {
            ++a;
        } else if (b - 1 > 0) {
            --b;
        } else {
            break;
        }
        --x;
    }

    console.log(Math.abs(a - b));

}

let fs=require('fs');
let txt=fs.readFileSync(0,'utf-8').split("\r\n");
txt.forEach((data)=>{
    let info=data.split(" ").filter(data=>{return data.length>0})
     rival(info[0]*1,info[1]*1,info[2]*1,info[3]*1);
})

function rival(n,x,a,b){
    while (x>0) {
        if(a+1<=n){
            ++a;
            --x;
        }else if(b-1>0){
            --b;
            --x;
        }else{
            break;
        }
    }

     console.log(Math.abs(a-b));

}

let fs = require('fs');
let txt = fs.readFileSync(0, 'utf-8').split("\r\n");
txt.shift()
txt.forEach((data) => {
    let info = data.split(" ")
    rival(info[0] * 1, info[1] * 1, info[2] * 1, info[3] * 1);
})

function rival(n, x, a, b) {
     if(b>a){
          let i=a;
          a=b;
          b=i;
     }
    while (x > 0) {
        if (a + 1 <= n) {
            ++a;
        } else if (b - 1 > 0) {
            --b;
        } else {
            break;
        }
        --x;
    }

    console.log(Math.abs(a - b));

}

let fs=require('fs');
let txt=fs.readFileSync(0,'utf-8').split("\r\n");
txt.forEach((data)=>{
     rival(data.split(" ").filter(data=>{return data.length>0}).map(data=>{return data*1}));
})

function rival(arr){
     let smallest=-Infinity;
     arr.forEach(data=>{
          arr.forEach(data1=>{
               if(Math.abs(data-data1)>smallest){
                    smallest=Math.abs(data-data1);
               }
          })
     })
     console.log(smallest);

     return smallest;
}

const fs = require('fs');
const stdinBuffer = fs.readFileSync(0);
const inputString = stdinBuffer.toString();

const [_, ...data] = inputString.split('\n');

function find(dataString) {
  const [n, x, a, b] = dataString.split(' ').map(x => { return parseInt(x, 10) });
  const maxLeft = Math.min(a,b) - 1, maxRight = n - Math.max(a,b);
  const max = maxLeft + maxRight;
  console.log(n, x, a, b, maxRight, maxLeft, max);

  return Math.min(max, x) + Math.abs(b - a);
}

process.stdout.write(`${data.map(find).join('\n')}`);

var count = Number(readline());
for(var i=0; i<count; i++){
    var args = readline().split(" ");
    var n = args[0];
    var x = args[1];
    var a = args[2];
    var b = args[3];
    print("n = "+n + "\nx = "+x + "\na="+a + "\nb="+b);
    print(Math.min(n-1, Math.abs(a-b)+x));
}

var count = Number(readline());
for(var i=0; i<count; i++){
    var args = readline().split(" ");
    var n = args[0];
    var x = args[1];
    var a = args[2];
    var b = args[3];
    print(Math.min(n-1, Math.abs(a-b)+x));
}

var count = Number(readline());
for(var i=0; i<count; i++){
    var args = readline().split(" ");
    var n = Number(args[0]);
    var x = Number(args[1]);
    var a = Number(args[2]);
    var b = Number(args[3]);
    print("n = "+n + "\nx = "+x + "\na="+a + "\nb="+b);
    print(Math.min(n-1, Math.abs(a-b)+x));
}

var num = +readline();
for (var i = 0; i < num - 1; i++) {
  var nums = readline().split(' ').map(i => parseInt(i));
  write(Math.min(Math.abs(nums[2] - nums[3]) + nums[1], nums[0] - 1))
}

var num = +readline();
for (var i = 0; i < num; i++) {
  var nums = readline().split(' ').map(i => parseInt(i));
  write(Math.min(Math.abs(nums[2] - nums[3]) + nums[1], nums[0] - 1))
}


'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();
var mod = 998244353n
var maxN = 10e6 + 1

function main() {
  var x = parseInt(readline())
  //
  Array(parseInt(x)).fill(1).map((t, iii) => {
    // var n = parseInt(readline())
    //   var a = new Array(n)
    //   var marked = new Array(n).fill(false)
    //   var found = new Array(n).fill(false)
    var [n, m] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    });

    var playes = {}
    var a = new Array(m)
    var position = new Array(m)
    for (let i = 0; i < m; i++) {
      a[i] = readline().split(' ').map((x, iii) => {
        return parseInt(x)
      });
      a[i].splice(0, 1)
      a[i].pos = i
    }
// console.log(a)
    a = a.sort((a, b) => a.length - b.length)
    // console.log(a)
    var min
    var minI
    var value = Math.ceil(m / 2)
    var exist = true
    var ans = new Array(m).fill(0)
    for (let i = 0; i < m; i++) {
      min = Number.MAX_SAFE_INTEGER
      for (let j = 0; j < a[i].length; j++) {
        if (playes[a[i][j]] === undefined) playes[a[i][j]] = 0
        if (playes[a[i][j]] < min) {
          min = playes[a[i][j]]
          minI = a[i][j]
        }
      }
      playes[minI]++
      ans[a[i].pos] = minI
      if (playes[minI] > value) exist = false
    }
    if (!exist) return console.log('NO')
    console.log('YES')
    console.log(ans.join(' '))
  })
}

function find(value, a) {
  var l = -1
  var r = a.length
  while (r > l + 1) {
    var m = Math.floor((r + l) / 2)
    // console.log(a[m], f, l, r)
    if (a[m] <= value) l = m
    if (a[m] > value) r = m
  }
  return r
}

//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 N = nextInt();
		var M = nextInt();
		var list = new Array(M);
		for(var j = 0; j < M; j++){
			var K = nextInt();
			var c = nextIntArray(K);
			list[j] = {
				no : j,
				c : c,
				size : K
			};
		}
		list.sort(function(a,b){
			return a.size - b.size;
		});
		var map = {};
		var output = new Array(M);
		var isOK2 = true;
		for(var j = 0; j < M; j++){
			var c = list[j].c;
			var isOK = false;
			for(var k = 0; k < c.length; k++){
				if(map[c[k]] == null){
					map[c[k]] = 0;
				}
				if(map[c[k]] < M / 2){
					map[c[k]]++;
					output[list[j].no] = c[k];
					isOK = true;
					break;
				}
			}
			if(!isOK){
				isOK2 = false;
				break;
			}
		}
		if(isOK2){
			myout("YES");
			myout(myconv(output, 8));
		}else{
			myout("NO");
		}
	}
}

'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();
var mod = 998244353n
var maxN = 10e6 + 1

function main() {
  var x = parseInt(readline())
  //
  Array(parseInt(x)).fill(1).map((t, iii) => {
    // var n = parseInt(readline())
    //   var a = new Array(n)
    //   var marked = new Array(n).fill(false)
    //   var found = new Array(n).fill(false)
    var [n, m] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    });

    var playes = {}
    var a = new Array(m)
    var position = new Array(m)
    for (let i = 0; i < m; i++) {
      a[i] = readline().split(' ').map((x, iii) => {
        return parseInt(x)
      });
      a[i].pos = i
    }

    a = a.sort((a, b) => a.length - b.length)
    // console.log(a)
    var min
    var minI
    var value = Math.ceil(m / 2)
    var exist = true
    var ans = new Array(m).fill(0)
    for (let i = 0; i < m; i++) {
      min = Number.MAX_SAFE_INTEGER
      for (let j = 0; j < a[i].length; j++) {
        if (playes[a[i][j]] === undefined) playes[a[i][j]] = 0
        if (playes[a[i][j]] < min) {
          min = playes[a[i][j]]
          minI = a[i][j]
        }
      }
      playes[minI]++
      ans[a[i].pos] = minI
      if (playes[minI] > value) exist = false
    }
    if (!exist) return console.log('NO')
    console.log('YES')
    console.log(ans.join(' '))
  })
}

function find(value, a) {
  var l = -1
  var r = a.length
  while (r > l + 1) {
    var m = Math.floor((r + l) / 2)
    // console.log(a[m], f, l, r)
    if (a[m] <= value) l = m
    if (a[m] > value) r = m
  }
  return r
}

'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();
var mod = 998244353n
var maxN = 10e6 + 1

function main() {
  var x = parseInt(readline())
  //
  Array(parseInt(x)).fill(1).map((t, iii) => {
    // var n = parseInt(readline())
    //   var a = new Array(n)
    //   var marked = new Array(n).fill(false)
    //   var found = new Array(n).fill(false)
    var [n, m] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    });

    var playes = {}
    var a = new Array(m)
    for (let i = 0; i < m; i++) {
      a[i] = readline().split(' ').map((x, iii) => {
        return parseInt(x)
      });
    }

    a = a.sort((a, b) => a.length - b.length)

    var min
    var minI
    var value = Math.ceil(m / 2)
    var exist = true
    var ans = []
    for (let i = 0; i < m; i++) {
      min = Number.MAX_SAFE_INTEGER
      for (let j = 0; j < a[i].length; j++) {
        if (playes[a[i][j]] === undefined) playes[a[i][j]] = 0
        if (playes[a[i][j]] < min) {
          min = playes[a[i][j]]
          minI = a[i][j]
        }
      }
      playes[minI]++
      ans.push(minI)
      if (playes[minI] > value) exist = false
    }
    if(!exist) return console.log('NO')
    console.log('YES')
    console.log(ans.join(' '))
  })
}

function find(value, a) {
  var l = -1
  var r = a.length
  while (r > l + 1) {
    var m = Math.floor((r + l) / 2)
    // console.log(a[m], f, l, r)
    if (a[m] <= value) l = m
    if (a[m] > value) r = m
  }
  return r
}


function solve() {
   var n = Number(read());
   var a = readArray(function(x, i) {
      return Number(x) === i + 1 ? 1 : 0;
   });
   var l = 0;
   var r = n - 1;
   while(l < n && a[l]) {
      l++;
   }
   while (r >= 0 && a[r]) {
      r--;
   }
   if (l > r) {
      write(0);
      return;
   }
   for (var i = l; i <= r; i++) {
      if (a[i]) {
         write(2);
         return;
      }
   }
   write(1);
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

function readArray(mapF) {
   return read().split(' ').map(mapF);
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', init);
   }
} else {
   init();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

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

    C();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let ans = '';
        for(let i = 0; i < n; i++){
            ans += '1 ';
        }
        console.log(ans);
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());

        if(n%2===0){
            console.log(n/2, n/2);
            continue;
        }

        let sq = Math.floor(Math.sqrt(n));
        let min = 999999999999999;
        let minPair = [];
        for(let i = 1; i <= sq; i++){
            if(n % i === 0){
                let j = n/i;
                let x = n-i;
                let y = n-j;

                if(x % i === 0){
                    if(min > Math.max(x,i)){
                        min = Math.max(x,i);
                        minPair = [i,x]
                    }
                }

                if(y % j === 0){
                    if(min > Math.max(j,y)){
                        min = Math.max(j,y);
                        minPair = [j,y]
                    }
                }
            }
        }
        console.log(minPair[0], minPair[1]);
    }
}

function C(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));
        let map = new Array(600000);

        let b = JSON.parse(JSON.stringify(a));
        b.sort((a,b) => a-b);
        for(let i = 0; i < n; i++)
            map[b[i]] = i;

        let pre = -1;
        let ans = -1;
        for(let i = 0; i < n; i++){
            if(map[a[i]] !== i){
                if(pre === -1)
                    pre = i;
                else{
                    if(pre === i-1){
                        pre = i;
                        ans = 1;
                    }else{
                        ans = 2;
                        break;
                    }
                }
            }
        }

        if(ans === -1)
            console.log(0);
        else
            console.log(ans);
    }
}

// node template.js < A-small.in > A-small.out

function main() {
    var tests = 1;
    tests = nextInt();

    for (let t = 1; t <= tests; t++) {
        let N = nextInt();
        let a = [];
        for(let i = 0; i < N; i++) {
            a.push(nextInt());
        }

        let [l, r] = cut(a);

        let result = 0;
        for(let i = l; i < r; i++) {
            if (a[i] > a[i+1]) {
                result = 1;
            }
        }
        if (result === 1) {
            a.forEach((x, i) => {
                if (l <= i && i <= r) {
                    if (x === i+1) {
                        result = 2;
                    }
                }
            });
        }

        print(result);
    }
}

function cut(a) {
    let l = 0,
        r = a.length -1,
        b = [];
    while (a[l] === l+1) a[l++] = 0;
    while (a[r] === r+1) a[r--] = 0;
    return [l, r];
}

// ------- Template ------------------
function newTensor(dimensions, value) {
    let res = [];
    let dim = dimensions[0], subdim = dimensions.slice(1);
    if (subdim.length == 0) {
        for(let i = 0; i < dim; i++) {
            res.push(value);
        }
    } else {
        for(let i = 0; i < dim; i++) {
            res.push(newTensor(subdim, value));
        }
    }
    return res;
}

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        value: function(search, rawPos) {
            var pos = rawPos > 0 ? rawPos|0 : 0;
            return this.substring(pos, pos + search.length) === search;
        }
    });
}
if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
        if (this_len === undefined || this_len > this.length) {
            this_len = this.length;
        }
        return this.substring(this_len - search.length, this_len) === search;
    };
}

var curTokens = [], curToken = 0;

function next() {
    while (curToken >= curTokens.length) {
        curTokens = readline().split(/[\s]+/);
        curToken = 0;
    }
    return curTokens[curToken++];
}

function nextInt() {
    return parseInt(next());
}

// code for nodejs
var inputBuffer = '', curLine = 0;

function readline() {
    return inputBuffer[curLine++];
}

function print(data) {
    process.stdout.write(data + '\n');
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
    inputBuffer += chunk;
});

process.stdin.on('end', function () {
    inputBuffer = inputBuffer.split(/[\s]+/);
    main();
});

// node template.js < A-small.in > A-small.out

function main() {
    var tests = 1;
    tests = nextInt();

    for (let t = 1; t <= tests; t++) {
        let N = nextInt();
        let a = [];
        for(let i = 0; i < N; i++) {
            a.push(nextInt());
        }

        let result = 0;
        for(let i = 0; i+1 < a.length; i++) {
            if (a[i] > a[i+1]) {
                result = 1;
            }
        }
        if (result === 1) {
            a.forEach((x, i) => {
                if (x === i) {
                    result = 2;
                }
            });
        }

        print(result);
    }
}

// ------- Template ------------------
function newTensor(dimensions, value) {
    let res = [];
    let dim = dimensions[0], subdim = dimensions.slice(1);
    if (subdim.length == 0) {
        for(let i = 0; i < dim; i++) {
            res.push(value);
        }
    } else {
        for(let i = 0; i < dim; i++) {
            res.push(newTensor(subdim, value));
        }
    }
    return res;
}

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        value: function(search, rawPos) {
            var pos = rawPos > 0 ? rawPos|0 : 0;
            return this.substring(pos, pos + search.length) === search;
        }
    });
}
if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
        if (this_len === undefined || this_len > this.length) {
            this_len = this.length;
        }
        return this.substring(this_len - search.length, this_len) === search;
    };
}

var curTokens = [], curToken = 0;

function next() {
    while (curToken >= curTokens.length) {
        curTokens = readline().split(/[\s]+/);
        curToken = 0;
    }
    return curTokens[curToken++];
}

function nextInt() {
    return parseInt(next());
}

// code for nodejs
var inputBuffer = '', curLine = 0;

function readline() {
    return inputBuffer[curLine++];
}

function print(data) {
    process.stdout.write(data + '\n');
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
    inputBuffer += chunk;
});

process.stdin.on('end', function () {
    inputBuffer = inputBuffer.split(/[\s]+/);
    main();
});

// node template.js < A-small.in > A-small.out

function main() {
    var tests = 1;
    tests = nextInt();

    for (let t = 1; t <= tests; t++) {
        let N = nextInt();
        let a = [];
        for(let i = 0; i < N; i++) {
            a.push(nextInt());
        }

        let result = 0;
        for(let i = 0; i+1 < a.length; i++) {
            if (a[i] > a[i+1]) {
                result = 2;
            }
        }

        print(result);
    }
}

// ------- Template ------------------
function newTensor(dimensions, value) {
    let res = [];
    let dim = dimensions[0], subdim = dimensions.slice(1);
    if (subdim.length == 0) {
        for(let i = 0; i < dim; i++) {
            res.push(value);
        }
    } else {
        for(let i = 0; i < dim; i++) {
            res.push(newTensor(subdim, value));
        }
    }
    return res;
}

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        value: function(search, rawPos) {
            var pos = rawPos > 0 ? rawPos|0 : 0;
            return this.substring(pos, pos + search.length) === search;
        }
    });
}
if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
        if (this_len === undefined || this_len > this.length) {
            this_len = this.length;
        }
        return this.substring(this_len - search.length, this_len) === search;
    };
}

var curTokens = [], curToken = 0;

function next() {
    while (curToken >= curTokens.length) {
        curTokens = readline().split(/[\s]+/);
        curToken = 0;
    }
    return curTokens[curToken++];
}

function nextInt() {
    return parseInt(next());
}

// code for nodejs
var inputBuffer = '', curLine = 0;

function readline() {
    return inputBuffer[curLine++];
}

function print(data) {
    process.stdout.write(data + '\n');
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
    inputBuffer += chunk;
});

process.stdin.on('end', function () {
    inputBuffer = inputBuffer.split(/[\s]+/);
    main();
});

// node template.js < A-small.in > A-small.out

function main() {
    var tests = 1;
    tests = nextInt();

    for (let t = 1; t <= tests; t++) {
        let N = nextInt();
        let a = [];
        for(let i = 0; i < N; i++) {
            a.push(nextInt());
        }

        let result = 0;
        for(let i = 0; i+1 < a.length; i++) {
            if (a[i] > a[i+1]) {
                result = 1;
            }
        }
        if (result === 1) {
            a.forEach((x, i) => {
                if (x === i+1) {
                    result = 2;
                }
            });
        }

        print(result);
    }
}

// ------- Template ------------------
function newTensor(dimensions, value) {
    let res = [];
    let dim = dimensions[0], subdim = dimensions.slice(1);
    if (subdim.length == 0) {
        for(let i = 0; i < dim; i++) {
            res.push(value);
        }
    } else {
        for(let i = 0; i < dim; i++) {
            res.push(newTensor(subdim, value));
        }
    }
    return res;
}

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        value: function(search, rawPos) {
            var pos = rawPos > 0 ? rawPos|0 : 0;
            return this.substring(pos, pos + search.length) === search;
        }
    });
}
if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
        if (this_len === undefined || this_len > this.length) {
            this_len = this.length;
        }
        return this.substring(this_len - search.length, this_len) === search;
    };
}

var curTokens = [], curToken = 0;

function next() {
    while (curToken >= curTokens.length) {
        curTokens = readline().split(/[\s]+/);
        curToken = 0;
    }
    return curTokens[curToken++];
}

function nextInt() {
    return parseInt(next());
}

// code for nodejs
var inputBuffer = '', curLine = 0;

function readline() {
    return inputBuffer[curLine++];
}

function print(data) {
    process.stdout.write(data + '\n');
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
    inputBuffer += chunk;
});

process.stdin.on('end', function () {
    inputBuffer = inputBuffer.split(/[\s]+/);
    main();
});

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

    C();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let ans = '';
        for(let i = 0; i < n; i++){
            ans += '1 ';
        }
        console.log(ans);
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());

        if(n%2===0){
            console.log(n/2, n/2);
            continue;
        }

        let sq = Math.floor(Math.sqrt(n));
        let min = 9999999999999;
        let minPair = [];
        for(let i = 1; i <= sq; i++){
            if(n % i === 0){
                let x = n/i;
                let b = (x-1)*i;
                if(i+b === n){
                    if(min > b){
                        min = b;
                        minPair = [i,b];
                    }
                }
            }
        }
        console.log(minPair[0], minPair[1]);
    }
}

function C(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));
        let map = new Array(600000);

        let b = JSON.parse(JSON.stringify(a));
        b.sort((a,b) => a-b);
        for(let i = 0; i < n; i++)
            map[b[i]] = i;

        let preCount = 0;
        let count = 0;
        let flag = false;
        for(let i = 0; i < n; i++){
            if(i === map[a[i]]){
                if(preCount === 1){
                    if(!flag)
                        count += 1;
                    flag = true;
                }else if(preCount !== 0){
                    count += 1;
                    preCount = 0;
                }
            }else{
                preCount += 1;
                flag = false;
            }
        }
        console.log(count);
    }
}

function solve() {
   var n = Number(read());
   var a = read().split(' ').map(function(x, i) {
      return Number(x) === i + 1 ? 1 : 0;
   });
   var d = 1;
   var ans = 0;
   var i = 0;
   var j = n - 1;
   while(i <= j) {
      while (i < n && a[i] === d) {
         i++;
      }
      while (j >= 0 && a[j] === d) {
         j--;
      }
      if (i <= j) {
         ans++;
      }
      d = 1 - d;
   }
   write(ans);
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', init);
   }
} else {
   init();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

function solve() {
   var n = Number(read());
   var a = read().split(' ').map(function(x, i) {
      return Number(x) === i + 1 ? 1 : 0;
   });
   var d = 1;
   var ans = 0;
   for (var i = 0; i < n; i++) {
      if (a[i] !== d) {
         d = 1 - d;
         ans++;
      }
   }
   write(ans);
}

function init() {
   var T;
   T = 1;
   //T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

function readArray(mapF) {
   return read().split(' ').map(mapF);
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', init);
   }
} else {
   init();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}


'use strict'

const problem = (n, x, s) => {
    let r = +!x, y = 0
    const t = s.reduce((a, b) => a + b, 0)
    for (let i = 0; i < n; i++) {
        y += s[i];
        if (y === x) {
            if (!t) return -1
            r += 1
        } else if ((x - y) * t > 0 && (x - y) % t === 0) r += 1
    }
    return r
}

let t = +readline()
while(t--) {
    const nx = readline().split(' ').map(i => +i);
    const s = readline().split('').map(i => i === '0' ? 1 : -1);
    print(problem(nx[0], nx[1], s));
}

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

let input = ''
let ptr = 0
process.stdin.on('data', (i) => {
  input += i
})

process.stdin.on('end', () => {
  input = input.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main()
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt() {
  return parseInt(input[ptr++])
}

function readString() {
  return input[ptr++]
}

function readStrings() {
  return input[ptr++].split(' ')
}

function readInts() {
  return input[ptr++].split(' ').map(a => parseInt(a))
}

function main() {
  let t = readInt()
  while(t--) {
    const [n, x] = readInts()
    const s = readString()
    let c0 = 0, c1 = 0
    let count = x === 0 ? 1 : 0
    for(let i = 0; i < n; i++) {
      if(s[i] === '0') c0++
      else c1++
    }
    let b = c0 - c1
    let r = 0
    if(b === 0) {
      let f = false
      for(let i = 0; i < n; i++) {
        if(s[i] === '0') r++
        else r--
        if(r === x){
          wr(-1)
          f = true
          break
        }
      }
      if(!f) wr(0)
    }
    else {
      r = 0
      for(let i = 0; i < n; i++) {
        if(s[i] === '0') r++
        else r--
        if((x - r) % b === 0 && (x - r) / b >= 0) {
          count++
        }
      }
      wr(count)
    }
  }
}

T=+readline()
function gcd(a,b){
    if (!b)
        return a;
    return gcd(b,a%b)
}
for (t=0;t<T;t++){
    s=readline().split(' ')
    n=+s[0]
    x=+s[1]
    s=readline()
    q=0
    for (i=0;i<=n;i++){
        if (i){
            if (s[i-1]=='1')
                --q
            else
                ++q
        }
    }
    bal=0
    ans=0
    for (i=0;i<n;i++){
        if (i){
            if (s[i-1]=='1')
                --bal
            else
                ++bal
        }
        if (q==0&&bal==x){
            ans=-1;
            break;
        }
        if ((x-bal)%q==0){
            if ((x-bal)/q>=0){
                ++ans
            }
        }
    }
    print(ans)
}

'use strict'

const problem = (n, x, s) => {
    s = s.map(i => i === '1' ? -1 : 1);
    let r = {}, p = 0;
    for (let i = 0; i < n; i++) { p += s[i]; if (r[p]) r[p]++; else r[p] = 1 }
    let max = -1, min = 1
    Object.keys(r).forEach(i => {
        if (i < min) min = i;
        if (i > max) max = i;
    })

    if (p > 0 && x < min) return +!x;
    if (p < 0 && x > max) return 0;
    if (p === 0) if (x >= min && x <= max) return -1; else return 0;

    const a = Math.ceil((x - max-1)/p);
    const b = Math.ceil((x - min-1)/p);

    let res = 0;
    for (let i = a - 1; i <= b + 1; i++) {
        res += r[x - i*p] || 0;
    }
    return res;
}
let t = +readline()
while(t--) {
    const nx = readline().split(' ').map(i => +i);
    print(problem(nx[0], nx[1], readline().split('')));
}

'use strict'

const problem = (n, x, s) => {
    s = s.map(i => i === '1' ? -1 : 1);
    let r = {}, p = 0;
    for (let i = 0; i < n; i++) { p += s[i]; if (r[p]) r[p]++; else r[p] = 1 }
    let max = -1, min = 1
    Object.keys(r).forEach(i => {
        if (i < min) min = i;
        if (i > max) max = i;
    })

    if (p > 0 && x < min) return +!x;
    if (p < 0 && x > max) return 0;
    if (p === 0) if (x >= min && x <= max) return -1; else return 0;

    const a = Math.ceil((x - max-1)/p);
    const b = Math.ceil((x - min-1)/p);

    let res = 0;
    for (let i = a; i <= b; i++) {
        res += r[x - i*p];
    }
    return res;
}
let t = +readline()
while(t--) {
    const nx = readline().split(' ').map(i => +i);
    print(problem(nx[0], nx[1], readline().split('')));
}

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main(arr)
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let i = 0
  let t = readInt(input, i++)
  while(t--) {
    let [n, x] = readInts(input, i++)
    const s = input[i++]
    const len = s.length
    let c0 = 0, c1 = 0
    for (let j = 0; j < len; j++) {
      if(s[j] == '0') c0++
      else c1++
    }

    if(c0 > c1 && x < 0) wr('0')
    else if(c0 < c1 && x > 0) wr('0')
    else if(c0 === c1 && x !== 0) wr('0')
    else if(c0 === c1 && x === 0) wr(-1)
    else if((c0 === 0 || c1 === 0) && x !== 0) wr(-1)
    else {
      // wr('j')
      let count = 0
      if(x < 0) {
        x = -x
        let t = c0
        c0 = c1
        c1 = t
      }
      let r = x % (c0 - c1)
      let qu = Math.floor(x / (c0 - c1))
      let cc1 = qu * c1
      let cc0 = qu * c0
      let k = 0
      if(cc0 - cc1 === x) count ++
      while(k < len) {
        // console.log("c", count, cc0, cc1)
        if(s[k] == '0') cc0++
        else cc1++
        if(cc0 - cc1 === x) count ++
        k++
      }
      k = len - 1
      cc1 = qu * c1
      cc0 = qu * c0
      while(k >= 0) {
        // console.log("c", count, cc0, cc1)
        if(s[k] == '0') cc0--
        else cc1--
        if(cc0 - cc1 === x) count ++
        k--
      }
      wr(count)

    }
  }
}

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

let input = ''
let ptr = 0
process.stdin.on('data', (i) => {
  input += i
})

process.stdin.on('end', () => {
  input = input.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main()
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt() {
  return parseInt(input[ptr++])
}

function readString() {
  return input[ptr++]
}

function readStrings() {
  return input[ptr++].split(' ')
}

function readInts() {
  return input[ptr++].split(' ').map(a => parseInt(a))
}

function main() {
  let t = readInt()
  while(t--) {
    const [n, x] = readInts()
    const s = readString()
    let c0 = 0, c1 = 0
    let count = x === 0 ? 1 : 0
    for(let i = 0; i < n; i++) {
      if(s[i] === '0') c0++
      else c1++
    }
    let b = c0 - c1
    let r = 0
    if(b === 0) {
      let f = false
      for(let i = 0; i < n; i++) {
        if(s[i] === '0') r++
        else r--
        if(r === x){
          wr(-1)
          f = true
          break
        }
      }
      if(!f) wr(0)
    }
    else {
      r = 0
      for(let i = 0; i < n; i++) {
        if(s[i] === '0') r++
        else r--
        if((x - r) % b === 0 && (x - r) / b > 0) {
          count++
        }
      }
      wr(count)
    }
  }
}

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main(arr)
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let i = 0
  let t = readInt(input, i++)
  while(t--) {
    let [n, x] = readInts(input, i++)
    let s = input[i++]
    const len = s.length
    let c0 = 0, c1 = 0
    for (let j = 0; j < len; j++) {
      if(s[j] == '0') c0++
      else c1++
    }

    if(c0 > c1 && x < 0) wr('0')
    else if(c0 < c1 && x > 0) wr('0')
    else if(c0 === c1 && x !== 0) wr('0')
    else if(c0 === c1 && x === 0) wr(-1)
    else if((c0 === 0 || c1 === 0) && x !== 0) wr(0)
    else {
      // wr('j')
      let count = 0
      if(x < 0) {
        x = -x
        let t = c0
        c0 = c1
        c1 = t
        let s2 = []
        for (let j = 0; j < len; j++) {
          if(s[j] == '0') s2.push('1')
          else s2.push('0')
        }
        s = s2.join('')
      }
      let r = x % (c0 - c1)
      let qu = Math.floor(x / (c0 - c1))
      let cc1 = qu * c1
      let cc0 = qu * c0
      let k = 0
      if(cc0 - cc1 === x) count ++
      while(k < len) {
        // console.log("c", count, cc0, cc1, s)
        if(s[k] == '0') cc0++
        else cc1++
        if(cc0 - cc1 === x) count ++
        k++
      }
      k = len - 1
      cc1 = qu * c1
      cc0 = qu * c0
      while(k >= 0) {
        // console.log("c", count, cc0, cc1)
        if(s[k] == '0') cc0--
        else cc1--
        if(cc0 - cc1 === x) count ++
        k--
      }
      wr(count)

    }
  }
}


function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var data = tokenizeIntegers(readline()),
		rNum = data[0], cNum = data[1], snakeNum = data[2],
		cells = rNum*cNum, snakeLen = Math.floor(cells/snakeNum),
		result = [], r = 0, c = -1, dir = +1;
	for (var i = 0; i < snakeNum; ++i) {
		var len = (i == snakeNum-1 ? cells : snakeLen),
			snake = new Array(2*len+1);
		snake[0] = len;
		cells -= len;
		for (var j = 0; j < len; ++j) {
			if (dir == +1) {
				if (c == cNum-1) {
					++r;
					dir = -1;
				} else {
					c += 1;
				}
			} else {
				if (c == 0) {
					++r;
					dir = +1;
				} else {
					c -= 1;
				}
			}
			snake[2*j+1] = r+1;
			snake[2*j+2] = c+1;
		}
		result.push(snake.join(' '));
	}
	print(result.join('\n'));
}

main();

var nextToken = new function() {
    var line = [];
    var lineIndex = 0;

    return function() {
        while (lineIndex >= line.length) {
            line = readline().split(/\s+/);
            lineIndex = 0;
        }

        return line[lineIndex++];
    }
}();

var nextInt = function() {
    return parseInt(nextToken(), 10);
};

var createMatrix = function (n, m, e) {
    var i, j;
    var a = [], b;

    for (i = 0; i < n; ++i) {
        b = [];
        for (j = 0; j < m; ++j) {
            b.push(e);
        }
        a.push(b);
    }

    return a;
}

var dx = [0, 1,  0, -1];
var dy = [1, 0, -1,  0];

var fill = function(n, m, a, x, y, e, cnt) {
   var i, dir, nx, ny, good;
   var result = [];
   for (i = 0; i < cnt; ++i) {
       a[x][y] = e;
       result.push(x + 1);
       result.push(y + 1);

       if (i + 1 < cnt) {
           good = false;
           for (dir = 0; dir < 4; ++dir) {
               nx = x + dx[dir];
               ny = y + dy[dir];

               if (0 <= nx && nx < n && 0 <= ny && ny < m && a[nx][ny] == -1) {
                   x = nx;
                   y = ny;
                   good = true;
                   break;
               }
           }

           if (!good) {
               throw "FAIL!";
           }
       }
   }
   return result;
}

var main = function () {
    var n = nextInt();
    var m = nextInt();
    var a = createMatrix(n, m, -1);

    var go = fill(n, m, createMatrix(n, m, -1), 0, 0, 0, n * m);
    var cnt = nextInt();
    var left = n * m;

    var x, y, cur, i;
    for (i = 0; i < go.length; i += 2) {
        x = go[i] - 1;
        y = go[i + 1] - 1;
        //print(x + ", " + y);
        if (a[x][y] === -1) {
            if (cnt == 1) {
                cur = fill(n, m, a, x, y, cnt, left);
            } else {
                cur = fill(n, m, a, x, y, cnt, 2);
                left -= 2;
                cnt--;
            }
            print((cur.length / 2) + " " + cur.join(" "));
        }
    }

};

main();

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var data = tokenizeIntegers(readline()),
		rNum = data[0], cNum = data[1], snakeNum = data[2],
		cells = rNum*cNum, snakeLen = Math.ceil(cells/snakeNum),
		result = [], r = 0, c = -1, dir = +1;
	for (var i = 0; i < snakeNum; ++i) {
		var len = Math.min(snakeLen, cells),
			snake = new Array(2*len+1);
		snake[0] = len;
		cells -= len;
		for (var j = 0; j < len; ++j) {
			if (dir == +1) {
				if (c == cNum-1) {
					++r;
					dir = -1;
				} else {
					c += 1;
				}
			} else {
				if (c == 0) {
					++r;
					dir = +1;
				} else {
					c -= 1;
				}
			}
			snake[2*j+1] = r+1;
			snake[2*j+2] = c+1;
		}
		result.push(snake.join(' '));
	}
	print(result.join('\n'));
}

main();


print(function(s) {
	var i, j,
		l = s.length,
		isP = [];

	for (i = 0; i < l; i++)
		isP[i] = new Int8Array(l);

	isP[0][0] = 1;

	for (i = l; i >= 0; i--)
		for (j = i; j < l; j++)
			if (s[i] === s[j])
				isP[i][j] = j - i > 1 ? isP[i + 1][j - 1] : 1;
			else
				isP[i][j] = 0;

	var sum = [1];
	for (j = 1; j < l; j++) {
		sum[j] = sum[j - 1];
		for (i = 0; i <= j; i++)
			sum[j] += isP[i][j];
	}

	var ans = 0;
	for (j = 1; j < l; j++)
		for (i = 1; i <= j; i++)
			if (isP[i][j] === 1)
				ans += sum[i - 1];

	return ans;
}(readline()));


var qq = readline().split(" ").map(function(x) { return parseInt(x); });
//var numbers = prompt("Enter data: ").split(" ").map(function(x) { return parseInt(x); });   // Chrome run

var N = qq[0];
var K = qq[1];

var uron = readline().split(" ").map(function(x) { return parseInt(x); });
var st = readline();

var p_sum = Array(N).fill(0);
p_sum[0] = uron[0];
for (var i=1; i<N; i++) p_sum[i] = p_sum[i-1] + uron[i];

function get_sum(i, j) {
	if (i <= 0)
		return p_sum[j];
	return p_sum[j] - p_sum[i-1];
}

var k = 0, glob = 0;

do {
	var bg = k;
	while (k+1<N && st[k]===st[k+1]) k++;
	var en = k;
	k++;

	var mx = 0;
	if (en-bg+1 <= K)
		mx = get_sum(bg, en);
	else {
		var ww = [];
		for (var pp=bg; pp<=en; pp++) ww.push(uron[pp]);
		ww.sort(function(a,b) {return a-b;});
		for (var pp=ww.length-1; pp>=ww.length-K; pp--) mx += ww[pp];
	}

	glob += mx;
} while (k < N);

write(glob);

(function() {
    var t = readline().split(' ');
    var n = +t[0];
    var q = +t[1];
    var u = readline().split(' ');
    var b = readline().split('');

    var bs = [];
    var bsi = -1;

    var dmg = 0;

    var lastb = '';
    for(var i = 0; i < n; i++) {
        if(lastb === b[i]) {
            bs[bsi].push(+u[i]);
        }
        else {
            bsi++;
            bs[bsi] = [+u[i]];
        }
        lastb = b[i];
    }

    for(var j = 0; j< bs.length; j++) {
        var g = bs[j];
        if(g.length <= q) {
            for(var i = 0; i < g.length; i++) {
                dmg += g[i];
            }
        }
        else {
            g.sort((a,b) => b - a);
            for(var i = 0; i < q; i++) {
                dmg += g[i];
            }
        }
    }
    print(dmg);
}());

(function() {
    var t = readline().split(' ');
    var n = +t[0];
    var q = +t[1];
    var u = readline().split(' ');
    var b = readline().split('');

    var bs = {};
    var dmg = 0;

    for(var i = 0; i < n; i++) {
        if(bs[b[i]]) {
            bs[b[i]].push(+u[i]);
        }
        else {
            bs[b[i]] = [+u[i]];
        }
    }

    for(var bi in bs) {
        var g = bs[bi];

        if(g.length <= q) {
            for(var i = 0; i < g.length; i++) {
                dmg += g[i];
            }
        }
        else {
            g = g.sort(function(a, b) {
                return b - a;
            });
            print(g);
            for(var i = 0; i < q; i++) {
                dmg += g[i];
            }
        }
    }
    print(dmg);
}());

(function() {
    var t = readline().split(' ');
    var n = +t[0];
    var q = +t[1];
    var u = readline().split(' ');
    var b = readline().split('');

    var bs = {};
    var dmg = 0;

    for(var i = 0; i < n; i++) {
        if(bs[b[i]]) {
            bs[b[i]].push(+u[i]);
        }
        else {
            bs[b[i]] = [+u[i]];
        }
    }

    for(var bi in bs) {
        var g = bs[bi];

        if(g.length <= q) {
            for(var i = 0; i < g.length; i++) {
                dmg += g[i];
            }
        }
        else {
            g = g.sort(function(a, b) {
                return b - a;
            });
            for(var i = 0; i < q; i++) {
                dmg += g[i];
            }
        }
    }
    print(dmg);
}());