const iteration = (arr) => {

}

const solve = (data, n, m) => {
	const arr = [];

	for (let i=0; i<data.length; i++) {
		arr[i] = data[i].sort((a, b) => a-b);
	}

	const res = [];

	for (let j=0; j<m; j++) {
		let min = arr[0][0], minIndex = 0;

		for (let i=0; i<arr.length; i++) {
			const minEl = arr[i][0];
			const maxEl = arr[i][arr[i].length - 1];

			if (minEl < min) {
				min = minEl;
				minIndex = i;
			}

			res[i] = res[i] || [];
			res[i][j] = maxEl;
		}

		for (let i=0; i<arr.length; i++) {
			res[i] = res[i] || [];
			if (i === minIndex) {
				res[i][j] = min;
				arr[i].splice(0, 1);
			} else {
				arr[i].splice(arr[i].length-1, 1);
			}
		}
	}

	console.log(res.map(item => item.join(' ')).join('\n'));
}

let input = '';
process.stdin.on('data', str => input += str)
process.stdin.on('end', () => {
	const lines = input.trim().split('\n').slice(1);

	for (let i=0; i<lines.length; i++) {
		const [n, m] = lines[i].split(' ').map(v => +v);
		const data = lines.slice(i+1, i+n+1)
			.map(line => line.split(' ').map(v => +v));

		solve(data, n, m);

		i+=n;
	}
})

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 () {
	let t = rn();
	while (t--) {
		const [n, m] = rna();
		const b = Array(n);
		for (let i = 0; i < n; i++) {
			b[i] = rna();
			b[i].sort((x, y) => x - y);
		}

		for (let i = 0; i < m; i++) {
			let k = 0;
			for (let j = 0; j < n; j++) {
				if (b[j][0] < b[k][0])
					k = j;
			}
			const r = m - 1 - i;
			b[k] = [...b[k].slice(1, r + 1), b[k][0], ...b[k].slice(r + 1)];
		}

		for (row of b)
			console.log(row.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));

function main () {
	let t = rn();
	while (t--) {
		const [n, m] = rna();
		const b = Array(n);
		for (let i = 0; i < n; i++) {
			b[i] = rna();
			b[i].sort((x, y) => x - y);
		}

		//console.log('b', b);
		const paths = [];
		for (let i = 0; i < m; i++) {
			paths[i] = [];
			let k = 0;
			for (let j = 0; j < n ; j++) {
				paths[i].push(b[j].pop());
				if (b[j][0] < b[k][0]) k = j;
			}
			b[k].push(paths[i][k]);
			paths[i][k] = b[k].shift();
		}
		//console.log('paths',paths)

		for (let i = 0; i < n; i++) {
			let ans = [];
			for (let j = 0; j < m; j++)
				ans.push(paths[j][i]);

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

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
//////////// LIBS
const io = new IO();
function solve(n, m, arr) {
    let combined = [];
    arr.forEach((arr2, k) => {
        arr2.forEach((v, i) => {
            combined.push({ v, k, i });
        });
    });
    combined.sort((a, b) => a.v - b.v);
    let ret = Array.from({ length: n }).map(() => []);
    for (let i = 0; i < m; i++) {
        let target = combined[i];
        ret[target.k][i] = target.v;
    }
    let next = Array.from({ length: n }).map(() => 0);
    for (let i = m; i < combined.length; i++) {
        let target = combined[i];
        let idx = next[target.k];
        while (ret[target.k][idx]) {
            idx++;
        }
        ret[target.k][idx] = target.v;
        next[target.k] = idx;
    }
    ret.forEach((t) => {
        t.forEach((a) => {
            io.write(a);
        });
        io.writeLine('');
    });
}
function main() {
    try {
        let t = io.nextNum();
        while (t--) {
            let n = io.nextNum();
            let m = io.nextNum();
            let arr = [];
            for (let i = 0; i < n; i++) {
                arr.push(io.nextNumArray(m));
            }
            solve(n, m, arr);
        }
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

//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 e = new Array();
		var output = new Array(N);
		for(var j = 0; j < N; j++){
			output[j] = new Array(M);
			for(var k = 0; k < M; k++){
				e.push({
					y : j,
					x : k,
					v : nextInt()
				});
			}
		}
		e.sort(function(a,b){
			return a.v - b.v;
		});
		for(var j = 0; j < M; j++){
			output[e[0].y][j] = e[0];
			e.shift();
		}
		var index = 0;
		e.sort(function(a,b){
			if(a.y == b.y){
				return a.x - b.x;
			}else{
				return a.y - b.y;
			}

		});

		for(var j = 0; j < N; j++){
			for(var k = 0; k < M; k++){
				if(output[j][k] == null){
					output[j][k] = e[index].v;
					index++;
				}else{
					output[j][k] = output[j][k].v;
				}
			}
			myout(myconv(output[j], 8));
		}
	}
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var line1 = readline().split(' ').map(a => parseInt(a));
  var n = line1[0];
  var m = line1[1];
  var a = [];

  for (var j = 0; j < n; j++)
    a.push(readline().split(' ').map(a => parseInt(a)));

  for (var i = 0; i < m; i++) {
    for (var j = 0; j < n; j++) {
      var left = a[j].splice(0, i);
      a[j].sort((a, b) => a - b);
      a[j] = left.concat(a[j]);
    }

    var f = 0;
    for (j = 0; j < n; j++)
      if (a[j][i] < a[f][i])
        f = j;

    for (j = 0; j < n; j++)
      if (j !== f) {
        var tt = a[j][i];
        a[j][i] = a[j][m - 1];
        a[j][m - 1] = tt;
      }
  }

  for (var i = 0; i < n; i++) {
    for (var j = 0; j < m; j++)
      write(`${a[i][j]} `);
    write('\n');
  }
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}
function getValue() {
  return parseInt(readline());
}
const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, m] = iInpArr();
    let arr = [];
    for (let i = 0; i < n; i++) {
      arr.push(iInpArr());
      arr[i].sort((a, b) => a - b);
    }
    let narr = [];
    for (let i = 0; i < n; i++)
      for (let j = 0; j < m; j++) narr.push({ val: arr[i][j], i: i, j: j });
    narr.sort((a, b) => a.val - b.val);
    for (let k = m - 1; k >= 0; k--) {
      let i = narr[k].i;
      let j = narr[k].j;
      [arr[i][j], arr[i][k]] = [arr[i][k], arr[i][j]];
    }
    for (let i = 0; i < n; i++) console.log(arr[i].join(" "));
  }
};
solve();

var t = parseInt(readline());

for(i = 0; i < t; i++) {
    var n = readline().split(" ");
    var m = n[1];
    n = n[0];
    var b = [];
    var used = [];
    var string = [];
    for(s = 0; s < n; s++) {
        temp = readline().split(" ");
        for(k = 0; k < temp.length; k++) {temp[k] = parseInt(temp[k]);}
        temp.sort(function(a, b) { return a - b; });
        b = b.concat(temp);
        used[i] = 0;
    }
    var min = [], max = [], minp = [], maxp = [];
    for(j = 0; j < n; j++) {
        min[j] = b[m * j];
        minp[j] = m * j;
        max[j] = b[m * (j + 1) - 1];
        maxp[j] = m * (j + 1) - 1;
    }
    for(q = 0; q < m; q++) {
        var index = min.indexOf(Math.min.apply(null, min));
        for(r = 0; r < n; r++) {
            if(r === index) {
                string.push(min[index]);
                minp[r] += 1;
                min[r] = b[minp[r]];
            }
            else {
                string.push(max[r]);
                maxp[r] -= 1;
                max[r] = b[maxp[r]];
            }
        }
    }
    var output = "";
    for(u = 0; u < n; u++) {
        output = "";
        for(v = 0; v < m; v++) {
            output += string[v * n + u] + " ";
        }
        output = output.slice(0, output.length - 1);
        print(output);
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

var maxN = 2 * 1e5 + 10
var mod = 1e9 + 7

function main() {
  const xx = readline();
  Array(Number(xx)).fill(1).map((t, i) => {
    // var n = parseInt(readline());
    var [n, m] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })
    var a = new Array(n)
    var copy = new Array(n)
    var used = new Array(n)

    for (let j = 0; j < n; j++) {
      a[j] = readline().split(' ').map((x, iii) => {
        return parseInt(x)
      })
      copy[j] = new Array(m)
      used[j] = new Array(m).fill(false)
    }
    var arryMin = []
    var min = Number.MAX_SAFE_INTEGER
    for (let i = 0; i < n; i++) {
      for (let j = 0; j < m; j++) {
        arryMin.push({value: a[i][j], i, j})
      }
    }
    arryMin.sort((a, b) => a.value - b.value)

    for (let k = 0; k < m; k++) {
      var value = arryMin[k]
      used[value.i][value.j] = true
      copy[value.i][k] = value.value
    }

    for (let i = 0; i < n; i++) {
      var index = 0
      for (let j = 0; j < m; j++) {
        if (!used[i][j]) {
          while (copy[i][index] !== undefined) index++
          copy[i][index] = a[i][j]
        }
      }
    }
    for (let k = 0; k < n; k++) {
      console.log(copy[k].join(' '))
    }
    // var a = readline().split(' ').map((x, iii) => {
    //   return parseInt(x)
  })
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}
function getValue() {
  return parseInt(readline());
}
const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, m] = iInpArr();
    let arr = [];
    for (let i = 0; i < n; i++) arr.push(iInpArr());
    let narr = [];
    arr.sort((a, b) => a - b);
    for (let i = 0; i < n; i++)
      for (let j = 0; j < m; j++) narr.push({ val: arr[i][j], i: i, j: j });
    narr.sort((a, b) => a.val - b.val);
    for (let k = m - 1; k >= 0; k--) {
      let i = narr[k].i;
      let j = narr[k].j;
      [arr[i][j], arr[i][k]] = [arr[i][k], arr[i][j]];
    }
    for (let i = 0; i < n; i++) console.log(arr[i].join(" "));
  }
};
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, m] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = [];
    for (let i = 0; i < n; i++) {
      arr.push(
        readline()
          .trim()
          .split(" ")
          .map((cur) => parseInt(cur))
      );
    }
    if (n === 1) {
      console.log(arr[0].join(" "));
      continue;
    }
    if (m === 1) {
      for (let i = 0; i < n; i++) {
        console.log(arr[i][0]);
      }
      continue;
    }
    //for (let i = 0; i < n; i++) arr[i].sort((a, b) => b - a);
    for (let i = 0; i < n; i++)
      for (let j = 0; j < m; j++) arr[i][j] = { val: arr[i][j], i: i, j: j };
    let narr = [];
    for (let i = 0; i < n; i++)
      for (let j = 0; j < m; j++) narr.push(arr[i][j]);
    narr.sort((a, b) => a.val - b.val);
    let narr1 = [];
    for (let i = 0; i < m; i++) narr1.push(narr[i]);
    narr1.sort((a, b) => a.i - b.i);
    const replace = (i, ele) => {
      [arr[ele.i][i], arr[ele.i][ele.j]] = [arr[ele.i][ele.j], arr[ele.i][i]];
    };
    for (let i = 0; i < m; i++) replace(i, narr1[i]);
    for (let i = 0; i < n; i++) {
      let res = "";
      for (let j = 0; j < m; j++) {
        res += arr[i][j].val + " ";
      }
      console.log(res);
    }
  }
};
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, m] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = [];
    for (let i = 0; i < n; i++) {
      arr.push(
        readline()
          .trim()
          .split(" ")
          .map((cur) => parseInt(cur))
      );
    }
    if (n === 1) {
      console.log(arr[0].join(" "));
      continue;
    }
    if (m === 1) {
      for (let i = 0; i < n; i++) {
        console.log(arr[i][0]);
      }
      continue;
    }
    for (let i = 0; i < n; i++) arr[i].sort((a, b) => b - a);
    for (let i = 0; i < n; i++)
      for (let j = 0; j < m; j++) arr[i][j] = { val: arr[i][j], i: i, j: j };
    let narr = [];
    for (let i = 0; i < n; i++)
      for (let j = 0; j < m; j++) narr.push(arr[i][j]);
    narr.sort((a, b) => a.val - b.val);
    const replace = (i, ele) => {
      [arr[ele.i][i], arr[ele.i][ele.j]] = [arr[ele.i][ele.j], arr[ele.i][i]];
    };
    for (let i = 0; i < m; i++) replace(i, narr[i]);
    for (let i = 0; i < n; i++) {
      let res = "";
      for (let j = 0; j < m; j++) {
        res += arr[i][j].val + " ";
      }
      console.log(res);
    }
  }
};
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, m] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = [];
    for (let i = 0; i < n; i++) {
      arr.push(
        readline()
          .trim()
          .split(" ")
          .map((cur) => parseInt(cur))
      );
    }
    arr[0].sort((a, b) => a - b);
    if (n === 1) {
      console.log(arr[0].join(" "));
      continue;
    }
    if (m === 1) {
      for (let i = 0; i < n; i++) {
        console.log(arr[i][0]);
      }
      continue;
    }
    for (let i = 1; i < n; i++) arr[i].sort((a, b) => b - a);
    let res = new Array(n).fill(0).map((cur) => new Array(m).fill(0));
    for (let i = 0; i < m; i++) res[0][i] = arr[0][i];
    for (let i = 0; i < m; i++) {
      for (let k = 1; k < n; k++) {
        res[k][i] = arr[k][i];
      }
    }
    for (let i = 0; i < res.length; i++) {
      console.log(res[i].join(" "));
    }
  }
};
solve();

