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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const arr = (await getLine()).split(' ').map(n => parseInt(n));
        arr.sort((a,b) => a - b);
        let mindiff = arr[arr.length - 1] - arr[0] + 2;
        for(let i = 1; i < arr.length; i++) {
            mindiff = Math.min(mindiff, arr[i] - arr[i-1]);
        }
        const printbest = function(pos) {
            rl.output.write(arr[pos + 1]+ '');
            for(let i = pos + 2; i<arr.length; i++) {
                rl.output.write(' ' + arr[i]);
            }
            for(let i = 0; i<=pos; i++)
                rl.output.write(' ' + arr[i]);
            rl.output.write('\n');
        }
        if (arr[1] - arr[0] === mindiff){
            if (arr.length === 2)
                rl.output.write(arr[0] + ' ' + arr[1]+'\n');
            else
                printbest(0);
        } else if (arr[arr.length - 1] - arr[arr.length - 2] === mindiff) {
            printbest(arr.length - 2);
        } else {
            for(let i = 1; i<arr.length; i++)
                if (arr[i] - arr[i-1] === mindiff){
                    printbest(i-1);
                    break;
                }
        }
    }
}

solve();

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

var arr = '';
process.stdin.on('data', function (chunk) {
    arr += chunk;
});
process.stdin.on('end', function () {
    arr = arr.split('\n');
    var t = +arr.shift();
    for (var i = 0; i < t; i++) {
        let n = +arr.shift();
        let array = arr.shift().split(' ').map(Number);
        solve(n, array);
    }
});
function solve(n, array) {
    var arr = array.sort((a, b) => (a - b));
    if (n <= 2) {
        console.log(arr.join(" "));
        return;
    }
    let idx = -1;
    let min = Number.MAX_SAFE_INTEGER;
    for (let i = 0; i < n - 1; i++) {
        if (arr[i + 1] - arr[i] < min) {
            idx = i;
            min = arr[i + 1] - arr[i];
        }
    }

    let ans = [];
    let p = 0;
    for (let i = idx + 1; i < n; i++) {
        ans[p++] = arr[i];
    }

    for (let i = 0; i <= idx; i++) {
        ans[p++] = arr[i];
    }

    console.log(ans.join(" "));
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    arr.sort((a, b) => a - b);
    let min = Infinity,
      s,
      e;
    for (let i = 0; i < n - 1; i++) {
      let d = arr[i + 1] - arr[i];
      if (d < min) {
        min = d;
        s = i;
        e = i + 1;
      }
    }
    let ans = [];
    ans.push(arr[s]);
    let ind = e + 1;
    for (let i = 0; i < n - 2; i++, ind++) ans.push(arr[ind % n]);
    ans.push(arr[e]);
    console.log(ans.join(" "));
  }
};
solve();

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

const INF = Number.POSITIVE_INFINITY;

function main () {
	let t = rn();
	while (t--) {
		let n = rn();
		let h = rna();

		h.sort((x, y) => x - y);

		let k = 0;
		for (let i = 1; i < n - 1; i++) {
			if (h[i + 1] - h[i] < h[k + 1] - h[k])
				k = i;
		}

		ans = [h[k], ...h.slice(k + 2, n), ...h.slice(0, k), h[k + 1]];

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

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

const INF = Number.POSITIVE_INFINITY;

function main () {
	let t = rn();
	while (t--) {
		let n = rn();
		let h = rna();

		h.sort((x, y) => x - y);

		let dif = INF, idx;
		for (let i = 0; i < n - 1; i++) {
			if (h[i + 1] - h[i] < dif) {
				dif = h[i + 1] - h[i];
				idx = i;
			}
		}

		let i = idx;
		ans = [h[i], ...h.slice(i + 2, n), ...h.slice(0, i), h[i + 1]];

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

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        var arr = lines[l++].split(' ').map(Number)
        console.log(solve(n, arr));
    }
});

function solve(n, arr) {
    arr.sort((a, b) => a - b)

    let min = Infinity
    let p
    for (var i = 1; i < arr.length; i++) {
        const diff = arr[i] - arr[i - 1]
        if (i === 1 || diff < min) {
            min = diff
            p = i
        }
    }
    return [arr[p - 1]]
        .concat(arr.slice(p + 1))
        .concat(arr.slice(0, p - 1))
        .concat([arr[p]])
        .join(' ')
}

var matr = 'haha';

function create(str) {
   var hahaIndexArr = [];
   for (var i = 0; i < str.length; i++) {
      var hasWrong = false;
      for (var j = 0; j < matr.length; j++) {
         if (str[i + j] !== matr[j]) {
            hasWrong = true;
            break;
         }
      }
      if (!hasWrong) {
         hahaIndexArr.push(i);
      }
   }
   if (hahaIndexArr.length === 0) {
      if (str.length < 8) {
         return [str, -1, str];
      }
      return [str.substr(0, 4), 0, str.substr(str.length - 4, 0)];
   }
   var preff = str.substr(0, Math.min(4, hahaIndexArr[0])) || 'ha';
   var suff = str.substr(Math.max(hahaIndexArr[hahaIndexArr.length - 1] + 4, str.length - 4)) || 'ha';
   return [preff, hahaIndexArr.length, suff];
}
function summ(a, b) {
   var createMiddle = create(a[2] + b[0]);
   if (a[1] === -1 && b[1] === -1) {
      return createMiddle;
   }
   var preff = a[1] === -1 ? createMiddle[0] : a[0];
   var suff = b[1] === -1 ? createMiddle[2] : b[2];
   var asum = a[1] === -1 ? 0 : a[1];
   var bsum = b[1] === -1 ? 0 : b[1];
   var midSum = createMiddle[1] === -1 ? 0 : createMiddle[1];
   return [preff, asum + bsum + midSum, suff];
}

function solve() {
   var n = Number(read())
   var arr = readArray(Number);
   arr.sort(sortF);
   if (n === 2) {
      write(arr.join(' '));
      return;
   }
   var closest = 1;
   for (var i = 2; i < n; i++) {
      if (arr[i] - arr[i - 1] < arr[closest] - arr[closest - 1]) {
         closest = i;
      }
   }
   var ans = [];
   for (var i = closest; i < n; i++) {
      ans.push(arr[i]);
   }
   for (var i = 0; i < closest; i++) {
      ans.push(arr[i]);
   }
   write(ans.join(' '));
}

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

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

function readArray(mapF) {
   var res = read().split(' ');
   if (mapF) {
      res = res.map(mapF);
   }
   return res;
}

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

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }
   MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\r\n');
}
init();

function write(value) {
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   if (isNode) {
      return MEMORY;
   }
   var res = [];
   var x;
   while (x = read()) {
      res.push(x);
   }
   return res;
}

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const arr = (await getLine()).split(' ').map(n => parseInt(n));
        arr.sort();
        let mindiff = arr[arr.length - 1] - arr[0] + 2;
        for(let i = 1; i < arr.length; i++) {
            mindiff = Math.min(mindiff, arr[i] - arr[i-1]);
        }
        const printbest = function(pos) {
            rl.output.write(arr[pos + 1]+ '');
            for(let i = pos + 2; i<arr.length; i++) {
                rl.output.write(' ' + arr[i]);
            }
            for(let i = 0; i<=pos; i++)
                rl.output.write(' ' + arr[i]);
            rl.output.write('\n');
        }
        if (arr[1] - arr[0] === mindiff){
            if (arr.length === 2)
                rl.output.write(arr[0] + ' ' + arr[1]+'\n');
            else
                printbest(0);
        } else if (arr[arr.length - 1] - arr[arr.length - 2] === mindiff) {
            printbest(arr.length - 2);
        } else {
            for(let i = 1; i<arr.length; i++)
                if (arr[i] - arr[i-1] === mindiff){
                    printbest(i-1);
                    break;
                }
        }
    }
}

