Consider the following process. You have a binary string (a string where each character is either 0 or 1) $$$w$$$ of length $$$n$$$ and an integer $$$x$$$. You build a new binary string $$$s$$$ consisting of $$$n$$$ characters. The $$$i$$$-th character of $$$s$$$ is chosen as follows:  if the character $$$w_{i-x}$$$ exists and is equal to 1, then $$$s_i$$$ is 1 (formally, if $$$i > x$$$ and $$$w_{i-x} = $$$ 1, then $$$s_i = $$$ 1);  if the character $$$w_{i+x}$$$ exists and is equal to 1, then $$$s_i$$$ is 1 (formally, if $$$i + x \le n$$$ and $$$w_{i+x} = $$$ 1, then $$$s_i = $$$ 1);  if both of the aforementioned conditions are false, then $$$s_i$$$ is 0. You are given the integer $$$x$$$ and the resulting string $$$s$$$. Reconstruct the original string $$$w$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains the resulting string $$$s$$$ ($$$2 \le |s| \le 10^5$$$, each character of $$$s$$$ is either 0 or 1). The second line contains one integer $$$x$$$ ($$$1 \le x \le |s| - 1$$$). The total length of all strings $$$s$$$ in the input does not exceed $$$10^5$$$.

For each test case, print the answer on a separate line as follows:   if no string $$$w$$$ can produce the string $$$s$$$ at the end of the process, print $$$-1$$$;  otherwise, print the binary string $$$w$$$ consisting of $$$|s|$$$ characters. If there are multiple answers, print any of them.

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;

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


Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.  Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to    "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.  It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.

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


You are the gym teacher in the school.There are $$$n$$$ students in the row. And there are two rivalling students among them. The first one is in position $$$a$$$, the second in position $$$b$$$. Positions are numbered from $$$1$$$ to $$$n$$$ from left to right.Since they are rivals, you want to maximize the distance between them. If students are in positions $$$p$$$ and $$$s$$$ respectively, then distance between them is $$$|p - s|$$$. You can do the following operation at most $$$x$$$ times: choose two adjacent (neighbouring) students and swap them.Calculate the maximum distance between two rivalling students after at most $$$x$$$ swaps.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of each test case contains four integers $$$n$$$, $$$x$$$, $$$a$$$ and $$$b$$$ ($$$2 \le n \le 100$$$, $$$0 \le x \le 100$$$, $$$1 \le a, b \le n$$$, $$$a \neq b$$$) — the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.

For each test case print one integer — the maximum distance between two rivaling students which you can obtain.

NoteIn the first test case you can swap students in positions $$$3$$$ and $$$4$$$. And then the distance between the rivals is equal to $$$|4 - 2| = 2$$$.In the second test case you don't have to swap students. In the third test case you can't swap students.

// 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;
}

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

}

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

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

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


Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i, o, i} and Igor has the set of letters {i, m, o}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i, o}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i, m}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string s = s1s2...sm is called lexicographically smaller than a string t = t1t2...tm (where s ≠ t) if si < ti where i is the smallest index such that si ≠ ti. (so sj = tj for all j < i)

The first line of input contains a string s of length n (1 ≤ n ≤ 3·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially.

The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally.

NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx.

// your code goes here

a = readline()
b = readline()

a=a.split('').sort().join('')
b=b.split('').sort().reverse().join('')

n = a.length

s = []
for(var i=0;i<n;i++){
	s.push('')
}
ah=0
at = Math.floor((n+1)/2)-1
bh=0
bt=Math.floor(n/2)-1
h = 0
t = n-1
for(var i=0;i<n;i++){
	if(i&1){
		if(b[bh]>a[ah]) {
			s[h++]=b[bh++]
		} else {
			s[t--]=b[bt--]
		}
	} else {
		if(b[bh]>a[at] || a[ah]<b[bh]) {
			s[h++]=a[ah++]
		} else {
			s[t--]=a[at--]
		}
	}
	// print(s)
}
print(s.join(''))

// your code goes here

a = readline()
b = readline()

a=a.split('').sort().join('')
b=b.split('').sort().reverse().join('')

n = a.length

s = []
for(var i=0;i<n;i++){
	s.push('')
}
ai=0
bi=0
h = 0
t = n-1
for(var i=0;i<n;i++){
	if(i&1){
		if(b[bi]>a[ai]) {
			s[h++]=b[bi++]
		} else {
			s[t--]=b[bi++]
		}
	} else {
		if(b[bi]>a[ai]) {
			s[h++]=a[ai++]
		} else {
			s[t--]=a[ai++]
		}
	}
}
print(s.join(''))

// your code goes here

a = readline()
b = readline()

a=a.split('').sort().join('')
b=b.split('').sort().reverse().join('')

n = a.length

s = []
for(var i=0;i<n;i++){
	s.push('')
}
ai=0
bi=0
h = 0
t = n-1
for(var i=0;i<n;i++){
	if(i&1){
		if(b[bi]>=a[ai]) {
			s[h++]=b[bi++]
		} else {
			s[t--]=b[bi++]
		}
	} else {
		if(b[bi]>=a[ai]) {
			s[h++]=a[ai++]
		} else {
			s[t--]=a[ai++]
		}
	}
}
print(s.join(''))

// your code goes here

a = readline()
b = readline()

a=a.split('').sort().join('')
b=b.split('').sort().reverse().join('')

n = a.length

s = []
for(var i=0;i<n;i++){
	s.push('')
}
ah=0
at = Math.floor((n+1)/2)-1
bh=0
bt=Math.floor(n/2)-1
h = 0
t = n-1
for(var i=0;i<n;i++){
	if(i&1){
		if(b[bh]>=a[ah]) {
			s[h++]=b[bh++]
		} else {
			s[t--]=b[bt--]
		}
	} else {
		if(b[bh]>a[at]) {
			s[h++]=a[ah++]
		} else {
			s[t--]=a[at--]
		}
	}
}
print(s.join(''))


Aleksey has $$$n$$$ friends. He is also on a vacation right now, so he has $$$m$$$ days to play this new viral cooperative game! But since it's cooperative, Aleksey will need one teammate in each of these $$$m$$$ days.On each of these days some friends will be available for playing, and all others will not. On each day Aleksey must choose one of his available friends to offer him playing the game (and they, of course, always agree). However, if any of them happens to be chosen strictly more than $$$\left\lceil\dfrac{m}{2}\right\rceil$$$ times, then all other friends are offended. Of course, Aleksey doesn't want to offend anyone.Help him to choose teammates so that nobody is chosen strictly more than $$$\left\lceil\dfrac{m}{2}\right\rceil$$$ times.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\leq n, m\leq 100\,000$$$) standing for the number of friends and the number of days to play, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains an integer $$$k_i$$$ ($$$1\leq k_i\leq n$$$), followed by $$$k_i$$$ distinct integers $$$f_{i1}$$$, ..., $$$f_{ik_i}$$$ ($$$1\leq f_{ij}\leq n$$$), separated by spaces — indices of available friends on the day $$$i$$$. It is guaranteed that the sums of $$$n$$$ and $$$m$$$ over all test cases do not exceed $$$100\,000$$$. It's guaranteed that the sum of all $$$k_i$$$ over all days of all test cases doesn't exceed $$$200\,000$$$.