const solve = (data, m) => {
	const arr = [];

	for (let i=0; i<data.length; i++) {
		arr[i] = data[i].sort((a, b) => a-b).slice(0, m)

		if (i%2 === 0) {
			arr[i] = arr[i].reverse();
		}
	}

	console.log(arr.map(item => item.join(' ')).join('\n'))
}

let input = '';
process.stdin.on('data', str => input += str)
process.stdin.on('end', () => {
	const lines = input.trim().split('\n').slice(1);

	for (let i=0; i<lines.length; i++) {
		const [n, m] = lines[i].split(' ').map(v => +v);
		const data = lines.slice(i+1, i+n+1)
			.map(line => line.split(' ').map(v => +v));

		solve(data, m);

		i+=n;
	}
})

const solve = (data, m) => {
	const arr = [];

	for (let i=0; i<data.length; i++) {
		arr[i] = data[i].sort((a, b) => a-b).slice(0, m)

		if (i%2 === 2) {
			arr[i].reverse();
		}
	}

	console.log(arr.map(item => item.join(' ')).join('\n'))
}

let input = '';
process.stdin.on('data', str => input += str)
process.stdin.on('end', () => {
	const lines = input.trim().split('\n').slice(1);

	for (let i=0; i<lines.length; i++) {
		const [n, m] = lines[i].split(' ').map(v => +v);
		const data = lines.slice(i+1, i+n+1)
			.map(line => line.split(' ').map(v => +v));

		solve(data, m);

		i+=n;
	}
})