solve();

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const arr = (await getLine()).split(' ').map(n => parseInt(n));
        arr.sort();
        let mindiff = arr[arr.length - 1] - arr[0] + 2;
        for(let i = 1; i < arr.length; i++) {
            mindiff = Math.min(mindiff, arr[i] - arr[i-1]);
        }
        const printbest = function(pos) {
            rl.output.write(arr[pos + 1]+ '');
            for(let i = pos + 2; i<arr.length; i++) {
                rl.output.write(' ' + arr[i]);
            }
            for(let i = 0; i<=pos; i++)
                rl.output.write(' ' + arr[i]);
            rl.output.write('\n');
        }
        if (arr[1] - arr[0] === mindiff){
            if (arr.length === 2)
                console.log(arr[0] + ' ' + arr[1]);
            else
                printbest(0);
        } else if (arr[arr.length - 1] - arr[arr.length - 2] === mindiff) {
            printbest(arr.length - 2);
        } else {
            for(let i = 1; i<arr.length; i++)
                if (arr[i] - arr[i-1] === mindiff){
                    printbest(i-1);
                    break;
                }
        }
    }
}

solve();

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const arr = (await getLine()).split(' ').map(n => parseInt(n));
        arr.sort();
        let mindiff = arr[arr.length - 1] - arr[0] + 2;
        for(let i = 1; i < arr.length; i++) {
            mindiff = Math.min(mindiff, arr[i] - arr[i-1]);
        }
        const printbest = function(pos) {
            rl.output.write(arr[pos + 1]+ '');
            for(let i = pos + 2; i<arr.length; i++) {
                rl.output.write(' ' + arr[i]);
            }
            for(let i = 0; i<=pos; i++)
                rl.output.write(' ' + arr[i]);
            rl.output.write('\n');
        }
        if (arr[1] - arr[0] === mindiff){
            printbest(0);
        } else if (arr[arr.length - 1] - arr[arr.length - 2] === mindiff) {
            printbest(arr.length - 2);
        } else {
            for(let i = 1; i<arr.length; i++)
                if (arr[i] - arr[i-1] === mindiff){
                    printbest(i-1);
                    break;
                }
        }
    }
}

solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    arr.sort((a, b) => a - b);
    let obj = {},
      flag = true;
    for (let i = 0; i < n - 1; i++) {
      if (arr[i] === arr[i + 1]) {
        flag = false;
        obj[i] = i;
        obj[i + 1] = i + 1;
        break;
      }
    }
    if (flag) {
      obj[0] = 0;
      obj[1] = 1;
    }
    let [s, e] = Object.keys(obj);
    let ans = [];
    ans.push(arr[obj[s]]);
    let ind = obj[e] + 1;
    for (let i = 0; i < n - 2; i++, ind++) ans.push(arr[ind % n]);
    ans.push(arr[obj[e]]);
    console.log(ans.join(" "));
  }
};
solve();

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        var arr = lines[l++].split(' ').map(Number)
        console.log(solve(n, arr));
    }
});

function solve(n, arr) {
    arr.sort((a, b) => a - b)

    let min = Infinity
    let p
    for (var i = 1; i < arr.length; i++) {
        const diff = arr[i] - arr[i - 1]
        if (i === 1 || diff < min) {
            min = diff
            p = i
        }
    }
    return [arr[p - 1]]
        .concat(arr.slice(p + 1))
        .concat(arr.slice(0, p - 1))
        .concat([arr[p]])
}


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 = Number(readLine())
    for (let _i = 0; _i < t; _i++) {
        const n = Number(readLine())
        const as = readLine().split(/\s/).map(Number)
        let previous = Array(as[0] + 1).fill('a')
        console.log(previous.join(''))
        for (let i = 0; i < n; i++) {
          let nextCharCode = previous[as[i]].charCodeAt(0) + 1
          if (nextCharCode > 122) {
            nextCharCode = 97
          }
          previous = [...previous.slice(0, as[i]), ...Array(i === n - 1 ? 1 : Math.max(0, as[i + 1] - as[i] + 1)).fill(String.fromCharCode(nextCharCode))]
          console.log(previous.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 len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    let str = "a".repeat(50).split("");

    console.log(str.join(""));
    for (let i = 0; i < len; i++) {
      for (let j = arr[i]; j < 50; j++) {
        if (str[j] === "a") str[j] = "b";
        else str[j] = "a";
      }
      console.log(str.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 len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    let charCode = 97;

    if (arr[0] === 0) {
      console.log(`${String.fromCharCode(charCode)}`.repeat(1));
      charCode = (charCode + 1) % 123;
    } else {
      console.log(`${String.fromCharCode(charCode)}`.repeat(arr[0]));
    }
    for (let i = 0; i < len - 1; i++) {
      let max = Math.max(arr[i], arr[i + 1]);
      max = max === 0 ? 1 : max;

      if (arr[i] === 0 && i > 0) {
        charCode = (charCode + 1) % 123;
        console.log(`${String.fromCharCode(charCode)}`.repeat(max));
      } else {
        console.log(`${String.fromCharCode(charCode)}`.repeat(max));
      }
    }
    if (arr[len - 1] === 0) {
      charCode = (charCode + 1) % 123;
      console.log(`${String.fromCharCode(charCode)}`.repeat(1));
    } else {
      console.log(`${String.fromCharCode(charCode)}`.repeat(arr[len - 1]));
    }
  }
}

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 len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    let charCode = 97;

    if (arr[0] === 0) {
      console.log(`${String.fromCharCode(charCode)}`.repeat(1));
      charCode++;
      charCode = charCode > 123 ? 97 : charCode;
    } else {
      console.log(`${String.fromCharCode(charCode)}`.repeat(arr[0]));
    }
    for (let i = 0; i < len - 1; i++) {
      let max = Math.max(arr[i], arr[i + 1]);
      max = max === 0 ? 1 : max;

      if (arr[i] === 0 && i > 0) {
        charCode++;
        charCode = charCode > 123 ? 97 : charCode;
        console.log(`${String.fromCharCode(charCode)}`.repeat(max));
      } else {
        console.log(`${String.fromCharCode(charCode)}`.repeat(max));
      }
    }
    if (arr[len - 1] === 0) {
      charCode++;
      charCode = charCode > 123 ? 97 : charCode;
      console.log(`${String.fromCharCode(charCode)}`.repeat(1));
    } else {
      console.log(`${String.fromCharCode(charCode)}`.repeat(arr[len - 1]));
    }
  }
}

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 = Number(readLine())
    for (let _i = 0; _i < t; _i++) {
        const n = Number(readLine())
        const as = readLine().split(/\s/).map(Number)
        let previous = Array(as[0] + 1).fill('a')
        console.log(previous.join(''))
        for (let i = 0; i < n; i++) {
          let nextCharCode = previous[as[i]].charCodeAt(0) + 1
          if (nextCharCode > 122) {
            nextCharCode = 97
          }
          previous = [...previous.slice(0, as[i]), ...Array(i === n - 1 ? 0 : Math.max(0, as[i + 1] - as[i] + 1)).fill(String.fromCharCode(nextCharCode))]
          console.log(previous.join(''))
        }
    }
}