Print an answer for each test case. If there is no way to achieve the goal, print "NO". Otherwise, in the first line print "YES", and in the second line print $$$m$$$ space separated integers $$$c_1$$$, ..., $$$c_m$$$. Each $$$c_i$$$ must denote the chosen friend on day $$$i$$$ (and therefore must be one of $$$f_{ij}$$$). No value must occur more than $$$\left\lceil\dfrac{m}{2}\right\rceil$$$ times. If there is more than one possible answer, print any of them.

'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
}


Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $$$n$$$ sessions follow the identity permutation (ie. in the first game he scores $$$1$$$ point, in the second game he scores $$$2$$$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up! Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $$$[1,2,3]$$$ can yield $$$[3,1,2]$$$ but it cannot yield $$$[3,2,1]$$$ since the $$$2$$$ is in the same position. Given a permutation of $$$n$$$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $$$10^{18}$$$.An array $$$a$$$ is a subarray of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the given permutation. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ ($$$1 \leq a_{i} \leq n$$$)  — the initial permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.

NoteIn the first permutation, it is already sorted so no exchanges are needed.It can be shown that you need at least $$$2$$$ exchanges to sort the second permutation.$$$[3, 2, 4, 5, 1, 6, 7]$$$Perform special exchange on range ($$$1, 5$$$)$$$[4, 1, 2, 3, 5, 6, 7]$$$Perform special exchange on range ($$$1, 4$$$)$$$[1, 2, 3, 4, 5, 6, 7]$$$

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

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

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

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


You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$:   $$$\mathit{in'}_v < \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$;  $$$\mathit{out'}_v < \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.

Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.

NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:

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 = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, m] = lines[l++].trim().split(' ').map(Number)
        const edges = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
        l += m
        output[i] = solve(n, m, edges)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, m, edges) {
    const adj = {}
    const radj = {}
    const din = Array(n + 1).fill(0)
    const dout = Array(n + 1).fill(0)
    edges.forEach(([a, b]) => {
        // a -> b
        adj[a] = adj[a] || []
        radj[b] = radj[b] || []
        adj[a].push(b)
        radj[b].push(a)
        dout[a]++
        din[b]++
    })
    //
    const dp = Array(n + 1).fill(0)
    for (let u = 1; u <= n; u++) {
        if (dp[u] > 0) continue
        dfs(adj, u, dp, din, dout)
    }
    let ans = 0
    for (let u = 1; u <= n; u++) {
        ans = Math.max(ans, dp[u])
    }
    return ans
}
function dfs(adj, r, dp, din, dout) {
    const stack = [[r, 0]]
    while (stack.length) {
        const [u, i] = stack[stack.length - 1]
        if (dp[u] > 0) continue

        const nb = adj[u] || []
        if (!i) {
            // first visited
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (!dp[v]) { // has circle
            // if (v !== p) {
                stack.push([v, 0])
            }
        } else {
            // last visited
            stack.pop()
            dp[u] = 1
            if (dout[u] > 1) {
                ;(adj[u] || []).forEach(v => {
                    if (din[v] > 1) {
                        dp[u] = Math.max(dp[u], dp[v] + 1)
                    }
                })
            }
        }
    }
}