const solve = (data, m) => {
	const arr = [];
	for (let i=0; i<data.length; i++) {
		arr.push(...data[i].sort((a, b) => a-b).slice(0, m));
	}

	return arr
		.sort((a, b) => a-b)
		.slice(0, m)
		.reduce((acc, item) => acc + item, 0);
}

let input = '';
process.stdin.on('data', str => input += str)
process.stdin.on('end', () => {
	const lines = input.trim().split('\n').slice(1);

	for (let i=0; i<lines.length; i++) {
		const [n, m] = lines[i].split(' ').map(v => +v);
		const data = lines.slice(i+1, i+n+1)
			.map(line => line.split(' ').map(v => +v));

		console.log(solve(data, m));

		i+=n;
	}
})

'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++];
}

var maxN = 2 * 1e5 + 10
var mod = 1e9 + 7

function main() {
  const xx = readline();
  Array(Number(xx)).fill(1).map((t, i) => {
    // var n = parseInt(readline());
    var [n, m] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })
    var a = new Array(n)
    var used = new Array(n)
    var answer = new Array(n)

    for (let j = 0; j < n; j++) {
      a[j] = readline().split(' ').map((x, iii) => {
        return parseInt(x)
      })
      used = new Array(m).fill(false)
      answer = new Array(m)
    }
    var copy = []
    for (let j = 0; j < n; j++) {
      a[j].sort((a, b) =>a - b)
      copy = new Array(a[j].length)
      // console.log(a[j])
      for (let k = 0; k < a[j].length; k++) {
        copy[(k+j) %a[j].length] = a[j][k]
      }
      a[j] = copy
    }
    for (let j = 0; j < n; j++) {
      console.log(a[j].join(' '))
    }

    // var a = readline().split(' ').map((x, iii) => {
    //   return parseInt(x)
  })
}

'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++];
}

var maxN = 2 * 1e5 + 10
var mod = 1e9 + 7

function main() {
  const xx = readline();
  Array(Number(xx)).fill(1).map((t, i) => {
    // var n = parseInt(readline());
    var [n, m] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })
    var a = new Array(n)
    var used = new Array(n)
    var answer = new Array(n)

    for (let j = 0; j < n; j++) {
      a[j] = readline().split(' ').map((x, iii) => {
        return parseInt(x)
      })
      used = new Array(m).fill(false)
      answer = new Array(m)
    }
    for (let j = 0; j < n; j++) {
      a[j].sort((a, b) => j % 2 === 0 ? a - b : b - a)
    }
    for (let j = 0; j < n; j++) {
      console.log(a[j].join(' '))

    }

    // var a = readline().split(' ').map((x, iii) => {
    //   return parseInt(x)
  })
}

'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++];
}

var maxN = 2 * 1e5 + 10
var mod = 1e9 + 7