//var input = readline()
var t = Number(readline())

var str = readline()
var s = str.split('').sort().join('')
print(s)

readline();
var word = readline().split('').sort().join('');
print(word);

    var n = parseInt(readline());
    var s = readline();
    print(s.split('').sort().join(''));


'use strict'

const eol = require('os').EOL

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split(eol).slice(1, -1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    switch (s) {
      case 'rat': s = 0; break
      case 'woman': s = 1; break
      case 'child': s = 1; break
      case 'man': s = 2; break
      case 'captain': s = 3; break
      default: s = 0
    }
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

  console.log(r.join('\n'))
})

'use strict'

const eol = require('os').EOL

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split(eol).slice(1, -1).forEach(line => {
    let [n, s] = line.split(' ')
    switch (s) {
      case 'rat': s = 0; break
      case 'woman': s = 1; break
      case 'child': s = 1; break
      case 'man': s = 2; break
      case 'captain': s = 3; break
    }
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

  console.log(r.join('\n'))
})

'use strict'

const eol = require('os').EOL

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split(eol).slice(1, -1).forEach(line => {
    let [n, s] = line.split(' ')
    switch (s) {
      case 'rat': s = 0; break
      case 'woman': s = 1; break
      case 'child': s = 1; break
      case 'man': s = 2; break
      case 'captain': s = 3; break
      default: s = 0
    }
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

  console.log(r.join('\n'))
})

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    if (s == 'rat') s = 0
    else if (s == 'woman') s = 1
    else if (s == 'child') s = 1
    else if (s == 'man') s = 2
    else s = 3
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

  console.log(r.join('\n'))
})

print(function(n) {

	var i, j,
		a = [],
		ans = [],
		r = {
			rat: 0,
			woman: 1,
			child: 1,
			man: 2,
			captain: 3
		};

	for (i = 0; i < n; i++) {
		a.push(readline().split(' '));
		a[i][1] = r[a[i][1]];
	}

	for (i = 0; i <= 3; i++)
		for (j = 0; j < n; j++)
			if (a[j][1] === i) ans.push(a[j][0]);

	return ans.join('\n');

}(+readline()));

var n = parseInt(readline())
var t = []
for(var i = 0; i < n; i++){
    var s = readline();
    t.push(s);
}
t = t.map(function(x){
   return x.split(' ');
});
var G = [/rat/, /woman|child/, /^man/, /captain/];
G.forEach(function(reg){
    t.filter(function(x){
        return reg.test(x[1]);
    }).forEach(function(x){
        print(x[0]);
    });
});

;(function () {

    print(function (n) {
        var s = [];
        while (n--) s.push(readline().split(' '));
        n = s.length;

        var r = [];
        for (var i = 0; i < n; i++) if (s[i][1] === 'rat') r.push(s[i][0]);
        for (var i = 0; i < n; i++) if (s[i][1] === 'child' || s[i][1] === 'woman') r.push(s[i][0]);
        for (var i = 0; i < n; i++) if (s[i][1] === 'man') r.push(s[i][0]);
        for (var i = 0; i < n; i++) if (s[i][1] === 'captain') r.push(s[i][0]);

        return r.join('\n');
    }(+readline()));

}.call(this));

'use strict'

let n = +readline()
let ps = [[], [], [], []]

for (let i = 0; i < n; i++) {
  let p = readline().split(' ')
  let n = p[0]
  let s = p[1]
  switch (s) {
    case 'rat': s = 0; break
    case 'woman': s = 1; break
    case 'child': s = 1; break
    case 'man': s = 2; break
    case 'captain': s = 3; break
  }
  ps[s].push(n)
}

let r = []

for (let i = 0; i < 4; i++) {
  for (let j = 0; j < ps[i].length; j++) {
    r.push((ps[i][j]))
  }
}

print(r.join('\n'))

'use strict'

const eol = require('os').EOL

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split(eol).slice(1).filter(Boolean).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    switch (s) {
      case 'rat': s = 0; break
      case 'woman': s = 1; break
      case 'child': s = 1; break
      case 'man': s = 2; break
      case 'captain': s = 3; break
      default: s = 0
    }
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

  console.log(r.join('\n'))
})

var n = parseInt(readline());

var data = [[], [], [], []];
var res = [];

for (var i = 0; i < n; i++) {
	var inp = readline().split(' ');
	switch(inp[1]) {
		case 'rat':
			data[0].push(inp[0]);
			break;
		case 'woman':
		case 'child':
			data[1].push(inp[0]);
			break;
		case 'man':
			data[2].push(inp[0]);
			break;
		case 'captain':
			data[3].push(inp[0]);
			break;
	}
}

data.forEach(function(arr){
	res = res.concat(arr);
});

res.forEach(function(name) {
	print(name);
});

'use strict'

const eol = require('os').EOL

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split(eol).slice(1).filter(Boolean).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    switch (s) {
      case 'rat': s = 0; break
      case 'woman': s = 1; break
      case 'child': s = 1; break
      case 'man': s = 2; break
      default: s = 3
    }
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

  console.log(r.join('\n'))
})

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    if (s == 'rat') s = 0
    else s = 1
    ps[s].push(line)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

  console.log(r.join('\n'))
})

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    if (s == 'rat') s = 0
    else if (s == 'woman') s = 1
    else s = 2
    ps[s].push(line)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

  console.log(r.join('\n'))
})

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    if (s == 'rat') s = 0
    else if (s == 'woman') s = 1
    else if (s == 'child') s = 2
    else s = 3
    ps[s].push(line)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

  console.log(r.join('\n'))
})

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = 0
    s = (s + 1) % 4
    ps[s % 4].push(line)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

  console.log(r.join('\n'))
})

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach((line, s) => {
    ps[s % 4].push(line)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

  console.log(r.join('\n'))
})

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    if (s == 'rat') s = 0
    else if (s == 'woman') s = 1
    else if (s == 'child') s = 1
    else if (s == 'man') s = 2
    else s = 3
    ps[s].push(line)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

  console.log(r.join('\n'))
})

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  input = input.split('\r\n').slice(1)
  console.log(input.join('\n'))
})

'use strict'

const eol = require('os').EOL

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split(eol).slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    switch (s) {
      case 'rat': s = 0; break
      case 'woman': s = 1; break
      case 'child': s = 1; break
      case 'man': s = 2; break
      case 'captain': s = 3; break
      default: s = 0
    }
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

  console.log(r.join('\n'))
})

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  console.log(input)
})

;(function () {

    print(function (n) {
        var s = [];
        while (n--) s.push(readline().split(' '));
        return s.sort(function (a, b) {
            a = typeToNumber(a[1]);
            b = typeToNumber(b[1]);
            return b - a;
        }).map(function (e) {
            return e[0];
        }).join('\n');
    }(+readline()));

    function typeToNumber (type) {
        switch (type) {
            case 'rat': return 100; break;
            case 'child':
            case 'woman': return 50; break;
            case 'man': return 35; break;
            case 'captain': return 0; break;
        }
    }

}.call(this));


'use strict';

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

  return obj;
}

function solve(n, a) {
  let t = -1;
  for (let i = 0; i < n; i++) {
    if (a[i] >= 0) {
      t = i;
      break;
    }
  }
  if (t === -1) return 0;
  const dp = new Array(n).fill(0);
  const heap = new Heap((a, b) => a - b);
  let sum = 0;
  for (let i = t; i < n; i++) {
    var _dp;
    if (a[i] < 0) heap.push(a[i]);
    sum += a[i];
    dp[i] = ((_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;
    while (sum < 0) {
      sum -= heap.pop();
      dp[i]--;
    }
  }
  let res = 0;
  for (let i = 0; i < n; i++) {
    res = Math.max(res, dp[i]);
  }
  return res;
}
class Heap {
  constructor(_comparator, arr) {
    _defineProperty(this, "_heap", []);
    this._comparator = _comparator;
    if (arr) {
      this._heap = [...arr];
      for (let i = arr.length >> 1; i; i--) this.down(i);
    }
  }
  swap(i, j) {
    [this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
  }
  _has(i) {
    return Object.prototype.hasOwnProperty.call(this._heap, i);
  }
  comparator(i, j) {
    return this._comparator(this._heap[i], this._heap[j]) < 0;
  }
  parent(i) {
    return i - 1 >> 1;
  }
  children(i) {
    return [2 * i + 1, 2 * i + 2];
  }
  up(i) {
    let parent = this.parent(i);
    while (i > 0 && this.comparator(i, parent)) {
      this.swap(i, parent);
      [i, parent] = [parent, parent - 1 >> 1];
    }
  }
  down(i) {
    let [left, right] = this.children(i);
    while (left < this._heap.length) {
      if (!this._has(right)) right = left;
      if (this.comparator(right, left)) [left, right] = [right, left];
      if (this.comparator(i, left)) break;
      this.swap(i, left);
      i = left;
      [left, right] = [2 * i + 1, 2 * i + 2];
    }
  }
  push(node) {
    this._heap.push(node);
    this.up(this._heap.length - 1);
  }
  pop() {
    if (this.size() === 0) return null;
    let res = this._heap[0];
    this.swap(0, this._heap.length - 1);
    this._heap.pop();
    this.down(0);
    return res;
  }
  remove(i) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this.swap(i, this._heap.length - 1);
    this._heap.pop();
    this.down(i);
    this.up(i);
    return res;
  }
  modify(i, val) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this._heap[i] = val;
    this.down(i);
    this.up(i);
    return res;
  }
  top() {
    if (this.size() === 0) return null;
    return this._heap[0];
  }
  size() {
    return this._heap.length;
  }
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

// PriorityQueue implementated using array based binary heap
// PriorityQueue methods
//  push(...values)
// 	peek()
//  pop()
//  size()
//  replace(value)

class PriorityQueue {

	constructor(comparator = (a, b) => a > b) {
		this.top = 0;
		this._heap = [];
		this._comparator = comparator;
	}
	size() {
		return this._heap.length;
	}
	isEmpty() {
		return this.size() == 0;
	}
	peek() {
		return this._heap[this.top];
	}
	push(...values) {
		values.forEach(value => {
				this._heap.push(value);
				this._siftUp();
				});
		return this.size();
	}
	pop() {
		const poppedValue = this.peek();
		const bottom = this.size() - 1;
		if (bottom > this.top) {
			this._swap(this.top, bottom);
		}
		this._heap.pop();
		this._siftDown();
		return poppedValue;
	}
	replace(value) {
		const replacedValue = this.peek();
		this._heap[this.top] = value;
		this._siftDown();
		return replacedValue;
	}
	_greater(i, j) {
		return this._comparator(this._heap[i], this._heap[j]);
	}
	_swap(i, j) {
		[this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
	}
	_siftUp() {
		const parent = i => ((i + 1) >>> 1) - 1;
		let node = this.size() - 1;
		while (node > this.top && this._greater(node, parent(node))) {
			this._swap(node, parent(node));
			node = parent(node);
		}
	}
	_siftDown() {
		const left = i => (i << 1) + 1;
		const right = i => (i + 1) << 1;
		let node = this.top;
		while (
				(left(node) < this.size() && this._greater(left(node), node)) ||
				(right(node) < this.size() && this._greater(right(node), node))
			  ) {
			let maxChild = (right(node) < this.size() && this._greater(right(node), left(node))) ? right(node) : left(node);
			this._swap(node, maxChild);
			node = maxChild;
		}
	}
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	const n = rn();
	const a = rna();

	let health = 0, used = 0;
	const q = new PriorityQueue((a, b) => a > b);
	for (let i = 0; i < n; i++) {
		if (a[i] >= 0) {
			health += a[i];
			used++;
		} else {
			a[i] = -a[i];
			if (health - a[i] >= 0) {
				health -= a[i];
				q.push(a[i]);
				used++;
			} else {
				if (a[i] < q.peek()) {
					health += q.pop() - a[i];
					q.push(a[i]);
				}
			}
		}
	}

	console.log(used);
}

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 05/28/21 night

const solve = (n, a) => {
    let pq = new MinPriorityQueue({ priority: x => x });
    let res = sum = 0;
    for (const e of a) {
        sum += e;
        res++;
        if (e < 0) {
            pq.enqueue(e);
            while (sum < 0) {
                sum -= pq.dequeue().element;
                res--;
            }
        }
    }
    pr(res);
};

class HeapNode {
    constructor(key, value) {
        this._key = key;
        this._value = value;
    }

    getKey() {
        return this._key;
    }

    getValue() {
        return this._value;
    }
}

const isNumber = (n) => typeof n === 'number';
const isNoneEmptyString = (s) => typeof s === 'string' && s.length;
const isNoneNullObject = (o) => typeof o === 'object' && o !== null;
const isNoneEmptyArray = (a) => Array.isArray(a) && a.length > 0;

class Heap {
    constructor(nodes) {
        this._nodes = Array.isArray(nodes) ? nodes : [];
        this._leaf = null;
    }

    _getLeftChildIndex(parentIndex) {
        return (parentIndex * 2) + 1;
    }

    _getRightChildIndex(parentIndex) {
        return (parentIndex * 2) + 2;
    }

    _getParentIndex(childIndex) {
        return Math.floor((childIndex - 1) / 2);
    }

    _getLastIndex() {
        return this._nodes.length - 1;
    }

    _swap(i, j) {
        const temp = this._nodes[i];
        this._nodes[i] = this._nodes[j];
        this._nodes[j] = temp;
    }

    _compareChildrenOf(parentIndex) {
        const leftChildIndex = this._getLeftChildIndex(parentIndex);
        const rightChildIndex = this._getRightChildIndex(parentIndex);
        const size = this.size();
        if (leftChildIndex >= size && rightChildIndex >= size) return -1;
        if (leftChildIndex >= size) return rightChildIndex;
        if (rightChildIndex >= size) return leftChildIndex;
        return this._compareChildren(leftChildIndex, rightChildIndex);
    }

    _heapifyUp() {
        let childIndex = this._getLastIndex();
        let parentIndex = this._getParentIndex(childIndex);
        while (this._shouldSwap(childIndex, parentIndex)) {
            this._swap(childIndex, parentIndex);
            childIndex = parentIndex;
            parentIndex = this._getParentIndex(childIndex);
        }
    }

    _heapifyDown() {
        let parentIndex = 0;
        let childIndex = this._compareChildrenOf(parentIndex);
        while (this._shouldSwap(childIndex, parentIndex)) {
            this._swap(childIndex, parentIndex);
            parentIndex = childIndex;
            childIndex = this._compareChildrenOf(parentIndex);
        }
    }

    _heapifyDownUntil(index) {
        let parentIndex = 0;
        let leftChildIndex = 1;
        let rightChildIndex = 2;
        let childIndex;
        while (leftChildIndex < index) {
            childIndex = this._compareChildrenBefore(
                index,
                leftChildIndex,
                rightChildIndex
            );
            if (this._shouldSwap(childIndex, parentIndex)) {
                this._swap(childIndex, parentIndex);
            }
            parentIndex = childIndex;
            leftChildIndex = this._getLeftChildIndex(parentIndex);
            rightChildIndex = this._getRightChildIndex(parentIndex);
        }
    }

    _clone(HeapType) {
        return new HeapType(this._nodes.slice());
    }

    sort() {
        for (let i = this._getLastIndex(); i > 0; i -= 1) {
            this._swap(0, i);
            this._heapifyDownUntil(i);
        }
        return this._nodes;
    }

    insert(key, value) {
        const newNode = new HeapNode(key, value);
        this._nodes.push(newNode);
        this._heapifyUp();
        return newNode;
    }

    root() {
        if (this.isEmpty()) return null;
        return this._nodes[0];
    }

    leaf() {
        return this._leaf;
    }

    extractRoot() {
        if (this.isEmpty()) return null;
        const root = this.root();
        this._nodes[0] = this._nodes[this._getLastIndex()];
        this._nodes.pop();
        this._heapifyDown();
        if (root === this._leaf) {
            if (this.isEmpty()) {
                this._leaf = null;
            } else {
                this._leaf = this.root();
            }
        }
        return root;
    }

    size() {
        return this._nodes.length;
    }

    isEmpty() {
        return this.size() === 0;
    }

    clear() {
        this._nodes = [];
        this._leaf = null;
    }

    static _heapify(items, HeapType) {
        if (!isNoneEmptyArray(items)) return null;
        const heap = new HeapType();
        items.forEach((item) => {
            if (isNumber(item) || isNoneEmptyString(item)) {
                heap.insert(item);
            } else if (isNoneNullObject(item) &&
                (isNumber(item.key) || isNoneEmptyString(item.key))) {
                heap.insert(item.key, item.value);
            }
        });
        return heap;
    }
}

class MinHeap extends Heap {
    _getMinChildIndex(leftChildIndex, rightChildIndex) {
        const leftChild = this._nodes[leftChildIndex];
        const rightChild = this._nodes[rightChildIndex];
        if (leftChild.getKey() < rightChild.getKey()) {
            return leftChildIndex;
        }
        return rightChildIndex;
    }

    _getMinChildIndexBefore(index, leftChildIndex, rightChildIndex) {
        const leftChild = this._nodes[leftChildIndex];
        const rightChild = this._nodes[rightChildIndex];
        if (rightChild.getKey() < leftChild.getKey() && rightChildIndex < index) {
            return rightChildIndex;
        }
        return leftChildIndex;
    }

    _shouldSwap(childIndex, parentIndex) {
        if (childIndex < 0 || childIndex >= this.size()) return false;
        if (parentIndex < 0 || parentIndex >= this.size()) return false;
        const child = this._nodes[childIndex];
        const parent = this._nodes[parentIndex];
        return child.getKey() < parent.getKey();
    }

    _compareChildren(leftChildIndex, rightChildIndex) {
        return this._getMinChildIndex(leftChildIndex, rightChildIndex);
    }

    _compareChildrenBefore(index, leftChildIndex, rightChildIndex) {
        return this._getMinChildIndexBefore(index, leftChildIndex, rightChildIndex);
    }

    insert(key, value) {
        const newNode = super.insert(key, value);
        if (this._leaf === null || key > this._leaf.getKey()) {
            this._leaf = newNode;
        }
        return newNode;
    }

    clone() {
        return super._clone(MinHeap);
    }

    static heapify(items) {
        return super._heapify(items, MinHeap);
    }
}

class PriorityQueue {
    constructor(options = {}) {
        const {
            priority
        } = options;
        if (priority !== undefined && typeof priority !== 'function') {
            throw new Error('invalid priority callback');
        }
        this._getPriority = typeof priority === 'function' ? priority : null;
    }

    size() {
        return this._heap.size();
    }

    isEmpty() {
        return this._heap.isEmpty();
    }

    front() {
        if (this.isEmpty()) return null;
        const first = this._heap.root();
        return {
            priority: first.getKey(),
            element: first.getValue()
        };
    }

    back() {
        if (this.isEmpty()) return null;
        const last = this._heap.leaf();
        return {
            priority: last.getKey(),
            element: last.getValue()
        };
    }

    enqueue(element, p) {
        if (p && Number.isNaN(+p)) {
            throw new Error('invalid priority number');
        }
        if (Number.isNaN(+p) && this._getPriority === null) {
            throw new Error('missing priority number or constructor callback');
        }
        const priority = !Number.isNaN(+p) ? p : this._getPriority(element);
        this._heap.insert(priority, element);
    }

    dequeue() {
        if (this.isEmpty()) return null;
        const first = this._heap.extractRoot();
        return {
            priority: first.getKey(),
            element: first.getValue()
        };
    }

    toArray() {
        return this._heap
            .clone()
            .sort()
            .map((n) => ({
                priority: n.getKey(),
                element: n.getValue()
            }))
            .reverse();
    }

    clear() {
        this._heap.clear();
    }
}

class MinPriorityQueue extends PriorityQueue {
    constructor(options) {
        super(options);
        this._heap = new MinHeap();
    }
}

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()


function readInts() {
    return readline().split(' ').map(function (v) { return parseInt(v); });
}
function solve(n, m, a) {
    var _a, _b;
    var _c = [0, 0, 0, 0], on = _c[0], off = _c[1], xon = _c[2], xoff = _c[3];
    var max = m;
    var i = n - 1;
    while (i >= -1) {
        var ai = i >= 0 ? a[i] : 0;
        var l = max - ai;
        _a = [l + xoff, xon], xon = _a[0], xoff = _a[1];
        if (l > 1) {
            var _d = [l - 1 + on, l - 1 + off], nxon = _d[0], nxoff = _d[1];
            if (nxon > xon)
                xon = nxon;
            if (nxoff > xoff)
                xoff = nxoff;
        }
        _b = [l + off, on], on = _b[0], off = _b[1];
        max = ai;
        // console.log({i,max,l,on,off,xon,xoff});
        i--;
    }
    return xon > on ? xon : on;
}
// function show(n: number, m: number, a: number[]) {
//     console.log(n, m, a, '-->', solve(n, m, a));
// }
// show(3, 10, [4, 6, 7]);
// show(2, 12, [1, 10]);
// show(2, 7, [3, 4]);
var _a = readInts(), n = _a[0], m = _a[1];
var a = readInts();
print(solve(n, m, a));

  var tmp = readline().split(' ').map(x => parseInt(x));
  var n = tmp[0];
  var m = tmp[1];

  var a = [0].concat(readline().split(' ').map(x => parseInt(x)), m);
  n += 2;
  var s = [0];
  for(var i = 1; i < n; i += 1) {
    if(i % 2 === 1) {
      s[i] = s[i - 1] + a[i] - a[i - 1];
    } else {
      s[i] = s[i - 1];
    }
  }
  var sr = [a[1]];
  for(var i = 1; i < n; i += 1) {
    if(i % 2 === 0) {
      sr[i] = sr[i - 1] + a[i] - a[i - 1];
    } else {
      sr[i] = sr[i - 1];
    }
  }
  var mx = -1;
  mx = Math.max(mx, s[n - 1]);
  for(var i = 0; i < n; i += 1) {
    if(i % 2 === 0) {
      if(i !== 0) {
        if(a[i - 1] !== a[i] - 1) {
          var res = s[i - 1];
          res += a[i] - a[i - 1] - 1;
          res += sr[n - 1] - sr[i];
          mx = Math.max(mx, res);
          // console.log(a[i - 1] + 1, res);
        }
      }
    } else {
      if(a[i - 1] + 1 !== a[i]) {
        var res = s[i - 1];
        res += a[i] - a[i - 1] - 1;
        res += sr[n - 1] - sr[i];
        mx = Math.max(mx, res);
        // console.log(a[i - 1] + 1, res);
      }
    }
  }
  // console.log(a);
  // console.log(s);
  // console.log(sr);
  print(mx);

'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 [N,M]=readLine().trim().split(' ').map(x=>{return +(x);});
    let A=readLine().trim().split(' ').map(x=>{return +(x);});
    A.unshift(0);
    A.push(M);
    let zer=[],zerc=0,on=[],onc=0;
    //console.log(A);
    for(let i=0;i<=N;i++)
    {
        if(i&1)
        {
            on.push(A[i+1]-A[i]);
            ++onc;
            if(i!=1)
            {
                on[onc-1]+=on[onc-2];
            }
        }
        else
        {
            zer.push(A[i+1]-A[i]);
            ++zerc;
            if(i!==0)
            {
                zer[zerc-1]+=zer[zerc-2];
            }
        }
    }
    zer.unshift(0);
    on.unshift(0);
    ++zerc;
    ++onc;
    //console.log(zer);
    //console.log(on);
    let m=zer[zerc-1];
    for(let i=0;i<=N;++i)
    {
        if(A[i+1]-A[i]>1)
        {
            let t=zer[Math.floor((i+1)/2)]+A[i+1]-A[i]-1-on[Math.floor((i+1)/2)]+on[onc-1];
            //console.log(t);
            if(t>m)
            {
                m=t;
            }
            t=zer[Math.floor((i+1)/2)]+1-on[Math.floor((i+1)/2)]+on[onc-1];
            //console.log(t);
            if(t>m)
            {
                m=t;
            }
        }
    }
    console.log(m);
}


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 j = 0; j < t; j++) {
    const [a, b] = arr[j].split(' ').map(a => parseInt(a))

    if((a + b) % 3 == 0 && a >= b && a <= 2 * b) {
      console.log('YES')
    }
    else if((a + b) % 3 == 0 && a <= b && b <= 2 * a) {
      console.log('YES')
    }
    else {
      console.log('NO')
    }
  }
})

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