function main() {
  const xx = readline();
  Array(Number(xx)).fill(1).map((t, i) => {
    // var n = parseInt(readline());
    var [n, m] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })
    var a = new Array(n)
    var used = new Array(n)
    var answer = new Array(n)

    for (let j = 0; j < n; j++) {
      a[j] = readline().split(' ').map((x, iii) => {
        return parseInt(x)
      })
      used = new Array(m).fill(false)
      answer = new Array(m)
    }
    for (let j = 0; j < n; j++) {
      a[j].sort((a, b) => j % 2 === 0 ? a - b : b - 1)
    }
    for (let j = 0; j < n; j++) {
      console.log(a[j].join(' '))

    }

    // var a = readline().split(' ').map((x, iii) => {
    //   return parseInt(x)
  })
}

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 () {
	let t = rn();
	while (t--) {
		const [n, m] = rna();
		const b = Array(n);
		for (let i = 0; i < n; i++) {
			b[i] = rna();
			b[i].sort((x, y) => x - y);
		}

		//console.log('b', b);
		const paths = [];
		for (let i = 0; i < m; i++) {
			paths[i] = [];
			let k = 0;
			for (let j = 0; j < n ; j++) {
				paths[i].push(b[j].pop());
				if (b[j] < b[k]) k = j;
			}
			b[k].push(paths[i][k]);
			paths[i][k] = b[k].shift();
		}
		//console.log('paths',paths)

		for (let i = 0; i < n; i++) {
			let ans = [];
			for (let j = 0; j < m; j++)
				ans.push(paths[j][i]);

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

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
//////////// LIBS
const io = new IO();
function solve(n, m, arr) {
    let combined = [];
    arr.forEach((arr2, k) => {
        arr2.forEach((v, i) => {
            combined.push({ v, k, i });
        });
    });
    for (let i = 0; i < m; i++) {
        let target = combined[i];
        let tmp = arr[target.k][i];
        arr[target.k][i] = target.v;
        arr[target.k][target.i] = tmp;
    }
    arr.forEach((t) => {
        t.forEach((a) => {
            io.write(a);
        });
        io.writeLine('');
    });
    // console.log(arr);
    // for (let i = 0; i < m; i++) {
    //   io.write(arr[0].shift()!);
    //   for (let j = 1; j < n; j++) {
    //     io.write(arr[j].pop()!);
    //   }
    //   io.writeLine('');
    // }
}
function main() {
    try {
        let t = io.nextNum();
        while (t--) {
            let n = io.nextNum();
            let m = io.nextNum();
            let arr = [];
            for (let i = 0; i < n; i++) {
                arr.push(io.nextNumArray(m));
            }
            solve(n, m, arr);
        }
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
//////////// LIBS
const io = new IO();
function solve(n, m, arr) {
    arr.forEach((t) => {
        t.sort((a, b) => b - a);
    });
    arr[0].reverse();
    arr.forEach((t) => {
        t.forEach((a) => {
            io.write(a);
        });
        io.writeLine('');
    });
    // console.log(arr);
    // for (let i = 0; i < m; i++) {
    //   io.write(arr[0].shift()!);
    //   for (let j = 1; j < n; j++) {
    //     io.write(arr[j].pop()!);
    //   }
    //   io.writeLine('');
    // }
}
function main() {
    try {
        let t = io.nextNum();
        while (t--) {
            let n = io.nextNum();
            let m = io.nextNum();
            let arr = [];
            for (let i = 0; i < n; i++) {
                arr.push(io.nextNumArray(m));
            }
            solve(n, m, arr);
        }
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var line1 = readline().split(' ').map(a => parseInt(a));
  var n = line1[0];
  var m = line1[1];
  var a = [];

  for (var j = 0; j < n; j++)
    a.push(
      readline().split(' ').map(a => parseInt(a)).sort((a, b) => b - a)
    );

  for (var i = 0; i < m; i++) {
    var f = 0;
    for (j = 0; j < n; j++)
      if (a[j][i] < a[f][i])
        f = j;

    for (j = 0; j < n; j++)
      if (j !== f) {
        var tt = a[j][i];
        a[j][i] = a[j][m - 1];
        a[j][m - 1] = tt;
      }
  }

  for (var i = 0; i < n; i++) {
    for (var j = 0; j < m; j++)
      write(`${a[i][j]} `);
    write('\n');
  }
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var line1 = readline().split(' ').map(a => parseInt(a));
  var n = line1[0];
  var m = line1[1];
  var a = [];

  for (var j = 0; j < n; j++)
    a.push(
      readline().split(' ').map(a => parseInt(a)).sort((a, b) => a - b)
    );

  for (var i = 0; i < m; i++) {
    var f = 0;
    for (j = 0; j < n; j++)
      if (a[j][i] < a[f][i])
        f = j;

    for (j = 0; j < n; j++)
      if (j !== f) {
        var tt = a[j][i];
        a[j][i] = a[j][m - 1];
        a[j][m - 1] = tt;
      }
  }

  for (var i = 0; i < n; i++) {
    for (var j = 0; j < m; j++)
      write(`${a[i][j]} `);
    write('\n');
  }
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var line1 = readline().split(' ').map(a => parseInt(a));
  var n = line1[0];
  var m = line1[1];
  var a = [];

  for (var j = 0; j < n; j++)
    a.push(
      readline().split(' ').map(a => parseInt(a)).sort((a, b) => a - b)
    );

  for (var i = 0; i < m; i++) {
    var f = 0;
    for (j = 0; j < n; j++)
      if (a[j][i] < a[f][i])
        f = j;

    for (j = 0; j < n; j++)
      if (j != f) {
        var tt = a[j][i];
        a[j][i] = a[j][m - 1];
        a[j][m - 1] = tt;
      }
  }

  for (var i = 0; i < n; i++) {
    for (var j = 0; j < m; j++)
      write(`${a[i][j]} `);
    write('\n');
  }
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var line1 = readline().split(' ').map(a => parseInt(a));
  var n = line1[0];
  var m = line1[1];
  var a = [];

  for (var j = 0; j < n; j++)
    a.push(
      readline().split(' ').map(a => parseInt(a)).sort((a, b) => a - b)
    );

  for (var i = 0; i < n; i++) {
    var f = 0;
    for (j = 0; j < n; j++)
      if (a[j][i] < a[f][i])
        f = j;

    for (j = 0; j < n; j++)
      if (j != f) {
        var tt = a[j][i];
        a[j][i] = a[j][m - 1];
        a[j][m - 1] = tt;
      }
  }

  for (var i = 0; i < n; i++) {
    for (var j = 0; j < m; j++)
      write(`${a[i][j]} `);
    write('\n');
  }
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var line1 = readline().split(' ').map(a => parseInt(a));
  var n = line1[0];
  var m = line1[1];
  var a = [];

  for (var j = 0; j < n; j++)
    a.push(
      readline().split(' ').map(a => parseInt(a)).sort((a, b) => a - b)
    );

  for (var i = 0; i < n; i++) {
    var f = 0;
    for (j = 0; j < n; j++)
      if (a[j][i] < a[f][i])
        f = j;

    for (j = 0; j < n; j++)
      if (j != f) {
        var tt = a[j][i];
        a[j][i] = a[j][m - 1];
        a[j][m - 1] = tt;
      }
  }

  for (var j = 0; j < n; j++) {
    for (var i = 0; i < m; i++)
      write(`${a[j][i]} `);
    write('\n');
  }
}

var t = parseInt(readline());

for(i = 0; i < t; i++) {
    var n = readline().split(" ");
    var m = n[1];
    n = n[0];
    var b = [];
    var used = [];
    var string = [];
    for(s = 0; s < n; s++) {
        temp = readline().split(" ");
        for(k = 0; k < temp.length; k++) {temp[k] = parseInt(temp[k]);}
        temp.sort(function(a, b) { return a - b; });
        b = b.concat(temp);
        used[i] = 0;
    }
    var min = [], max = [], minp = [], maxp = [];
    for(j = 0; j < n; j++) {
        min[j] = b[m * j];
        minp[j] = m * j;
        max[j] = b[m * (j + 1) - 1];
        maxp[j] = m * (j + 1) - 1;
    }
    for(q = 0; q < m; q++) {
        var index = min.indexOf(Math.min.apply(null, min));
        for(r = 0; r < n; r++) {
            if(r === index) {
                string.push(min[index]);
                minp[r] += 1;
                min[r] = b[minp[r]];
            }
            else {
                string.push(max[r]);
                maxp[r] -= 1;
                max[r] = b[maxp[r]];
            }
        }
    }
    var output = "";
    print(string);
    for(u = 0; u < n; u++) {
        output = "";
        for(v = 0; v < m; v++) {
            output += string[v * n + u] + " ";
        }
        output = output.slice(0, output.length - 1);
        print(output);
    }
}

var t = parseInt(readline());

for(i = 0; i < t; i++) {
    var n = readline().split(" ");
    var m = n[1];
    n = n[0];
    var b = [];
    var used = [];
    var string = [];
    for(s = 0; s < n; s++) {
        temp = readline().split(" ");
        for(k = 0; k < temp.length; k++) {temp[k] = parseInt(temp[k]);}
        temp.sort(function(a, b) { return a - b; });
        b = b.concat(temp);
        used[i] = 0;
    }
    var min = [], max = [], minp = [], maxp = [];
    for(j = 0; j < n; j++) {
        min[j] = b[m * j];
        minp[j] = m * j;
        max[j] = b[m * (j + 1) - 1];
        maxp[j] = m * (j + 1) - 1;
    }
    for(q = 0; q < m; q++) {
        var index = min.indexOf(Math.min.apply(null, min));
        for(r = 0; r < n; r++) {
            if(r === index) {
                string.push(min[index]);
                minp[r] += 1;
                min[r] = b[minp[r]];
            }
            else {
                string.push(max[r]);
                maxp[r] -= 1;
                max[r] = b[maxp[r]];
            }
        }
    }
    var output = "";
    print(string);
    for(u = 0; u < n; u++) {
        output = "";
        for(v = 0; v < m; v++) {
            output += string[v * n + u] + " ";
        }
        output.slice(0, output.length - 1);
        print(output);
    }
}


const readline = require('readline')

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

function solve(n, str) {
    const sorted = str.split('')
        .sort((a, b) => a < b ? 1 : (b < a ? -1 : 0))
    return sorted[0].charCodeAt(0) - 'a'.charCodeAt(0) + 1
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	var alpha = "abcdefghijklmnopqrstuvwxyz";
	while(hasNext()){
		var N = nextInt();
		var s = next();
		var max = 0;
		for(var i = 0; i < N; i++){
			max = Math.max(max, alpha.indexOf(s[i]) + 1);
		}
		myout(max);
	}
}

var t = +readline();

for(var i = 0; i< t; i ++) {

      var nums = [];
    var arr = readline()
    var arr = readline()

    print(alphabet(arr))

}

function alphabet(arr){

    var max = -Infinity
    for(var l of arr){
        max = Math.max(max,l.charCodeAt(0) - 96);
    };
    return max
}

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

let inputString = "";
let currentLine = 0;

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

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.trim().split("\n").map(line =>{
	return line.trim()
});
  main();
});

// ********** Code Start **********
function findLow(str,n){

      let s = 'abcdefghijklmnopqrstuvwxyz'

      let max = 'a';
      for(let i=0;i<n;i++){
          if(str[i]>max){
              max = str[i]
              // console.log(max)
          }
      }
      let res = 0;
      for(let i=0;i<s.length;i++){
          if(s[i]===max){
             res = i+1;
             break;
          }
      }
      return res;
  }
function main() {
  let t = readline();
  t = parseInt(t);
  while(t--){

    let n = readline();
    n = parseInt(n)
    let str = readline();
     console.log(findLow(str,n))
  }
}

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main() {
const t = readline();
for (let i = 0; i < t; i++) {
  const chars = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6,
    g: 7,
    h: 8,
    i: 9,
    j: 10,
    k: 11,
    l: 12,
    m: 13,
    n: 14,
    o: 15,
    p: 16,
    q: 17,
    r: 18,
    s: 19,
    t: 20,
    u: 21,
    v: 22,
    w: 23,
    x: 24,
    y: 25,
    z: 26,
  };
  var l = readline();
  var s = readline();
  let maxSize = 0;
  for (let i = 0; i < l; i++) {
    if (chars[s[i]] > maxSize) {
      maxSize = chars[s[i]];
    }
  }
  console.log(maxSize);
}

}

let buf='';

process.stdin.on('readable', function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end', function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    for(let _=1;_<=t;_++)
    {
        let n=parseInt(line[2*_-1]);
        let s=line[2*_];
        let ans=1;
        for(let i=0;i<n;i++)
        {
            ans=Math.max(ans,s.charCodeAt(i)-97+1);
        }
        console.log(ans);
    }
})

'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 testNumbers = readline();

    for(let i = 0; i<testNumbers; i++){
        solve(parseInt(readline()), readline());
    }
}

function solve(size, input){
    let dicc = {
        a:1, b:2, c:3, d:4, e:5, f:6, g:7, h:8, i:9, j:10, k:11, l:12, m:13, n:14, o:15, p:16, q:17, r:18, s:19, t:20, u:21, v:22, w:23, x:24, y:25, z:26
    }
    let max = 'a'
    for(let i = 0; i<size; i++){
        max = max > input[i] ? max : input[i];
    }
    console.log(dicc[max]);
}

'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 testCases = Number(readline());
    for (let i = 0; i < testCases; i++) {
        let len = Number(readline());
        let s = readline();
        console.log(findMedium(len,s))
    }
}