function max(...x) {
  return Math.max(...x)
}

function min(...x) {
  return Math.min(...x)
}

var t = parseInt(readline(), 10);

while(t--) {
    var inp = readline().split(' ');
    var a = parseInt(inp[0], 10), b = parseInt(inp[1], 10), div = 0, valid = true;

    if((a+b)%3 !== 0) valid = false;
    else if((a+b)/3 > a || (a+b)/3 > b) valid = false;

    print(valid ? 'YES' : 'NO');
}

var t = parseInt(readline(), 10);

while(t--) {
    var inp = readline().split(' ');
    var a = parseInt(inp[0], 10), b = parseInt(inp[1], 10), a_cpy = a, b_cpy = b;

    if(a === b || (a%2 === 0 && b%2 === 0) || (a%2 !== 0 && b%2 !== 0)) {
        print('NO');

    } else {
        if(a%2 === 0) {
            a_cpy -= 2;
            b_cpy -= 1;

        } else {
            a_cpy -= 1;
            b_cpy -= 2;

        }

        if(a>b) {
            if(a_cpy%b_cpy === 0) print('YES');
            else print('NO');

        } else if(b>=a && (a_cpy !== 0 && b_cpy !== 0)) {
            if(b_cpy%a_cpy === 0) print('YES');
            else print('NO');

        } else if(a_cpy === 0 && b_cpy === 0) {
            print('YES');

        }
    }
}