function findMedium(len, s) {
    let res = s[0].charCodeAt(0)
    let a = 97;
    for (let i = 1; i < len; i++) {
        let ch = s[i].charCodeAt(0)
        if (ch > res) {
            res = ch
        }
    }

    return res - a + 1
}

const fs = require("fs");
const input = fs.readFileSync(0, 'utf8').trim().split('\r\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}
function alph() {
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return f;
}
function max(x,y) {
  return x >=y ? x : y;
}
function min(x,y) {
  return x <=y ? x : y;
}
function abs(x) {
  return x < 0 ? x*(-1) : x;
}
var T = readline();
var inf = 1000000000000;
for(var tc=1;tc<=T;tc++) {
	var N = readline();
	var n = readline();
	var arr = alph();
	var maxx = 0;
	for(var i=0;i<N;i++) maxx = max(maxx, arr.indexOf(n[i]));
	console.log(maxx+1);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

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

    return gcd( b , a%b )
}

function main() {

    let t = parseInt(readLine());

    //let mod = 10**9+7
    loopwhile:
    while(t--)
    {

        let n = parseInt(readLine());

        let s = readLine().trim();//.split(" ").map(x=>parseInt(x));

        //console.log("n " +n )
        //console.log("s " + s)

        let max=0;
        for(const char of s)
        {
            let code = char.charCodeAt(0);
            //console.log("code " + code)
            max = Math.max(max,code)
        }
        console.log(max - "a".charCodeAt(0)+1)
    }
}

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

let lines = []

const createReadLine = () => {
  i = 0;
  return () => lines[i++]
}
const int = (num, radix=10) => parseInt(num, radix)

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

rl.on("close", () => {
  const readLine = createReadLine();
  // const alphabet = "abcdefghijklmnopqrstuvwxyz".toUpperCase();
  let t = int(readLine());
  let alphabet = "abcdefghijklmnopqrstuvwxyz"
  while (t--) {
    let ans = 0
    // let al = {}
    let n = int(readLine())
    let str = readLine();
    for (let i = 0; i < n; i++) {
      ans = Math.max(alphabet.indexOf(str[i]), ans)
    }

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

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

let inputString = "";
let currentLine = 0;

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

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.trim().split("\n").map(line =>{
	return line.trim()
});
  main();
});

// ********** Code Start **********
function findLow(str,n){
      let s = 'abcdefghijklmnopqrstuvwxyz'

      let max = 'a';
      for(let i=0;i<n;i++){
          if(str[i]>max){
              max = str[i]
              // console.log(max)
          }
      }
      let res = 0;
      for(let i=0;i<s.length;i++){
          if(s[i]===max){
             res = i+1;
             break;
          }
      }
     console.log(res)
  }
function main() {
  let t = readline();
  t = parseInt(t);
  while(t--){

    let n = readline();
    n = parseInt(n)
    let str = readline();
    findLow(n,str)
  }
}

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main() {
const t = readline();
for (let i = 0; i < t; i++) {
  const chars = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6,
    g: 7,
    h: 8,
    i: 9,
    j: 10,
    k: 11,
    l: 12,
    m: 13,
    n: 14,
    o: 15,
    p: 16,
    q: 17,
    r: 18,
    s: 19,
    t: 20,
    u: 21,
    v: 22,
    w: 23,
  };
  var l = readline();
  var s = readline();
  let maxSize = 0;
  for (let i = 0; i < l; i++) {
    if (chars[s[i]] > maxSize) {
      maxSize = chars[s[i]];
    }
  }
  console.log(maxSize);
}

}

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main() {
const t = 5;
for (let i = 0; i < t; i++) {
  const chars = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
    f: 6,
    g: 7,
    h: 8,
    i: 9,
    j: 10,
    k: 11,
    l: 12,
    m: 13,
    n: 14,
    o: 15,
    p: 16,
    q: 17,
    r: 18,
    s: 19,
    t: 20,
    u: 21,
    v: 22,
    w: 23,
  };
  var l = 4;
  var s = "down";
  let maxSize = 0;
  for (let i = 0; i < l; i++) {
    if (chars[s[i]] > maxSize) {
      maxSize = chars[s[i]];
    }
  }
  console.log(maxSize);
}

}


var readNums = function () {
  return readline().split(" ").map(Number);
};

var n = Number(readline());

for (var i = 0; i < n; i++) {
  var nums = readNums();
  var a = nums[0];
  var b = nums[1];
  if (b % a !== 0) {
    print(0, 0);
    continue;
  }
  var k = b / a;
  print(1, k);
}

T = readline()
while (T--) {
   s = readline().split(' ')
   x = s[0]
   y = s[1]
   a = 0
   b = 0

   if(y%x ==0){
      a = 1
      b = y/x
   }

   print(a, b)
}

var readNums = function () {
    return readline().split(" ").map(Number);
};

var x = Number(readline());

for (var p = 0; p < x; p++) {
    var nums = readNums();
    var a = nums[0];
    var b = nums[1];
    if (b % a !== 0) {
        print(0, 0);
        continue;
    }
    var q = b / a;
    print(1, q);
}

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

function Main(){
    // input in nodeJs
	var t = nextInt();
	while(hasNext()){
        var x = nextInt();
		var y = nextInt();
        let c = y/x;
        // console.log({c})
        if (c < 1 || !Number.isInteger(c)) {
            myout('0 0');
            continue;
        }

        if (c === 1) {
            myout('1 1');
            continue
        }

        for (let i = 2; i <= c; i++) {
            const a = Math.log(c)/Math.log(i);
            // console.log({i, a, c})
            if (Number.isInteger(a)) {
                myout(`${a} ${i}`);
                break;
            }
        }

	}
}

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

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

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

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (x, y)=>{
    if (y % x !== 0 || x > y) return '0 0';
    if (y === x) return '1 1';
    let d = y / x;
    let dd = d;

    for (let i = 2; i <= d; i++) {
        let td = d;
        let count = 0;
        while (td % i === 0) {
            count++;
            td = td / i;
        }

        if (td === 1 && count > 0) {
            return `${count} ${i}`;
        }
    }

    return '0 0';
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let [x, y] = ra();
        console.log(`${calc(x, y)}`);
    }
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}
var T = readline();

for(var q=1;q<=T;q++) {
  var [x, y] = readline().split(' ').map(w => parseInt(w));
  var r = y/x;
  var ans = -1;
  if(r > 0) {
    for(var a=1;a<=10;a++) {
      for(var b=1;b<=100;b++) {
        var pow = Math.pow(b,a);
        if(pow > 1000000000) continue;
        if(pow == r) {
          ans = [a, b];
          break;
        }
      }
    }
  }
  if(ans == -1) ans = [0, 0];
  console.log(ans.join(' '));
}

'use-strict'

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

let data = '';
let currentLine = 0;

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

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

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const [x,y] = get_ints();

        const res = MY_FUNC(x,y);

        console.log(res[0],res[1])
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function MY_FUNC(x,y){
    if(y % x !== 0) return [0,0];
    return [1, y/x]
}

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    let line=buf.split('\n');
    let t=parseInt(line[0]);
    for(let i=1;i<=t;i++)
    {
        let [x,y]=line[i].split(" ").map(x=>{return parseInt(x)});
        // console.log(x,y);
        if(y%x==0)
        {
            let ans=1+' '+y/x;
            console.log(ans);
        }
        else
        {
            let ans=0+' '+0;
            console.log(ans);
        }
    }
})

'use strict';

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(s => s.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++) {
        let [x, y] = readline().split(' ').map(Number);
        if (y % x !== 0) {
            output('0 0');
        } else {
            output(`1 ${y/x}`);
        }
    }
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
	var t = lines[0];
	for(i = 1; i <= t; i++){
	    var a = lines[i].split(' ').map(Number);
	    var x = a[0], y = a[1];
	    if(y % x){
	        console.log(0, 0);
	        continue;
	    }
	    y /= x;
	    console.log(1, y);
	}
});

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var x = nextInt();
		var y = nextInt();
		if(x == y){
			myout("1 1");
			continue;
		}
		var ok = "0 0";
		for(var i = 2; i <= 100; i++){
			var now = x;
			var c = 0;
			while(now < y){
				now *= i;
				c++;
				if(now == y){
					ok = c + " " + i;
				}
			}
		}
		myout(ok);
	}
}

/**
 * Author : Fazlul Hoque
 * Node.js version : 12.16.3
 * command : node fileName.js <input.txt >output.txt
 */
"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");
let inputString = ""; //An array of  raw inputs (includes 'n,\r , not usable. need to process before use)
let currentLine = 0; //input sequence controller variable.

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main(); // after input
});

/********** Utility Functions Start **********/
/**
 *  read row Input
 * @returns string
 */
function _readRawLine() {
    return inputString[currentLine++];
}
function readLine(){
    // return _readRawLine().replace(/\s+$/g, '');
    return _readRawLine().replace('\r', '');
}

function print(x) {
    console.log(x);
}

function readSingleInt() {
    const p = readLine();
    return parseInt(p);
}

function readIntArray() {
    return readLine().split(" ").map((v) => parseInt(v));
}

function readArray() {
    return readLine().split(" ");
}

function int(n) {
    return parseInt(n);
}
/********** Utility Functions End **********/
/**
 * Don't Touch this fucntion at all , unless you know what are you doing!
 */
function main() {
    solve();
}

// ********** actual Code Starts from here **********

function solve() {
    let n = readSingleInt();
    while(n--)
    {
        let [x,y] = readIntArray();
        let k =parseInt((y/x));
        let n = k*x;
        if(y==n){
            console.log(1,k);

        }else{
            console.log("0 0");
        }

    }

}

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(x, y) {
  if (y % x !== 0) {
    console.log('0 0');
  } else {
    console.log(`1 ${y / x}`);
  }
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const [n, m] = (await read()).split(' ').map(Number);
    solve(n, m);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const lines = []
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
rl.on('line', line => {
    lines.push(line);
});
rl.on('close', main)
let rli = 0;
function readline() {
    return lines[rli++];
}
const L = process.env.DEBUG ? console.log : ()=>{};

const pcalc = function(){
  print(calc.apply(null, arguments)); }

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

// SOLUTION

const calc = (x, y)=>{
  for (let b=1; b<=100; b++){
    let tmp = x*b;
    let a = 1;
    while (tmp<y && tmp*b!=tmp){
      tmp = tmp * b;
      a++;
    }
    if (tmp==y)
      return `${a} ${b}`;
  }
  return `0 0`
};

function main() {
    let T = +readline()
    while (T--){
      let [x, y] = ra();
      L('Ans:');
      pcalc(x, y);
    }
}

const readline = require('readline')

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

function solve(x, y) {
    if (y % x) return [0, 0]
    return [1, y / x]
}

var tests = parseInt(readline());
    var x, y;
    for (var t=0; t < tests; t++) {
        var xy = readline().split(' ').map(x=>parseInt(x));
        x = xy[0];
        y = xy[1];
        var a = 0, b = 0;
        if (y % x == 0) {
            a = 1;
            b = y / x;
        }

        print(a + ' ' + b);
    }

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

function Main(){
    // input in nodeJs
	var t = nextInt();
	while(hasNext()){
        var x = nextInt();
		var y = nextInt();
        let c = y/x;
        // console.log({c})
        if (c < 1 || !Number.isInteger(c)) {
            myout('0 0');
            continue;
        }

        if (c === 1) {
            myout('1 1');
            continue
        }

        for (let i = 2; i <= c; i++) {
            const a = Math.log(c)/Math.log(i);
            // console.log({i, a, c})
            if (Number.isInteger(a)) {
                myout(`${a} ${i}`);
                continue;
            }
        }

	}
}

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

function Main(){
    // input in nodeJs
	var t = nextInt();
	while(hasNext()){
        var x = nextInt();
		var y = nextInt();
        let c = y/x;
        // console.log({c})
        if (c < 1 || !Number.isInteger(c)) {
            myout('0 0');
            continue;
        }

        if (c === 1) {
            myout('1 1');
            continue
        }

        for (let i = 2; i <= c; i++) {
            const a = Math.log(c)/Math.log(i);
            console.log({i, a, c})
            if (Number.isInteger(a)) {
                myout(`${a} ${i}`);
                continue;
            }
        }

	}
}

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

function Main(){
    // input in nodeJs
	var t = nextInt();
	while(hasNext()){
        var x = nextInt();
		var y = nextInt();
        let c = y/x;
        // console.log({c})
        if (c < 1 || !Number.isInteger(c)) {
            myout('0 0');
            continue;
        }

        if (c === 1) {
            myout('1 1');
            continue
        }

        for (let i = 2; i <= Math.sqrt(c); i++) {
            const a = Math.log(c)/Math.log(i);
            // console.log({i, a, c})
            if (Number.isInteger(a)) {
                myout(`${a} ${i}`);
                continue;
            }
        }

	}
}

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

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

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

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (x, y)=>{
    if (y % x !== 0 || x > y) return '0 0';
    if (y === x) return '1 1';
    let d = Math.round(y / x);
    let dd = d;

    let divs = {};
    for (let i = 2; i <= d; i++) {
        while (d % i === 0) {
            divs[i] = (divs[i] || 0) + 1;
            d = Math.round(d / i);
        }
    }
    let keys = Array.from(Object.keys(divs));
    for (let i = 0; i < keys.length; i++) {
        let a = divs[keys[i]];
        let b = keys[i];
        if (Math.pow(b, a) === dd) {
            return `${a} ${b}`;
        }
    }

    return '0 0';
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let [x, y] = ra();
        console.log(`${calc(x, y)}`);
    }
}

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

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

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

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (x, y)=>{
    if (y % x !== 0 || x > y) return '0 0';
    if (y === x) return '1 1';
    let d = Math.round(y / x);

    let divs = {};
    for (let i = 2; i <= d; i++) {
        while (d % i === 0) {
            divs[i] = (divs[i] || 0) + 1;
            d = Math.round(d / i);
        }
    }
    let keys = Array.from(Object.keys(divs));
    if (keys.length !== 1) return '0 0';
    return `${divs[keys[0]]} ${keys[0]}`;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let [x, y] = ra();
        console.log(`${calc(x, y)}`);
    }
}

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

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

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

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (x, y)=>{
    if (y % x !== 0) return '0 0';
    if (y === x) return '1 1';
    let d = Math.round(y / x);

    let divs = {};
    for (let i = 2; i <= d; i++) {
        while (d % i === 0) {
            divs[i] = (divs[i] || 0) + 1;
            d = Math.round(d / i);
        }
    }
    let keys = Array.from(Object.keys(divs));
    if (keys.length !== 1) return '0 0';
    return `${divs[keys[0]]} ${keys[0]}`;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let [x, y] = ra();
        console.log(`${calc(x, y)}`);
    }
}