var t = parseInt(readline(), 10);

while(t--) {
    var inp = readline().split(' ');
    var a = parseInt(inp[0], 10), b = parseInt(inp[1], 10), a_cpy = a, b_cpy = b;

    if(a === 0 && b === 0) {
        print('YES');

    } else if(a === b || (a%2 === 0 && b%2 === 0) || (a%2 !== 0 && b%2 !== 0) || a === 0 || b === 0) {
        print('NO');

    } else {
        if(a%2 === 0) {
            a_cpy -= 2;
            b_cpy -= 1;

        } else {
            a_cpy -= 1;
            b_cpy -= 2;

        }

        if(a_cpy === 0 && b_cpy === 0) {
            print('YES');

        } else if(a_cpy === 0 || b_cpy === 0) {
            print('NO');
        } else if(a_cpy>b_cpy) {
            if(a_cpy%b_cpy === 0) print('YES');
            else print('NO');

        } else if(b_cpy>=a_cpy && (a_cpy !== 0 && b_cpy !== 0)) {
            if(b_cpy%a_cpy === 0) print('YES');
            else print('NO');

        }
    }
}

var t = parseInt(readline(), 10);

while(t--) {
    var inp = readline().split(' ');
    var a = parseInt(inp[0], 10), b = parseInt(inp[1], 10), a_cpy = a, b_cpy = b;

    if(a === 0 && b === 0) {
        print('YES');

    } else if(a === b || (a%2 === 0 && b%2 === 0) || (a%2 !== 0 && b%2 !== 0) || a === 0 || b === 0) {
        print('NO');

    } else {
        if(a%2 === 0) {
            a_cpy -= 2;
            b_cpy -= 1;

        } else {
            a_cpy -= 1;
            b_cpy -= 2;

        }

        if(a_cpy === 0 && b_cpy === 0) {
            print('YES');

        } else if(a_cpy>b_cpy) {
            if(a_cpy%b_cpy === 0) print('YES');
            else print('NO');

        } else if(b_cpy>=a_cpy && (a_cpy !== 0 && b_cpy !== 0)) {
            if(b_cpy%a_cpy === 0) print('YES');
            else print('NO');

        }
    }
}

var t = parseInt(readline(), 10);

while(t--) {
    var inp = readline().split(' ');
    var a = parseInt(inp[0], 10), b = parseInt(inp[1], 10), div = 0, valid = true;

    if(a===0 && b===0) {
        valid = true;

    } else if(a===0 || b===0) {
        valid = false;

    } else if(a>b) {
        div = Math.floor(a/2);

        if(div < b) {
            a -= 2*div;
            b -= div;

            if(a!==1 || b!==2) valid = false;

        } else if(div === b && a%2 === 0) {
            valid = true;

        } else {
            valid = false;
        }

    } else {
        div = Math.floor(b/2);

        if(div < a) {
            b -= 2*div;
            a -= div;

            if(b!==1 || a!==2) valid = false;

        } else if(div === a && b%2 === 0) {
            valid = true;

        } else {
            valid = false;
        }
    }

    print(valid ? 'YES' : 'NO');
}

var t = parseInt(readline(), 10);