'use-strict'

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

let data = '';
let currentLine = 0;

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

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

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const [x,y] = get_ints();

        const res = MY_FUNC(x,y);

        console.log(res)
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function MY_FUNC(x,y){
    if(y % x !== 0) return [0,0];
    return [y/x, 1]
}

var readNums = function () {
  return readline().split(" ").map(parseInt);
};

var n = parseInt(readline());

for (var i = 0; i < n; i++) {
  var nums = readNums();
  var a = nums[0];
  var b = nums[1];
  if (b % a !== 0) {
    print(0, 0);
    continue;
  }
  var k = b / a;
  print(1, k);
}


(function main(){
    http://codeforces.com/problemset/problem/554/B

    var numeroLineas = readline();
    var lineas = [];

    for (var i = 0; i < numeroLineas; i++) {
        lineas.push(readline());
    }

    lineas.sort();

    var maxLineasRepetidas = 0;
    var repeticionesActuales = 0;
    var lineaAnterior = "";
    for (var i = 0; i < numeroLineas; i++) {
        if(lineas[i] != lineaAnterior){
            lineaAnterior = lineas[i];
            if (repeticionesActuales > maxLineasRepetidas){
                maxLineasRepetidas = repeticionesActuales;
            }
            repeticionesActuales = 1;
        }else{
            repeticionesActuales++;
        }
    }
    if (repeticionesActuales > maxLineasRepetidas){
        maxLineasRepetidas = repeticionesActuales;
    }
    write(maxLineasRepetidas);
})();

function ProblemSolver() {
    this.HAS_TEST_CASES = false ;
    this.INPUT_FILE_NAME = "sample.in" ;
    this.OUTPUT_FILE_NAME = "sample.out" ;
    this.DO_OUTPUT_TO_FILE = false ;
    this.CLEAR_ARRAY_PER_CASE = false ;

    this.solveCase = function() {
        var res , i , j , fl , cn , a , b , c , k ;
        res = 0 ;
        for( i = 0 ; i < this.n ; i++ ) {
        	this.brr = [] ;
        	for( j = 0 ; j < this.n ; j++ ) {
        		this.brr.push( [] ) ;
        		for( k = 0 ; k < this.n ; k++ ) {
        			this.brr[ j ].push( this.arr[ j ][ k ] ) ;
        		}
        	}
        	for( j = 0 ; j < this.n ; j++ ) {
        		if( this.brr[ i ][ j ] == 1 ) {
        			for( k = 0 ; k < this.n ; k++ ) {
        				if( this.brr[ k ][ j ] == 1 ) {
        					this.brr[ k ][ j ] = 0 ;
        				}
        				else {
        					this.brr[ k ][ j ] = 1 ;
        				}
        			}
        		}
        	}
        	b = 0 ;
        	for( j = 0 ; j < this.n ; j++ ) {
        		a = 1 ;
        		for( k = 0 ; k < this.n ; k++ ) {
        			if( this.brr[ j ][ k ] == 1 ) {
        				a = 0 ;
        				break ;
        			}
        		}
        		if( a == 1 ) {
        			b++ ;
        		}
        	}
        	res = Math.max( res , b ) ;
        }
        print( res ) ;
    } ;

    this.init = function() {
        this.lim1 = 100010 ;
        this.lim2 = 110 ;
        this.cc = 1 ;
        this.ind = 1 ;
        this.n = 0 ;
        this.cn = 0 ;
        this.declareAndFillArrays() ;
    } ;

    this.getInput = function( irObj ) {
        var hasMoreInput , i , j , str ;
        hasMoreInput = true ;
        try {
            this.n = irObj.nextInt() ;
            this.arr = [] ;
            for( i = 0 ; i < this.n ; i++ ) {
            	str = irObj.nextString() ;
            	this.arr.push( [] ) ;
            	for( j = 0 ; j < this.n ; j++ ) {
            		this.arr[ i ].push( str.charCodeAt( j ) - '0'.charCodeAt( 0 ) ) ;
            	}
            }
        }
        catch( ex ) {
            hasMoreInput = false ;
        }
        return hasMoreInput ;
    } ;

    this.clearArraysPerCase = function() {
        var i ;
        this.arr = new Array() ;
        this.adjList = new Array() ;
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.arr.push( 0 ) ;
            this.adjList.push( new Array() ) ;
        }
    } ;

    this.clearPerCase = function() {
        this.cn = 0 ;
        this.cc++ ;
        if( this.CLEAR_ARRAY_PER_CASE == true ) {
            this.clearArraysPerCase() ;
        }
    } ;

    this.declareAndFillArrays = function() {
        var i , j ;
        this.srr = new Array() ;
        this.vis = new Array() ;
        this.arr = new Array() ;
        this.brr = new Array() ;
        this.memo = new Array() ;
        this.done = new Array() ;
        this.adjList = new Array() ;
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.srr.push( '' ) ;
            this.vis.push( 0 ) ;
            this.arr.push( 0 ) ;
            this.brr.push( 0 ) ;
            this.adjList.push( new Array() ) ;
        }
        for( i = 0 ; i < this.lim2 ; i++ ) {
            this.memo.push( new Array() ) ;
            this.done.push( new Array() ) ;
            for( j = 0 ; j < this.lim2 ; j++ ) {
                this.memo[ i ].push( -1 ) ;
                this.done[ i ].push( 0 ) ;
            }
        }
    } ;

    this.init() ;
}