while(t--) {
    var inp = readline().split(' ');
    var a = parseInt(inp[0], 10), b = parseInt(inp[1], 10), div = 0, valid = true;

    if(a===0 && b===0) {
        valid = true;

    } else if(a===0 || b===0 || a===b) {
        valid = false;

    } else if(a>b) {
        div = Math.floor(a/2);

        if(div < b) {
            a -= 2*div;
            b -= div;

            if(a!==1 || b!==2) valid = false;

        } else if(div === b && a%2 === 0) {
            valid = true;

        } else {
            valid = false;
        }

    } else {
        div = Math.floor(b/2);

        if(div < a) {
            b -= 2*div;
            a -= div;

            if(b!==1 || a!==2) valid = false;

        } else if(div === a && b%2 === 0) {
            valid = true;

        } else {
            valid = false;
        }
    }

    print(valid ? 'YES' : 'NO');
}

var t = parseInt(readline(), 10);

while(t--) {
    var inp = readline().split(' ');
    var a = parseInt(inp[0], 10), b = parseInt(inp[1], 10), div = 0, valid = true;

    if(a===0 || b===0 || a===b) {
        valid = false;

    } else if(a>b) {
        div = Math.floor(a/2);

        if(div < b) {
            a -= 2*div;
            b -= div;

            if(a!==1 || b!==2) valid = false;

        } else if(div === b && a%2 === 0) {
            valid = true;

        } else {
            valid = false;
        }

    } else {
        div = Math.floor(b/2);

        if(div < a) {
            b -= 2*div;
            a -= div;

            if(b!==1 || a!==2) valid = false;

        } else if(div === a && b%2 === 0) {
            valid = true;

        } else {
            valid = false;
        }
    }

    print(valid ? 'YES' : 'NO');
}

var t = parseInt(readline(), 10);

while(t--) {
    var inp = readline().split(' ');
    var a = parseInt(inp[0], 10), b = parseInt(inp[1], 10), a_cpy = a, b_cpy = b;

    if(a === 0 && b === 0) {
        print('YES');

    } else if(a === b || (a%2 !== 0 && b%2 !== 0) || a === 0 || b === 0) {
        print('NO');

    } else {
        if(a%2 === 0 && b%2 === 0) {
            if(a>b) {
                a_cpy -= 2;
                b_cpy -= 1;
            } else {
                a_cpy -= 1;
                b_cpy -= 2;
            }

        } else if(a%2 === 0) {
            a_cpy -= 2;
            b_cpy -= 1;

        } else {
            a_cpy -= 1;
            b_cpy -= 2;

        }

        if(a_cpy === 0 && b_cpy === 0) {
            print('YES');

        } else if(a_cpy === 0 || b_cpy === 0) {
            print('NO');
        } else if(a_cpy>b_cpy) {
            if(a_cpy%b_cpy === 0) print('YES');
            else print('NO');

        } else if(b_cpy>=a_cpy && (a_cpy !== 0 && b_cpy !== 0)) {
            if(b_cpy%a_cpy === 0) print('YES');
            else print('NO');

        }
    }
}

var t = parseInt(readline(), 10);

while(t--) {
    var inp = readline().split(' ');
    var a = parseInt(inp[0], 10), b = parseInt(inp[1], 10), a_cpy = a, b_cpy = b;

    if(a === 0 && b === 0) {
        print('YES');

    } else if(a === b || (a%2 === 0 && b%2 === 0) || (a%2 !== 0 && b%2 !== 0)) {
        print('NO');

    } else {
        if(a%2 === 0) {
            a_cpy -= 2;
            b_cpy -= 1;

        } else {
            a_cpy -= 1;
            b_cpy -= 2;

        }

        if(a>b) {
            if(a_cpy%b_cpy === 0) print('YES');
            else print('NO');

        } else if(b>=a && (a_cpy !== 0 && b_cpy !== 0)) {
            if(b_cpy%a_cpy === 0) print('YES');
            else print('NO');

        } else if(a_cpy === 0 && b_cpy === 0) {
            print('YES');

        }
    }
}


'use strict';

function solve(n, a) {
  const cnt = Array.from({
    length: n
  }, () => []);
  for (let [i, num] of a.entries()) {
    cnt[num - 1].push(i);
  }
  const res = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    let t = -1,
        ans = 0,
        p = cnt[i][0] & 1 ^ 1;
    for (let j = 0; j < cnt[i].length; j++) {
      const num = cnt[i][j];
      if ((num & 1) !== p) {
        p ^= 1;
        ans++;
      } else if (t === -1) {
        t = j;
      }
    }
    if (t !== -1) {
      p = cnt[i][t] & 1 ^ 1;
      let ans1 = 0;
      for (let j = t; j < cnt[i].length; j++) {
        const num = cnt[i][j];
        if ((num & 1) !== p) {
          p ^= 1;
          ans1++;
        }
      }
      ans = Math.max(ans, ans1);
    }
    res[i] = ans;
  }
  return res.join(' ');
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let res = new Array(n).fill(0);
    let obj = {};
    for (let i = 0; i < n; i++) {
      if (obj[arr[i]]) obj[arr[i]].push(i);
      else {
        let k = [i];
        obj[arr[i]] = k;
      }
      res[arr[i] - 1] = 1;
    }
    for (let i of Object.keys(obj)) {
      let k = obj[i];
      if (k.length > 1) {
        for (let j = 0; j < k.length - 1; j++) {
          if ((k[j + 1] - k[j]) % 2 === 1) res[i - 1] += 1;
        }
      }
    }
    console.log(res.join(" "));
  }
};
solve();

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '', currentLine = 0;
process.stdin.on('data', inputStdin => { inputString += inputStdin; });
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => string.trim());
    main();
});
function readLine() {
    return inputString[currentLine++];
}

function main() {
    const t = parseInt(readLine(), 10);
    for(let i = 0; i < t; i++){
        const n = +readLine();
        const arr = readLine().split(' ').map(p => +p);
        myFunc(n, arr);
    }
}

function myFunc(n, arr){
    let resp = new Array(n).fill(0);
    let last = new Array(n);

    for(let j = 0; j < n; j++){
        if(last[arr[j]-1] == undefined){
            last[arr[j]-1] = j;
            resp[arr[j]-1]++;
        }
    }

    for(let i = 1; i < n; i++){
        if( (i-1-last[arr[i]-1])%2 == 0 ){
            resp[arr[i]-1]++;
        }
        last[arr[i]-1] = i;
    }//for1

    console.log(resp.join(' '));

}


'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 output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        const [rows, cols] = readline().split(' ').map(Number);

        for (let row = 0; row < rows; row++) {
            let line = '';
            for (let col = 0; col < cols; col++) {
                if (col !== 0) {
                    line += ' ';
                }
            if (row % 4 === 0 || row % 4 === 3) {
                line += (col % 4 === 0 || col % 4 === 3) ? '0' : '1';
            } else {
                line += (col % 4 === 0 || col % 4 === 3) ? '1' : '0';
            }
            }
            output(line);
          }
    }
}

'use strict';

function solve(n, m) {
  const res = Array.from({
    length: n
  }, () => new Array(m).fill(0));
  for (let i = 1; i < m; i++) {
    if ((i ^ 1) === i - 1) {
      res[0][i] = res[0][i - 1] ^ 1;
    } else {
      res[0][i] = res[0][i - 1];
    }
  }
  res[1][0] = 1;
  for (let i = 1; i < m; i++) {
    if ((i ^ 1) === i - 1) {
      res[1][i] = res[1][i - 1] ^ 1;
    } else {
      res[1][i] = res[1][i - 1];
    }
  }
  for (let i = 2; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if ((i ^ 1) === i - 1) {
        res[i][j] = res[i - 1][j] ^ 1;
      } else {
        res[i][j] = res[i - 1][j];
      }
    }
  }
  return res.map(arr => arr.join(' ')).join('\n');
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      res[i] = solve(n, m);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var arr = "";
process.stdin.on("data", function (chunk) {
  arr += chunk;
});