function InputReader() {
    var self = this ;
    this.allLines = new Array() ;
    this.currrentLineNumber = 0 ;
    this.currrentCharacterIndex = 0 ;
    this.callBackFunction = null ;
    this.parentContext = null ;

    this.readAllLines = function() {
        var singleLine ;
        while( true ) {
            try {
                singleLine = readline() ;
                if( singleLine == null ) {
                    break ;
                }
            }
            catch( ex ) {
                break ;
            }
            this.allLines.push( singleLine ) ;
        }
    } ;

    this.readAllLinesFromRhino = function() {
        var brObj , line ;
        importPackage( java.io ) ;
        importPackage( java.lang ) ;
        brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;
        this.allLines = [] ;
        while( true ) {
            line = brObj.readLine() ;
            if( line == null ) {
                break;
            }
            this.allLines.push( line ) ;
        }
    } ;

    this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {
        self.chunkData += chunk ;
    } ;

    this.readEndFromNodeJsJudgeServer = function() {
        self.parseRawData( self.chunkData ) ;
        self.parentContext.runCases() ;
    } ;

    this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {
        this.parentContext = parentContext ;
        process.stdin.resume() ;
        process.stdin.setEncoding( 'utf8' ) ;
        this.chunkData = '' ;
        process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;
        process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;
    } ;

    this.parseRawData = function( data ) {
        var len , i , currentString ;
        len = data.length ;
        currentString = '' ;
        this.allLines = [] ;
        for( i = 0 ; i < len ; i++ ) {
            if( data[ i ] == '\r' ) {
            }
            else if( data[ i ] == '\n' ) {
                this.allLines.push( currentString ) ;
                currentString = '' ;
            }
            else {
                currentString += data[ i ] ;
            }
        }
        if( currentString != '' ) {
            this.allLines.push( currentString ) ;
        }
    } ;

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData ;
        fsObj = require( 'fs' ) ;
        currentDirectory = __dirname ;
        if( currentDirectory.indexOf( 'D:' ) != -1 ) {
            //on windows
            inputFilePath = currentDirectory + '\\' + inputFileName ;
        }
        else {
            //on linux
            inputFilePath = currentDirectory + '/' + inputFileName ;
        }
        rawData = fsObj.readFileSync( inputFilePath , "utf8" ) ;
        this.parseRawData( rawData ) ;
    } ;

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx ;
        if( flag == 0 ) {
            if( this.currrentCharacterIndex != 0 ) {
                this.currrentLineNumber++ ;
                this.currrentCharacterIndex = 0 ;
            }
            res = '' ;
            len = this.allLines[ this.currrentLineNumber ].length ;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
            }
            this.currrentLineNumber++ ;
            this.currrentCharacterIndex = 0 ;
            return res ;
        }
        while( true ) {
            if( this.currrentLineNumber >= this.allLines.length ) {
                throw new Error( 'No more tokens available!' ) ;
            }
            startIdx = -1 ;
            len = this.allLines[ this.currrentLineNumber ].length ;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {
                    startIdx = i ;
                    break ;
                }
            }
            if( startIdx == -1 ) {
                this.currrentLineNumber++ ;
                this.currrentCharacterIndex = 0 ;
                continue ;
            }
            res = '' ;
            endIdx = len - 1 ;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i ;
                    break ;
                }
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {
                    res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;
                }
                else {
                    res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
                }
            }
            this.currrentCharacterIndex = endIdx ;
            if( endIdx == len - 1 ) {
                this.currrentLineNumber++ ;
                this.currrentCharacterIndex = 0 ;
            }
            return res ;
        }
    } ;

    this.nextInt = function() {
        return parseInt( this.next( 1 ) ) ;
    } ;

    this.nextDouble = function() {
        return parseFloat( this.next( 1 ) ) ;
    } ;

    this.nextString = function() {
        return this.next( 1 ) ;
    } ;

    this.nextLine = function() {
        return this.next( 0 ) ;
    } ;
}

function FileOutputHandler() {
    this.resultantStringArray = new Array() ;

    this.addNewLine = function( newString ) {
        this.resultantStringArray.push( newString ) ;
    } ;

    this.clearPercase = function() {
        this.resultantStringArray = new Array() ;
    } ;

    this.flushOutOutputToFile = function( outputFileName ) {
        var i , sz , res , currentDirectory , fsObj , outputFilePath ;
        res = '' ;
        sz = this.resultantStringArray.length ;
        for( i = 0 ; i < sz ; i++ ) {
            if( i != 0 ) {
                res += '\n' ;
            }
            res += this.resultantStringArray[ i ] ;
        }
        fsObj = require( 'fs' ) ;
        currentDirectory = __dirname ;
        if( currentDirectory.indexOf( 'D:' ) != -1 ) {
            //on windows
            outputFilePath = currentDirectory + '\\' + outputFileName ;
        }
        else {
            //on linux
            outputFilePath = currentDirectory + '/' + outputFileName ;
        }
        fsObj.writeFileSync( outputFilePath , res ) ;
        this.clearPercase() ;
    } ;
}

function CodeExecutioner() {
    this.irObj = new InputReader() ;
    this.psObj = new ProblemSolver() ;
    this.fohObj = new FileOutputHandler() ;

    this.runCases = function() {
        var testCases , hasMoreTestCases , i ;
        if( this.psObj.HAS_TEST_CASES == true ) {
            testCases = this.irObj.nextInt() ;
            for( i = 0 ; i < testCases ; i++ ) {
                this.psObj.clearPerCase() ;
                this.psObj.getInput( this.irObj ) ;
                this.psObj.solveCase() ;
            }
        }
        else {
            while( true ) {
                this.psObj.clearPerCase() ;
                hasMoreTestCases = this.psObj.getInput( this.irObj ) ;
                if( hasMoreTestCases == false ) {
                    break;
                }
                this.psObj.solveCase() ;
            }
        }
        if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
            this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME ) ;
        }
    } ;

    this.detectEnvironmentType = function() {
        var environmentType = null ;
        try {
            if( importPackage != null ) {
                environmentType = 'rhino' ;
            }
        }
        catch( ex1 ) {
            try {
                //for nodejs local server check
                if( __dirname != null && ( __dirname.indexOf( 'D:') != -1 || __dirname.indexOf( '/media/') != -1 ) ) {
                    environmentType = 'local-node-js' ;
                }
                else {
                    environmentType = 'server-node-js' ;
                }
            }
            catch( ex2 ) {
                try {
                    if( readline == null || typeof( readline ) != 'function' ) {
                        environmentType = 'server-node-js' ;
                    }
                    else {
                        try {
                            if( Map != null ) {
                                environmentType = 'spider-monkey' ;
                            }
                            else {
                                environmentType = 'javascript-v8' ;
                            }
                        }
                        catch( ex3 ) {
                            environmentType = 'javascript-v8' ;
                        }
                    }
                }
                catch( ex3 ) {
                    environmentType = 'server-node-js' ;
                }
            }
        }
        return environmentType ;
    } ;

    this.configureStreamsAndReadInput = function() {
        var localContext , isNodeJsJudgeServer , environmentType ;
        isNodeJsJudgeServer = false ;
        environmentType = this.detectEnvironmentType() ;
        if( environmentType == 'local-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log ;
                }
            }
            catch( ex ) {
                print = console.log ;
            }
            if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
                localContext = this.fohObj ;
                print = function() {
                    localContext.addNewLine.apply( localContext , arguments ) ;
                }
            }
            this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME ) ;
            this.runCases() ;
        }
        else if( environmentType == 'server-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log ;
                }
            }
            catch( ex ) {
                print = console.log ;
            }
            this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;
        }
        else if( environmentType == 'javascript-v8' ) {
            this.irObj.readAllLines() ;
            this.runCases() ;
        }
        else if( environmentType == 'rhino' ) {
            this.irObj.readAllLinesFromRhino() ;
            this.runCases() ;
        }
        else if( environmentType == 'spider-monkey' ) {
            this.irObj.readAllLines() ;
            this.runCases() ;
        }
    } ;

    this.configureStreamsAndReadInput() ;
}

new CodeExecutioner() ;

(function main(){
    http://codeforces.com/problemset/problem/554/B

    var numeroLineas = readline();
    var lineas = [];

    for (var i = 0; i < numeroLineas; i++) {
        lineas.push(readline());
    }

    lineas.sort();

    var maxLineasRepetidas = 0;
    var repeticionesActuales = 0;
    var lineaAnterior = "";
    for (var i = 0; i < numeroLineas; i++) {
        if(lineas[i] != lineaAnterior){
            lineaAnterior = lineas[i];
            if (repeticionesActuales > maxLineasRepetidas){
                maxLineasRepetidas = repeticionesActuales;
            }
            repeticionesActuales = 0;
        }else{
            repeticionesActuales++;
        }
    }

    write(maxLineasRepetidas);
})();