process.stdin.on("end", function () {
  arr = arr.split("\n");
  const testcases = parseInt(arr.shift());
  for (let t = 0; t < testcases; t++) {
    const [m, n] = arr[t].split(" ").map((el) => parseInt(el));

    const nums = [];
    for (let i = 0; i < parseInt(n / 4); i++) nums.push(1, 0, 0, 1);
    if (n % 4 >= 1) nums.push(1);
    if (n % 4 >= 2) nums.push(0);
    if (n % 4 >= 3) nums.push(0);

    const numsInv = [];
    for (let i = 0; i < n; i++) numsInv.push((nums[i] + 1) % 2);

    const matrix = [];
    for (let i = 0; i < parseInt(m / 4); i++) {
      matrix.push([...nums]);
      matrix.push([...numsInv]);
      matrix.push([...numsInv]);
      matrix.push([...nums]);
    }

    if (m % 4 >= 1) matrix.push([...nums]);
    if (m % 4 >= 2) matrix.push([...numsInv]);
    if (m % 4 >= 3) matrix.push([...numsInv]);

    console.log(matrix.map((el) => el.join(" ")).join("\n"));
  }
});

'use strict';

function solve(n, m) {
  const res = Array.from({
    length: n
  }, () => new Array(m).fill(0));
  for (let i = 1; i < m; i++) {
    if ((i ^ 1) === i - 1) {
      res[0][i] = res[0][i - 1] ^ 1;
    } else {
      res[0][i] = res[0][i - 1];
    }
  }
  res[1][0] = 1;
  for (let i = 1; i < m; i++) {
    if ((i ^ 1) === i - 1) {
      res[0][i] = res[0][i - 1] ^ 1;
    } else {
      res[0][i] = res[0][i - 1];
    }
  }
  for (let i = 2; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if ((i ^ 1) === i - 1) {
        res[i][j] = res[i - 1][j] ^ 1;
      } else {
        res[i][j] = res[i - 1][j];
      }
    }
  }
  return res.map(arr => arr.join(' ')).join('\n');
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      res[i] = solve(n, m);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, m) {
  if (n === 2 && m === 2) return `0 1\n1 0`;
  const res = Array.from({
    length: n
  }, () => new Array(m).fill(0));
  for (let i = 2; i < m; i += 4) {
    res[0][i] = res[0][i - 1] = 1;
  }
  res[1][0] = 1;
  res[1][m - 1] = 1;
  for (let i = 4; i < m; i += 4) res[1][i] = res[1][i - 1] = 1;
  for (let i = 2; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if ((i ^ 1) === i - 1) {
        res[i][j] = res[i - 1][j] ^ 1;
      } else {
        res[i][j] = res[i - 1][j];
      }
    }
  }
  return res.map(arr => arr.join(' ')).join('\n');
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      res[i] = solve(n, m);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, m) {
  if (n === 2 && m === 2) return `0 0\n0 0`;
  const res = Array.from({
    length: n
  }, () => new Array(m).fill(0));
  for (let i = 2; i < m; i += 4) {
    res[0][i] = res[0][i - 1] = 1;
  }
  res[1][0] = 1;
  res[1][m - 1] = 1;
  for (let i = 4; i < m; i += 4) res[1][i] = res[1][i - 1] = 1;
  for (let i = 2; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if ((i ^ 1) === i - 1) {
        res[i][j] = res[i - 1][j] ^ 1;
      } else {
        res[i][j] = res[i - 1][j];
      }
    }
  }
  return res.map(arr => arr.join(' ')).join('\n');
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      res[i] = solve(n, m);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var arr = "";
process.stdin.on("data", function (chunk) {
  arr += chunk;
});

process.stdin.on("end", function () {
  arr = arr.split("\n");
  const testcases = parseInt(arr.shift());
  for (let t = 0; t < testcases; t++) {
    const [m, n] = arr[t].split(" ").map((el) => parseInt(el));

    const nums = [];
    for (let i = 0; i < parseInt(n / 4); i++) nums.push(1, 0, 0, 1);
    if (n % 4 >= 1) nums.push(1);
    if (n % 4 >= 2) nums.push(0);
    if (n % 4 >= 3) nums.push(0);

    const numsInv = [];
    for (let i = 0; i < n; i++) numsInv.push((nums[i] + 1) % 2);

    const matrix = [];
    for (let i = 0; i < parseInt(m / 4); i++) {
      matrix.push([...nums]);
      matrix.push([...numsInv]);
      matrix.push([...numsInv]);
      matrix.push([...nums]);
    }

    if (n % 4 >= 1) matrix.push([...nums]);
    if (n % 4 >= 2) matrix.push([...numsInv]);
    if (n % 4 >= 3) matrix.push([...numsInv]);

    // for (let i = 0; i < m; i++) matrix.push([...nums]);
    // for (let i = 1; i < m; i += 2) {
    //   for (let j = 0; j < n; j++) {
    //     matrix[i][j] = (matrix[i][j] + 1) % 2;
    //   }
    // }

    console.log(matrix.map((el) => el.join(" ")).join("\n"));
  }
});

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var arr = "";
process.stdin.on("data", function (chunk) {
  arr += chunk;
});

process.stdin.on("end", function () {
  arr = arr.split("\n");
  const testcases = parseInt(arr.shift());
  for (let t = 0; t < testcases; t++) {
    const [m, n] = arr[t].split(" ").map((el) => parseInt(el));

    const nums = [];
    for (let i = 0; i < parseInt(n / 4); i++) nums.push(1, 0, 0, 1);
    if (n % 4 >= 1) nums.push(1);
    if (n % 4 >= 2) nums.push(0);
    if (n % 4 >= 3) nums.push(0);

    const matrix = [];
    for (let i = 0; i < m; i++) matrix.push([...nums]);
    for (let i = 1; i < m; i += 2) {
      for (let j = 0; j < n; j++) {
        matrix[i][j] = (matrix[i][j] + 1) % 2;
      }
    }

    console.log(matrix.map((el) => el.join(" ")).join("\n"));
  }
});

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var arr = "";
process.stdin.on("data", function (chunk) {
  arr += chunk;
});

process.stdin.on("end", function () {
  arr = arr.split("\n");
  const testcases = parseInt(arr.shift());
  for (let t = 0; t < testcases; t++) {
    const [m, n] = arr[t].split(" ").map((el) => parseInt(el));

    const matrix = [];
    for (let i = 0; i < m; i++) matrix.push([]);

    for (let i = 0; i < m; i += 2) {
      let start = 0;
      for (let j = 0; j < n; j++) {
        matrix[i][j] = (start + 1) % 2;
        start = (start + 1) % 2;
      }
    }

    for (let i = 1; i < m; i += 2) {
      let start = 1;
      for (let j = 0; j < n; j++) {
        matrix[i][j] = (start + 1) % 2;
        start = (start + 1) % 2;
      }
    }

    console.log(matrix.map((el) => el.join(" ")).join("\n"));
  }
});