const readline = require('readline');

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

rl.on('line', input => {
  rl.on('line', input2 => {
    console.log(min(input2.split(' ').map(n => parseInt(n))));
    process.exit();
  });
});

const min = input => {
  const min = Math.min(...input);
  const max = Math.max(...input);
  let iMin = input.lastIndexOf(min);
  let iMax = input.findIndex(e => e == max);
  let secs = 0;
  let temp = 0;
  const length = input.length - 1;

  return iMin > iMax ? length - iMin + iMax : length - 1 - iMin + iMax;

  // while(input[input.length-1] !== min) {
  //   if(input[iMin+1] !== min) {
  //     temp = input[iMin+1];
  //     input[iMin+1] = input[iMin];
  //     input[iMin] = temp;
  //     secs++;
  //   }
  //   iMin++;
  // }

  // while(input[0] !== max) {
  //   if(input[iMax-1] !== max) {
  //     temp = input[iMax-1];
  //     input[iMax-1] = input[iMax];
  //     input[iMax] = temp;
  //     secs++;
  //   }
  //   iMax--;
  // }

  // return secs;
}

var n=+readline();
var a=readline().split(' ').map(function(v){return+v;});
var min=Math.min.apply(null, a);
var max=Math.max.apply(null, a);
var minIndex = a.lastIndexOf(min);
a.splice(minIndex,1);
a.push(min);
var maxIndex = a.indexOf(max);
print( n-minIndex-1+maxIndex );

var n = +readline(), line = readline().split(" "), sorted = [], cmax, cmin, buf;
line.forEach(function(a){
	sorted.push(+a);
})
sorted.sort(function(a,b){return a-b});

cmin = line.lastIndexOf(sorted[0].toString(10));
cmax = line.indexOf(sorted[n-1].toString(10));

for(i = 1;  ; i++){
	if( cmax > 0 ){
		buf = line[cmax-1];
		line[cmax-1] = line[cmax];
		line[cmax] = buf;
		cmin = line.lastIndexOf(sorted[0].toString(10));
		cmax = line.indexOf(sorted[n-1].toString(10));
	}
	else if( cmin < n-1 ){
		buf = line[cmin+1];
		line[cmin+1] = line[cmin];
		line[cmin] = buf;
		cmin = line.lastIndexOf(sorted[0].toString(10));
		cmax = line.indexOf(sorted[n-1].toString(10));
	}
	if( (cmax == 0) && (cmin == n-1) ){
		write( (buf != undefined) ? i : i-1 );
		break;
	}
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  const len = +readLine();
  const arr = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  let [minIndex, maxIndex] = [-1, -1];
  let [min, max] = [Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER];

  for (let i = 0; i < len; i++) {
    if (arr[i] > max) {
      max = arr[i];
      maxIndex = i;
    }
    if (arr[i] <= min) {
      min = arr[i];
      minIndex = i;
    }
  }
  const moves = maxIndex + (len - 1 - minIndex);
  if (moves > len - 2) {
    console.log(moves - 1);
  } else {
    console.log(moves);
  }
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error("\n");
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw "ArrayIndexOutOfBoundsException ‚There is no more input";}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var list = nextIntArray();
  var min = 101;
  var max = 0;
  var minIndex = -1;
  var maxIndex = -1;
  for(var i = 0; i < N; i++){
    if(min >= list[i]){
      min = list[i];
      minIndex = i;
    }
  }
  for(var i = N - 1; i >= 0; i--){
    if(max <= list[i]){
      max = list[i];
      maxIndex = i;
    }
  }
  if(maxIndex > minIndex){
    myout(maxIndex + (N - minIndex - 1) - 1);
  }else{
    myout(maxIndex + (N - minIndex - 1));
  }
}

const readline = require('readline');

let inputs = [];

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

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    let arr = inputs[1].split(' ').map(num => parseInt(num));
    let Pmax = arr.indexOf(Math.max(...arr));
    let Pmin = 0;
    let limiter = 0;
    const shortestHeight = Math.min(...arr);

    for (let i = arr.length; i > 0; i--) {
        if (arr[i] == shortestHeight && limiter == 0) {
            Pmin = i;
            limiter++
        }
    }

    let minSeconds;

    Pmin = parseInt(Pmin)
    Pmax = parseInt(Pmax)

    if (Pmin < Pmax) {
        minSeconds = Pmax + (arr.length - 1 - Pmin) - 1;
    } else {
        minSeconds = Pmax + (arr.length - 1 - Pmin);
    }

    console.log(minSeconds);

})

const readline = require('readline');

let inputs = [];

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

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    let arr = inputs[1].split(' ');
    let Pmax = arr.indexOf(Math.max(...arr).toString());
    let Pmin = 0;
    let limiter = 0;
    const shortestHeight = Math.min(...arr).toString();

    for (let i = arr.length; i > 0; i--) {
        if (arr[i] == shortestHeight && limiter == 0) {
            Pmin = i;
            limiter++
        }
    }

    let minSeconds;

    Pmin = parseInt(Pmin)
    Pmax = parseInt(Pmax)

    if (Pmin < Pmax) {
        minSeconds = Pmax + (arr.length - Pmin) - 2;
    } else {
        minSeconds = Pmax + (arr.length - 1 - Pmin);
    }

    console.log(minSeconds);

})

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

const input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
    const a = input[1].split(' ').map(x => +x);
    let imax = 0;
    let imin = 0;
    for (let i = 1; i < a.length; i++) {
        if (a[i] > a[imax]) {
            imax = i;
        }
        else if (a[i] <= a[imin]) {
            imin = i;
        }
    }
    const maxSteps = imax;
    const minSteps = a.length - imin - 1;
    const commonSteps = +(imax > imin);
    console.log(maxSteps + minSteps - commonSteps);
});

//Arrival of the General

const {EOL} = require('os');

let inp = '';

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

process.stdin.on('end', () => {
    let lines = inp.split(EOL)[1].split(' ').map(c => +c);

    let maxi = 0, mini = 0;
    for(let i = 0; i < lines.length; i++)  {
    	if(lines[i] <= lines[mini])  {
    		mini = i;
    	}
    	if(lines[i] > lines[maxi])  {
    		maxi = i;
    	}
    }

    if(maxi > mini)  {
    	process.stdout.write((maxi + lines.length - mini - 2) + '');
    }  else  {
    	process.stdout.write((maxi + lines.length - mini - 1) + '');
    }

    return;
});

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input))+1;
var max_index = input.indexOf(Math.max(...input))+1;
var output;
if(min_index < max_index){
    output = input.length-min_index+max_index-2;
}else{
    output = input.length-min_index+max_index-1;
}
print(output);

;(function () {

	var s = (readline(), readline()).split(' ').map(function (x) {return parseInt(x);});

	var max = Math.max.apply(null, s);
	var min = Math.min.apply(null, s);

	for (var i = 0; i < s.length; i++) if (max == s[i]) break;
	for (var j = s.length - 1; j >= 0; j--) if (min == s[j]) break;

	print(i + ( s.length - j - 1 ) - ( i > j));

}).call(this);

'use strict';

let n = parseInt(readline());
let array = readline().split(' ').map(value => parseInt(value));

let max = array[0],
    min = array[0],
    time = 0;

for(let i = 0; i < array.length; i++){
    if (array[i] > max) {
        max = array[i];
    }

    if (array[i] < min) {
        min = array[i];
    }
}

let maxPosition = array.indexOf(max);

for(let i=maxPosition; i > 0; i--) {
    time++;
    let temp = array[i];
    array[i] =  array[i - 1];
    array[i - 1] = temp;
}

let minPosition = array.reverse().indexOf(min);

write(time + minPosition);

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

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

  const arr = d.split(' ').map(Number);
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  const idxMin = arr.lastIndexOf(min);
  const idxMax = arr.indexOf(max);

  ans += idxMax;

  if (idxMin > idxMax) {
    ans += Math.max(arr.length - idxMin - 1, 0);
  }
  else {
    ans += Math.max(arr.length - idxMin - 2, 0);
  }

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

const input = [];

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

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

RL.on('close', () => {
    const nums = input[1].split(' ').map(x => parseInt(x));
    let min = 1000, minIndex = -1;
    let max = 0, maxIndex = -1;
    nums.forEach((x, i) => {
      if (x > max) {max = x; maxIndex = i}
      if (x <= min) {min = x; minIndex = i}
    });

    if (maxIndex < minIndex)
      console.log(maxIndex + nums.length - (minIndex + 1));
    else
      console.log(maxIndex + nums.length - (minIndex + 1) - 1);
});

const readline = require('readline');

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

rl.on('line', input => {
  rl.on('line', input2 => {
    console.log(min(input2.split(' ').map(n => parseInt(n))));
    process.exit();
  });
});

const min = input => {
  const min = Math.min(...input);
  const max = Math.max(...input);
  let iMin = input.lastIndexOf(min);
  let iMax = input.findIndex(e => e == max);
  let secs = 0;
  let temp = 0;

  while(input[input.length-1] !== min) {
    if(input[iMin+1] !== min) {
      temp = input[iMin+1];
      input[iMin+1] = input[iMin];
      input[iMin] = temp;
      secs++;
    }
    iMin++;
  }

  while(input[0] !== max) {
    if(input[iMax-1] !== max) {
      temp = input[iMax-1];
      input[iMax-1] = input[iMax];
      input[iMax] = temp;
      secs++;
    }
    iMax--;
  }

  return secs;
}

var n  = readline();//.split(" ");
var str  = readline().split(" ").map((x)=>+x);
var min = Math.min.apply(this, str); var max = Math.max.apply(this, str);
var MinIndex = str.lastIndexOf(min)+1; var MaxIndex = str.indexOf(max)+1;

print(min==+str[str.length-1]&&max==+str[0]? 0:
MaxIndex>MinIndex? MaxIndex-1+str.length-MinIndex-1:MaxIndex-1+str.length-MinIndex);

var n = parseInt(readline());
var soldiers = readline().split(' ').map(function(num){return parseInt(num)});
var max = Math.max(...soldiers);
var min = Math.min(...soldiers);
var indexOfMax = soldiers.indexOf(max);
var indexOfMin = soldiers.lastIndexOf(min);
var swaps = (n - (indexOfMin  + 1)) + (indexOfMax);
if(indexOfMax > indexOfMin) swaps--;
print(swaps);

var n = Number(readline());
var s = readline().split(' ').map(Number);

var max = Math.max.apply(null, s);
var min = Math.min.apply(null, s);

for (var i = 0; i < n; i++) {
    if (max === s[i]) {
        break;
    }
}
for (var j = n - 1; j >= 0; j--) {
    if (min === s[j]) {
        break;
    }
}

print(i + ( n - j - 1 ) - ( i > j));

var n = parseInt(readline());
var a = readline().split(" ").map(function(x) { return parseInt(x); });
var time = 0;
var min_p = 0;
var min_v = 999;
var max_p = 0;
var max_v = 0;

for (var i = 0; i < a.length; i++){
  if (min_v >= a[i]) {
   min_v = a[i];
   min_p = i;
  }
  if (max_v < a[i]) {
   max_v = a[i];
   max_p = i;
  }
}

if (max_p > min_p) {
	time = max_p + (a.length - 1 - min_p) - 1;
} else {
	time = max_p + (a.length - 1 - min_p);
}

print (time);

var computeSoldiersForGeneral = function(arr)
{
    arr = arr.split(' ');
    var indexMax = 0, indexMin = 0;
    for (var i = 1; i <= arr.length - 1; i++)
    {
        if (+arr[i] > +arr[indexMax]) indexMax = i;
        if (+arr[i] <= +arr[indexMin]) indexMin = i;
    }
    if (indexMax > indexMin) return indexMax + arr.length - indexMin - 2;
    else return indexMax + arr.length - indexMin - 1;
}
var input1 = readline();
var input = readline();
print(computeSoldiersForGeneral(input));

var n = readline();
var soliders = readline().split(" ");

var maxIndex = 0;
var minIndex = 0;
var swapTime = 0;

for(var i = 0; i < n; i++){
	maxIndex = (parseInt(soliders[i]) > parseInt(soliders[maxIndex])) ? i : maxIndex;
	minIndex = (parseInt(soliders[i]) <= parseInt(soliders[minIndex])) ? i : minIndex;
}
if(maxIndex > minIndex)
	swapTime = (parseInt(maxIndex) + (parseInt(n)-1-parseInt(minIndex))-1);
else
	swapTime = parseInt(maxIndex) + (parseInt(n)-1-parseInt(minIndex));
print(swapTime);

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function isPrime(x) {
	let s = Math.sqrt(x);
	let i = 2;
	while (i <= s) {
		if (x % i === 0) {
			return false;
		}
		i++;
	}
	return true;
}

function main() {
	let n = readLine() >> 0;
	let sol = readLine()
		.split(' ')
		.map(x => x >> 0);

	let sc = 0;

	let min = Math.min(...sol);
	let max = Math.max(...sol);
	let posMax = 0,
		posMin = 0;

	sol.forEach((x, i) => {
		if (x === min && i >= posMin) posMin = i + 1;
		if (x === max && posMax === 0) posMax = i + 1;
	});

	sc = n - posMin;
	if (posMax > posMin) sc += posMax - 2;
	else sc += posMax - 1;

	console.log(sc);
}

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

const input = [];
readline.on('line', line => { input.push(line); });

readline.on('close', () => {
    const arr = input[1].split(' ').map(Number);
    let min = 101, max = 0;
    arr.forEach(v => {
        if (v < min) min = v;
        if (v > max) max = v;
    });
    let minpos = -1, maxpos = 101;
    arr.forEach((v, i) => {
        if (v == min && i > minpos) minpos = i;
        if (v == max && i < maxpos) maxpos = i;
    });
    let dist = 0;
    if (minpos < maxpos) dist -= 1;
    dist += arr.length - minpos - 1;
    dist += maxpos;
    console.log(dist);
});

let fs = require('fs');

let txt = fs.readFileSync(0, "utf-8").split("\n").filter(data => data.length > 0);
for (let i = 0; i < txt.length; i += 2) {
    doit(txt[i + 1].split(" ").filter(data => data.length > 0).map(data => data * 1));
}

function doit(tab) {
    let max = tab.indexOf(Math.max(...tab));
    let score = max;
    tab.unshift(tab.splice(max, 1)[0]);
    tab.reverse();
    let min = tab.indexOf(Math.min(...tab));
    score += min;
    console.log(score);

}

// Sample code to perform I/O:

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

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

function main(input) {
    let output = nameLookUp(input);
    process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split('\n');
    let arr = inputs[1].trim().split(' ');
    let max = Math.max(...arr);
    let min = Math.min(...arr);
    let swaps = 0;
    if (arr[0] == max && arr[arr.length - 1] == min) {
        swaps = 0;
    }
    else {
        let minIndex = arr.lastIndexOf(String(min));

        for (let i = minIndex + 1; i < arr.length; i++) {
            if (+arr[minIndex] < +arr[i]) {
                let temp = arr[i];
                arr[i] = arr[minIndex];
                arr[minIndex] = temp;
                minIndex = i;
                swaps++;
            }
        }

        let maxIndex = arr.indexOf(String(max));
        for (let i = maxIndex - 1; i >= 0; i--) {
            if (+arr[maxIndex] > +arr[i]) {
                let temp = arr[i];
                arr[i] = arr[maxIndex];
                arr[maxIndex] = temp;
                maxIndex = i;
                swaps++;
            }
        }
    }

    return swaps.toString();
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    let n = parseInt(readLine());
    let arr = readLine().split(' ').map(value => parseInt(value));
    let idxMax = arr.indexOf(Math.max(...arr));
    let min = Math.min(...arr);
    let idxMin = arr.indexOf(min);
    let arrIdxMin = [];
    while (idxMin != -1) {
        arrIdxMin.push(idxMin);
        idxMin = arr.indexOf(min, idxMin + 1);
    }
    idxMin = arrIdxMin[arrIdxMin.length - 1];
    if (idxMin < idxMax) {
        console.log(idxMax + n - idxMin - 2);
    } else {
        console.log(idxMax + n - idxMin - 1);
    }
}

var n=+readline();
var a=readline().split(' ').map(function(v){return+v;});
var min=a.indexOf( Math.min.apply(null, a) );
var max=a.indexOf( Math.max.apply(null, a) );
var ans=n-min-1+max;
if(max==min) print(0);
else print(min<max?ans-2:ans);

var n = +readline(), line = readline().split(" "), sorted = [], cmax, cmin, buf;
line.forEach(function(a){
	sorted.push(+a);
})
sorted.sort(function(a,b){return a-b});

cmin = line.lastIndexOf(sorted[0].toString(10));
cmax = line.indexOf(sorted[n-1].toString(10));

for(i = 1;  ; i++){
	if( cmax > 0 ){
		buf = line[cmax-1];
		line[cmax-1] = line[cmax];
		line[cmax] = buf;
		cmin = line.lastIndexOf(sorted[0].toString(10));
		cmax = line.indexOf(sorted[n-1].toString(10));
	}
	else if( cmin < n-1 ){
		buf = line[cmin+1];
		line[cmin+1] = line[cmin];
		line[cmin] = buf;
		cmin = line.lastIndexOf(sorted[0].toString(10));
		cmax = line.indexOf(sorted[n-1].toString(10));
	}
	if( (cmax == 0) && (cmin == n-1) ){
		write(i);
		break;
	}
}

var n = +readline(), line = readline().split(" "), sorted = [], cmax, cmin, buf;
line.forEach(function(a){
	sorted.push(+a);
})
sorted.sort(function(a,b){return a-b});

cmin = line.lastIndexOf(sorted[0].toString(10));
cmax = line.indexOf(sorted[n-1].toString(10));

for(i = 1;  ; i++){
	if( cmax > 0 ){
		buf = line[cmax-1];
		line[cmax-1] = line[cmax];
		line[cmax] = buf;
		cmin = line.lastIndexOf(sorted[0].toString(10));
		cmax = line.indexOf(sorted[n-1].toString(10));
		continue;
	}
	else if( cmin < n-1 ){
		buf = line[cmin+1];
		line[cmin+1] = line[cmin];
		line[cmin] = buf;
		cmin = line.lastIndexOf(sorted[0].toString(10));
		cmax = line.indexOf(sorted[n-1].toString(10));
	}
	if( (cmax == 0) && (cmin == n-1) ){
		write(i);
		break;
	}
}

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var temp = input[min_index];
input[min_index] = input[input.length - 1];
input[input.length - 1] = temp;
var max_index = input.indexOf(Math.max(...input));
var output = input.length-min_index+max_index;
print(output);

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var max_index = input.indexOf(Math.max(...input));
print(2*input.length-min_index-max_index-1);

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var max_index = input.indexOf(Math.max(...input));
print(max_index-1+input.length-min_index+1-1);

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var temp = input[min_index];
input[min_index] = input[input.length - 1];
input[input.length - 1] = temp;
var max_index = input.indexOf(Math.max(...input));
var output = ((input.length-1)-min_index)+max_index;
print(output);

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var max_index = input.indexOf(Math.max(...input));
print(2*input.lenth-min_index-max_index-1);

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var max_index = input.indexOf(Math.max(...input));
print(max_index-1+input.length-1-min_index);

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var max_index = input.indexOf(Math.max(...input));
print(max_index+input.length-min_index-1);

var n  = readline();//.split(" ");
var str  = readline().split(" ").map((x)=>+x);
var min = Math.min.apply(this, str); var max = Math.max.apply(this, str);
var MinIndex = str.lastIndexOf(min)+1; var MaxIndex = str.lastIndexOf(max)+1;

print(MaxIndex>MinIndex? MaxIndex-1+str.length-MinIndex-1:MaxIndex-1+str.length-MinIndex);

var n  = readline();//.split(" ");
var str  = "100 95 100 100 88".split(" ").map((x)=>+x);
var min = Math.min.apply(this, str); var max = Math.max.apply(this, str);
var MinIndex = str.lastIndexOf(min)+1; var MaxIndex = str.lastIndexOf(max)+1;

print(MaxIndex>MinIndex? MaxIndex-1+str.length-MinIndex-1:MaxIndex-1+str.length-MinIndex);

var n = readline();
var m = readline().split(" ");
var min = 0; var max = 0;
		for (var i=0; i<+n; i++){
			if (m[i]==Math.min.apply(this,m))//m[i+1]&&min<=m[i+1]){
				min = n-(i+1);
			else if (m[i]==Math.max.apply(this, m))
			max = (i+1)-1;
		}
	print(min+max-1);

var n = readline();
var m = readline().split(" ");
var temp = 0;
var res = 0;
	for (var j=0; j<+2; j++){
		for (var i=0; i<+n; i++){
			if (m[i]<m[i+1]){
				temp = m[i];
				m[i] = m[i+1];
				m[i+1] = temp;
				res++;
			}
		}
	}
	print(res);

var n  = readline();//.split(" ");
var str  = readline().split(" ").map((x)=>+x);
var min = Math.min.apply(this, str); var max = Math.max.apply(this, str);
var MinIndex = str.lastIndexOf(min)+1; var MaxIndex = str.lastIndexOf(max)+1;

print(min==+str[str.length-1]&&max==+str[0]? 0:
MaxIndex>MinIndex? MaxIndex-1+str.length-MinIndex-1:MaxIndex-1+str.length-MinIndex);

var n = readline();
var soliders = readline().split(" ");

var maxIndex = 0;
var minIndex = 0;
var swapTime = 0;

for(var i = 0; i < n; i++){
	maxIndex = (soliders[i] > soliders[maxIndex]) ? i : maxIndex;
	minIndex = (soliders[i] <= soliders[minIndex]) ? i : minIndex;
}

if(maxIndex > minIndex)
	swapTime = (parseInt(maxIndex) + (parseInt(n)-1-parseInt(minIndex))-1);
else
	swapTime = parseInt(maxIndex) + (parseInt(n)-1-parseInt(minIndex));
print(swapTime);

var n = readline();
var soliders = readline().split(" ");

var maxIndex = 0;
var minIndex = 0;
var swapTime = 0;

for(var i = 0; i < n; i++){
	maxIndex = (parseInt(soliders[i]) > parseInt(soliders[maxIndex])) ? i : maxIndex;
	minIndex = (parseInt(soliders[i]) <= parseInt(soliders[minIndex])) ? i : minIndex;
}
print(maxIndex+" "+minIndex);
if(maxIndex > minIndex)
	swapTime = (parseInt(maxIndex) + (parseInt(n)-1-parseInt(minIndex))-1);
else
	swapTime = parseInt(maxIndex) + (parseInt(n)-1-parseInt(minIndex));
print(swapTime);

const readline = require('readline');

let inputs = [];

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

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    let arr = inputs[1].split(' ');
    let Pmax = arr.indexOf(Math.max(...arr).toString());
    let Pmin = 0;
    const shortestHeight = Math.min(...arr).toString();

    for (let i = arr.length; i > 0; i--) {
        if (arr[i] == shortestHeight) {
            Pmin = i;
        }
    }

    let minSeconds;
    Pmin = parseInt(Pmin)
    Pmax = parseInt(Pmax)

    if (Pmin < Pmax) {
        minSeconds = Pmax + (arr.length - Pmin) - 2;
    } else {
        minSeconds = Pmax + (arr.length - 1 - Pmin);
    }

    console.log(minSeconds);

})

const readline = require('readline');

let inputs = [];

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

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    let arr = inputs[1].split(' ');
    const Pmax = arr.indexOf(Math.max(...arr).toString());
    const shortestHeight = Math.min(...arr).toString();
    let Pmin;

    for (let i = arr.length; i > 0; i--) {
        if (arr[i] == shortestHeight) {
            Pmin = i;
        }
    }

    let minSeconds;
    if (parseInt(Pmin) < parseInt(Pmax)) {
        minSeconds = Pmax + (arr.length - Pmin) - 2
    } else {
        minSeconds = Pmax + (arr.length - 1 - Pmin);
    }

    console.log(minSeconds);

})

const readline = require('readline');

let inputs = [];

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

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    let arr = inputs[1].split(' ');
    let Pmax = arr.indexOf(Math.max(...arr).toString());
    let Pmin = 0;
    const shortestHeight = Math.min(...arr).toString();

    for (let i = arr.length; i > 0; i--) {
        if (arr[i] == shortestHeight) {
            Pmin = i;

            let minSeconds;
            Pmin = parseInt(Pmin)
            Pmax = parseInt(Pmax)

            if (Pmin < Pmax) {
                minSeconds = Pmax + (arr.length - Pmin) - 2;
            } else {
                minSeconds = Pmax + (arr.length - 1 - Pmin);
            }

            return console.log(minSeconds);
        }
    }

})

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

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

  const arr = d.split(' ').map(Number);
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  const idxMin = arr.lastIndexOf(min);
  const idxMax = arr.indexOf(max);

  ans += idxMax;

  if (arr.indexOf(min) > arr.indexOf(max)) {
    ans += Math.max(arr.length - idxMin - 1, 0);
  }
  else {
    ans += Math.max(arr.length - idxMin - 2, 0);
  }

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

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

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

  const arr = d.split(' ').map(Number);
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  const ans = Math.max(arr.indexOf(max) - 1, 1) + arr.length - 1 - arr.lastIndexOf(min);

  // console.log(Math.max(arr.indexOf(max) - 1, 0), arr.length - 1 - arr.lastIndexOf(min));

  // let ans = 0;
  // let isSwap = true;

  // while (isSwap) {
  //   isSwap = false;

  //   for (let j = 0; j < arr.length - 1; j++) {
  //     if (arr[j] < arr[j + 1]) {
  //       const temp = arr[j];
  //       arr[j] = arr[j + 1];
  //       arr[j + 1] = temp;
  //       ans++;
  //       isSwap = true;
  //     }
  //   }
  // }

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

const readline = require('readline');

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

rl.on('line', input => {
  rl.on('line', input2 => {
    console.log(min(input2.split(' ').map(n => parseInt(n))));
    process.exit();
  });
});

const min = input => {
  const min = Math.min(...input);
  const max = Math.max(...input);
  let iMin = input.findIndex(e => e == min);
  let iMax = input.findIndex(e => e == max);
  let secs = 0;
  let temp = 0;

  while(input[input.length-1] !== min) {
    if(input[iMin+1] !== min) {
      temp = input[iMin+1];
      input[iMin+1] = input[iMin];
      input[iMin] = temp;
      secs++;
    }
    iMin++;
  }

  while(input[0] !== max) {
    if(input[iMax-1] !== max) {
      temp = input[iMax-1];
      input[iMax-1] = input[iMax];
      input[iMax] = temp;
      secs++;
    }
    iMax--;
  }

  return secs;
}

const readline = require('readline');

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

rl.on('line', input => {
  rl.on('line', input2 => {
    console.log(min(input2.split(' ').map(n => parseInt(n))));
    process.exit();
  });
});

const min = input => {
  const iMin = input.findIndex(e => e == Math.min(...input));
  const iMax = input.findIndex(e => e == Math.max(...input));

  return iMin > iMax ? input.length - 1 - iMin + iMax : input.length - 2 - iMin + iMax;
}

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function isPrime(x) {
	let s = Math.sqrt(x);
	let i = 2;
	while (i <= s) {
		if (x % i === 0) {
			return false;
		}
		i++;
	}
	return true;
}

function main() {
	let n = readLine() >> 0;
	let sol = readLine()
		.split(' ')
		.map(x => x >> 0);

	let sc = 0;

	let min = Math.min(...sol);
	let max = Math.max(...sol);
	let posMax = 0,
		posMin = 0;

	sol.forEach((x, i) => {
		if (x === min && i >= posMin) posMin = i;
		if (x === max) posMax = i;
	});

	sc = n - posMin - 1;
	if (posMax > posMin) sc += posMax - 1;
	else sc += posMax;

	console.log(sc);
}

// Sample code to perform I/O:

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

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

function main(input) {
    let output = nameLookUp(input);
    process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split('\n');
    let arr = inputs[1].trim().split(' ');
    let max = Math.max(...arr);
    let min = Math.min(...arr);
    let swaps = 0;
    if (arr[0] == max && arr[arr.length - 1] == min) {
        swaps = 0;
    }
    else {
        let minIndex = arr.lastIndexOf(String(min));

        for (let i = minIndex + 1; i < arr.length; i++) {
            if (arr[minIndex] < arr[i]) {
                let temp = arr[i];
                arr[i] = arr[minIndex];
                arr[minIndex] = temp;
                minIndex = i;
                swaps++;
            }
        }

        let maxIndex = arr.indexOf(String(max));
        for (let i = maxIndex - 1; i >= 0; i--) {
            if (arr[maxIndex] > arr[i]) {
                let temp = arr[i];
                arr[i] = arr[maxIndex];
                arr[maxIndex] = temp;
                maxIndex = i;
                swaps++;
            }
        }
    }

    return swaps.toString();
}

// Sample code to perform I/O:

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

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

function main(input) {
    let output = nameLookUp(input);
    process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split('\n');
    let arr = inputs[1].trim().split(' ');
    let swaps = 0;
    for (let i = 1; i < arr.length; i++) {
        let min = arr[i];
        let j = i - 1;
        while (j >= 0 && arr[j] < min) {
            arr[j + 1] = arr[j];
            j--;
            swaps++;
        }
        arr[j + 1] = min;
    }
    swaps = Math.abs(+inputs[0] - swaps);
    return swaps.toString();
}


// Classes to be taken on monday.
const classCount = 7;
// Getting problem data from codeforces.
var groupCount = parseInt(readline()),
  groupSchedules = [];
for(var j = 0;j<groupCount;++j){
  groupSchedules.push(readline());
}
// Computing required number of rooms.
var roomCount = 0,oneCounts = 0;
for(var j = 0; j<classCount;++j){
  for(var i = 0;i<groupCount;++i){
    groupSchedules[i][j] == '1'?
      oneCounts++:undefined;
  }
  roomCount = Math.max(roomCount,oneCounts);
    oneCounts = 0;
}
// Solution.
print(roomCount);

var n=parseInt(readline());
var max=0,count=0;
var ar=new Array(n);
var s="";
for(var i=0;i<n;i++){
	ar[i]=readline();
}
for(var y=0;y<7;y++){
	for(var i=0;i<n;i++){
		s=ar[i];
		count+=parseInt(s[y]);
	}
	if(count>max){max=count;}
	count=0;
}print(max);

n=+readline()
s=[]
for (var i=0;i<n;i++)
{
    s.push(readline())
}
var res=0;
for (var j=0;j<7;j++)
{
    var kol=0;
    for (var i=0;i<n;i++)
    {
        if (s[i][j]=='1')
        kol++
    }
    if (kol>res){res=kol;}
}
print(res)

n=+readline()
s=[]
for (var i=0;i<n;i++)
{
    s.push(readline())
}
var res=0;
for (var j=0;j<7;j++)
{
    var kol=0;
    for (var i=0;i<n;i++)
    {
        kol+=s[i][j]
    }
    if (kol>res){res=kol;}
}
print(res)

// Classes to be taken on monday.
const classCount = 7;
// Getting problem data from codeforces.
var groupCount = parseInt(readline()),
  groupSchedules = [];
for(var j = 0;j<groupCount;++j){
  groupSchedules.push(readline());
}
// Computing required number of rooms.
var roomCount = -1,oneCounts = 0;
for(var j = 0; j<classCount;++j){
  for(var i = 0;i<groupCount;++i){
    groupSchedules[i][j] == '0'?
      oneCounts++:undefined;
  }
  roomCount = Math.max(roomCount,oneCounts);
    oneCounts = 0;
}
// Solution.
print(roomCount);


'use strict';

function main() {
  let n = 0, x = 0, y = 0, s = '';
  let i = 0, toBeChanged = 0;
  n = parseInt(next()), x = parseInt(next()), y = parseInt(next()), s = next();
  for(i = n-x; i < n; i++) {
    if(i != n-y-1) {
      toBeChanged += s[i] === '1';
    } else {
      toBeChanged += s[i] === '0';
    }
  }
  println(toBeChanged);
}

//process.stdin.resume();
process.stdin.setEncoding('ascii');

let input = "";
process.stdin.on('data', (chunk) => input += chunk);

// next: reads next value from input.
let inputCursor = 0;
let next = () => {
  return inputCursor < input.length ? input[inputCursor++] : '';
};

//print: print one or more space seperated values.
let print = (...data) => {
  for(let i = 0; i < data.length; i++) {
    process.stdout.write('' + data[i] + (i < data.length - 1 ? ' ' : ''));
  }
};

//println: print one or more space seperated values then a line feed.
let println = (...data) => {
  print(...data);
  print('\n');
};

//after the the input is read.
process.stdin.on('end', () => {
    input = input.trim().split(/[\s]+/);
    main();
});

'use strict'

function main() {
  let n, x, y, s;
  n = parseInt(next()), x = parseInt(next()), y = parseInt(next()), s = next();
  let toBeChanged = 0;
  for(let i = n-x; i < n; i++) {
    if(i != n-y-1) {
      toBeChanged += s[i] == '1';
    } else {
      toBeChanged += s[i] == '0';
    }
  }
  println(toBeChanged);
}

//process.stdin.resume();
process.stdin.setEncoding('ascii');

let input = "";
process.stdin.on('data', (chunk) => input += chunk);

// next: reads next value from input.
let inputCursor = 0;
let next = () => {
  return inputCursor < input.length ? input[inputCursor++] : '';
};

//print: print one or more space seperated values.
let print = (...data) => {
  for(let i = 0; i < data.length; i++) {
    process.stdout.write('' + data[i] + (i < data.length - 1 ? ' ' : ''));
  }
};

//println: print one or more space seperated values then a line feed.
let println = (...data) => {
  print(...data);
  print('\n');
};

//after the the input is read.
process.stdin.on('end', () => {
    input = input.trim().split(/[\s]+/);
    main();
});

try {require("codeforces")} catch(e){};

let fs =  require('fs');
let input = (fs.readFileSync2 || fs.readFileSync)(0, 'ascii').split('\n').map(s => s.trim());

let [n, x, y] = input[0].split(" ").map(Number);
let ch = input[1];

ch = ch.substr(-x).split("");
ch.reverse();
console.log(ch.filter(function(ch, index) {return index === y && ch === "0" || index !== y && ch === "1"}).length);

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    }

    var line = read.arrNumber(' ');
    var n = line[0];
    var x = line[1];
    var y = line[2];

    var s = read.arr('');

    var res = 0;
    for(var i = n - 1; i > n - x - 1; i-- ) {
        if(i == n - y - 1) {
            if(s[i] === '0')
                res++
        }
        else {
            if(s[i] === '1') {
                res++;
            }
        }

    }
    print(res);
}());

var input = readline().split(' ').map(Number);
var n, x, y;
n = input.shift();
x = input.shift();
y = input.shift();
var str = readline();
var res = 0;
for(var i = n - 1; i >= n - x; i--){
    if(str[i] == '1' && Math.abs(n - i - 1) != y){
        res++;
    } else if(str[i] == '0' && Math.abs(n - 1 - i) == y)
        res++;
}
print(res);

var input = readline().split(" ").map(Number);
var n = input.shift();
var x = input.shift();
var y = input.shift();
var ch = readline();
ch = ch.substr(-x).split("");
ch.reverse();
write(ch.filter(function(ch, index) {return index === y && ch === "0" || index !== y && ch === "1"}).length);

'use strict'

function main() {
  let n = 0, x = 0, y = 0, s = '';
  let i = 0, toBeChanged = 0;
  n = parseInt(next()), x = parseInt(next()), y = parseInt(next()), s = next();
  for(i = n-x; i < n; i++) {
    if(i != n-y-1) {
      toBeChanged += s[i] === '1';
    } else {
      toBeChanged += s[i] === '0';
    }
  }
  println(toBeChanged);
}

//process.stdin.resume();
process.stdin.setEncoding('ascii');

let input = "";
process.stdin.on('data', (chunk) => input += chunk);

// next: reads next value from input.
let inputCursor = 0;
let next = () => {
  return inputCursor < input.length ? input[inputCursor++] : '';
};

//print: print one or more space seperated values.
let print = (...data) => {
  for(let i = 0; i < data.length; i++) {
    process.stdout.write('' + data[i] + (i < data.length - 1 ? ' ' : ''));
  }
};

//println: print one or more space seperated values then a line feed.
let println = (...data) => {
  print(...data);
  print('\n');
};

//after the the input is read.
process.stdin.on('end', () => {
    input = input.trim().split(/[\s]+/);
    main();
});

'use strict'

function main() {
  let n, x, y, s;
  n = parseInt(next()), x = parseInt(next()), y = parseInt(next()), s = next();
  let toBeChanged = 0;
  for(let i = n-x; i < n; i++) {
    if(i != 11-y-1) {
      toBeChanged += s[i] == '1';
    } else {
      toBeChanged += s[i] == '0';
    }
  }
  println(toBeChanged);
}

//process.stdin.resume();
process.stdin.setEncoding('ascii');

let input = "";
process.stdin.on('data', (chunk) => input += chunk);

// next: reads next value from input.
let inputCursor = 0;
let next = () => {
  return inputCursor < input.length ? input[inputCursor++] : '';
};

//print: print one or more space seperated values.
let print = (...data) => {
  for(let i = 0; i < data.length; i++) {
    process.stdout.write('' + data[i] + (i < data.length - 1 ? ' ' : ''));
  }
};

//println: print one or more space seperated values then a line feed.
let println = (...data) => {
  print(...data);
  print('\n');
};

//after the the input is read.
process.stdin.on('end', () => {
    input = input.trim().split(/[\s]+/);
    main();
});


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

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

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

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], k = data[1],
		childPieces = tokenizeIntegers(readline()),
		used = {}, rows = [];
	for (var i = 0; i < childPieces.length; ++i) {
		used[childPieces[i]] = true;
		rows.push([childPieces[i]]);
	}
	var child = 0, limit = n*k;
	for (var piece = 1; piece <= limit; ++piece) {
		if (!used[piece]) {
			rows[child].push(piece);
			if (rows[child].length == n) {
				++child;
			}
		}
	}
	var lines = [];
	for (var child = 0; child < k; ++child) {
		lines.push(rows[child].join(' '));
	}
	print(lines.join('\n'));
}

main();

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

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

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

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], k = data[1],
		childPieces = tokenizeIntegers(readline()),
		piece2child = {}, child2piece = {};
	for (var i = 0; i < childPieces.length; ++i) {
		var piece = childPieces[i], child = i+1;
		piece2child[piece] = child;
		child2piece[child] = piece;
	}
	var piece = 0;
	for (var child = 1; child <= k; ++child) {
		var result = [child2piece[child]];
		for (var j = 1; j < n; ++j) {
			++piece;
			while (piece2child[piece] !== undefined) {
				++piece;
			}
			result.push(piece);
		}
		print(result.join(' '));
	}
}

main();

print(function(n, k) {

	var l = n * k;
	var a = new Int32Array(l + 1);

	readline().split(' ').forEach(function(v, i) {
		a[v] = i + 1;
	});

	var ret = [];
	for (var i = 0; i < k; i++)
		ret.push([]);

	for (var i = 1, c = 0, j = 0; i <= l; i++) {
		if (c === n - 1) {
			c = 0;
			j++;
		}
		if (a[i] === 0) {
			c++;
			ret[j].push(i);
		} else {
			ret[a[i] - 1].push(i);
		}
	}

	return ret.map(function(v) {
		return v.join(' ');
	}).join('\n');

}.apply(0, readline().split(' ').map(Number)));

;(function () {

	print(function(n, k) {
		var t = [], a = readline().split(' ').map(Number);
		a.forEach(function (e) { t.push([e]); });

		for (var i = 1, _i = n * k + 1, l = 0; i < _i; i++) {
			if (a.indexOf(i) !== -1) continue;

			if (t[l].length === n) l++;
			t[l].push(i);
		}

		return t.map(function (e) { return e.join(' '); }).join('\n');
	}.apply(null, readline().split(' ').map(Number)));

}).call(this);

print(function(n, k) {

	var a = ('0 ' + readline()).split(' ').map(Number);

	for (var i = n - 1; i >= 1; i--)
		if (a[i] !== a[i + 1])
			return i >= k ? -1 : i;

	return 0;

}.apply(0, readline().split(' ').map(Number)));

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

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

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

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], k = data[1],
		childPieces = tokenizeIntegers(readline()),
		used = {}, rows = [];
	for (var i = 0; i < childPieces.length; ++i) {
		used[childPieces[i]] = true;
		rows.push([childPieces[i]]);
	}
	var child = 0, limit = n*k, lines = [];
	for (var piece = 1; piece <= limit; ++piece) {
		if (!used[piece]) {
			rows[child].push(piece);
			if (rows[child].length == n) {
				lines.push(rows[child].join(' '));
				++child;
			}
		}
	}
	print(lines.join('\n'));
}

main();


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

//main
function main() {
    var totalTests = parseInt(readline());
    for (var i=0 ; i < totalTests ; i++) {
        console.log(360 % (180 - parseInt(readline())) ? "NO" : "YES");
    }

}

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

const input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
  let [n] = input[0].split(' ').map(x => parseInt(x));

  input.forEach((x, i) => {
    if (i === 0) return;

    if (360 % (180 - x) === 0)
      console.log('YES');
    else
      console.log('NO');
  });
});

// https://codeforces.com/problemset/problem/270/A
// Big O:
// Time complexity: O(n)
// Space complexity: O(n)

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

let tests;
let angles = [];
let counter = 0;
rl.on('line', (input) => {
    if (!tests) {
        tests = parseInt(input);
        return;
    }

    counter++;
    if (counter <= tests) {
        angles.push(parseInt(input));
    }

    if (counter === tests) {
        solve(angles);
        rl.close();
    }

});

function solve(angles) {
    for (angle of angles) {
        const output = isRegularPolygon(angle) ? "YES" : "NO";
        console.log(output);
    }
}

// Problem
// For a regular convex n-gon, each interior angle has a measure of: 180(n-2)/n degrees
function isRegularPolygon(angle) {
    const modulus = 360 % (180 - angle);
    return modulus === 0;
}

// https://codeforces.com/problemset/problem/270/A
// Big O:
// Time complexity:
// Space complexity:

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

let tests;
let angles = [];
let counter = 0;
rl.on('line', (input) => {
    if (!tests) {
        tests = parseInt(input);
        return;
    }

    counter++;
    if (counter <= tests) {
        angles.push(parseInt(input));
    }

    if (counter === tests) {
        readAngles(angles);
        rl.close();
    }

});

function readAngles(angles) {
    for (angle of angles) {
        const isRegularPolygon = canBuildRegularPolygon(angle)
        console.log(isRegularPolygon ? "YES" : "NO");
    }
}

// Problem
// For a regular convex n-gon, each interior angle has a measure of: 180(n-2)/n degrees
function canBuildRegularPolygon(angle) {
    const modulus = 360 % (180 - angle);
    return modulus === 0;
}

function main(stdin) {
  const lines = stdin.split("\n");
  lines.slice(1).forEach(v => {
    console.log(360 % (180 - parseInt(v)) === 0 ? "YES" : "NO");
  });
}

main(
  require("fs")
    .readFileSync(0, "utf-8")
    .trim()
);

var t = parseInt( readline(), 10 );
var answers = [];
while ( t-- ) {
  var a = parseInt( readline(), 10 );
  answers.push( 360%(180 - a) === 0 ? "YES" : "NO" );
}
print( answers.join( "\n" ) );

var limit= parseInt(readline());
var angle;
for (var i = 0; i < limit; i++) {
  angle = parseInt(readline());
  if (360 % (180-angle) === 0) print('YES');
  else print('NO');
}

var t=+readline();
while(t--){
	print(0 === 360%( 180-readline() ) ? 'YES' : 'NO');
}

var n = parseInt(readline());
var inp, k;

for(var i=0; i<n; i++)
{
  inp = parseInt(readline());
  k = 360/(180-inp);
  if(k%1 == 0) print('YES');
  else print('NO');
}

var l = parseInt(readline());
for(var i = 0; i < l; ++i)
{
    var a = parseInt(readline());
    var b = 0, n = 3;
    while(8)
    {
        b = 180 - 360/n;
             if(b == a){print("YES"); break;}
        else if(b > a){print("NO"); break;}
        n++;
    }
}

var n = parseInt(readline());
var result ="";
var flag = false;
for(var i=0; i < n; i++){
    var alpha = parseInt(readline());
    flag = false;
    for(var j = 3; j < 65538; j++ ){
        if(alpha == (180/j) * (j-2)) {
            result += 'YES' + '\n';
            flag = true;
            break;
        }
    }
    if(!flag){
        result += 'NO' + '\n';
    }

}

print(result);

;(function () {

	function pu (n) {
		var u = (n - 2)*180 / n;
		return u % 1 ? false : u;
	}

	var n = +readline();
	var us = [];
	var i, j, u;

	for (i = 0; i < n; i++) {
		u = +readline();
		j = 2;

		while (true) {
			j++;
			if (!us[j]) us[j] = pu(j);

			if (us[j]) {
				if (us[j] == u) {
					print('YES');
					break;
				}

				if (us[j] > u) {
					print('NO');
					break;
				}
			}
		}
	}

}).call(this);

var InputReader = (function () {
    function InputReader() {
        this.index = 0;
        this.tokenizer = [];
    }
    InputReader.prototype.next = function () {
        while (this.tokenizer == null || this.index == this.tokenizer.length) {
            this.tokenizer = readline().split(" ");
            this.index = 0;
        }
        var res = this.tokenizer[this.index++];
        return res;
    };
    InputReader.prototype.nextInt = function () {
        return parseInt(this.next());
    };
    InputReader.prototype.nextFloat = function () {
        return parseFloat(this.next());
    };
    return InputReader;
})();
function main() {
    var input = new InputReader();
    var nTest = input.nextInt();
    for (var i = 0; i < nTest; i++) {
        var n = input.nextInt();
        if (360 % (180 - n) == 0) {
            print("YES");
        }
        else {
            print("NO");
        }
    }
}
main();

var n = readline();

	for (var j=0; j<+n; j++){
			var str = readline();
			if ((360/(180-Number(str))%1==0))
			print("YES");
			else 	print("NO");
	}

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {"use strict";
    // TODO
    var t = rdN();
    while (t --> 0) {
        var a = rdN();
        var b = 180 - a;
        pr(360%b === 0 && 360/b > 2 ? 'YES' : 'NO');
    }
};

if (INPUT) {
INPUT = INPUT.split('\n').reverse();
readline = () => INPUT.pop();
write = (...s) => {OUTPUT += [...s].join(' ')};
print = (...s) => {write(...s); OUTPUT += '\n'};
}
const rdS = readline;
const rdN = () => +rdS();
const wr = write;
const pr = print;
const rdArS = () => rdS().split(' ');
const rdArN = () => rdArS().map(v => +v);
const prAr = (a) => pr(...a);
const cmpLt = (a, b) => a - b;
const cmpGt = (a, b) => b - a;
const defineProperty = (o, pN, v) => Object.defineProperty(o, pN, {configurable: true, enumerable: false, value: v });
defineProperty(Array.prototype, 'sortLt', function() { return this.sort(cmpLt); });
defineProperty(Array.prototype, 'sortGt', function() { return this.sort(cmpGt); });
const crAr = function(length, ...fillArgs) { return new Array(length).fill(...fillArgs); };
const getPrimes = function(n){var sieve=crAr(n+1,true);for(var i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}var primes=[];for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;};

main();
return OUTPUT;
})();

var t = parseInt(readline());
for (var i = 0; i < t; i++) {
    var a = 180 - parseInt(readline());
    if (360 % a == 0) print("YES");
    else print("NO")
}

var t=+readline();
while(t--){
	var a=+readline();
	var ans=false;
	for(var i=3; i<100; i++){
		if( 360/i + a/2 === 180-a ){
			ans=true;
			break;
		}
	}
	print(ans?'YES':'NO');
}

var n = parseInt(readline());

for(var i=0; i < n; i++){
    var alpha = parseInt(readline());
    for(var i = 3; i < 65538; i++ ){
        if(alpha == (180/i) * (i-2)){
            print('YES');
        }
    }
    print('NO');
}

var n = parseInt(readline());
var result ="";
for(var i=0; i < n; i++){
    var alpha = parseInt(readline());
    for(var j = 3; i < 65538; i++ ){
        if(alpha == (180/j) * (j-2)){
            result += 'YES' + '\n';
            break;
        }
    }
    result += 'NO' + '\n';
}

print(result);

var n = parseInt(readline());
var result ="";
for(var i=0; i < n; i++){
    var alpha = parseInt(readline());
    for(var i = 3; i < 65538; i++ ){
        if(alpha == (180/i) * (i-2)){
            result += 'YES' + '\n';
        }
    }
    result += 'NO' + '\n';
}

print(result);

var n = parseInt(readline());
var result ="";
for(var i=0; i < n; i++){
    var alpha = parseInt(readline());
    for(var j = 3; j < 65538; j++ ){
        if(alpha == (180/j) * (j-2)){
            result += 'YES' + '\n';
            break;
        }
        result += 'NO' + '\n';
    }

}

print(result);

var n = parseInt(readline());
var result ="";
for(var i=0; i < n; i++){
    var alpha = parseInt(readline());
    for(var j = 3; j < 65538; j++ ){
        if(alpha == (180/j) * (j-2)){
            result += 'YES' + '\n';
            break;
        }
    }
    result += 'NO' + '\n';
}

print(result);


'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 = BigInt(1e9 + 7)
var map = new Map()
var ans = new Map()

function main() {
  const xx = readline();

  Array(Number(xx)).fill(1).map((t, i) => {
    const n = Number(readline());

    var mark = {}
    for (let j = -100; j <= 100; j++) {
      mark[j] = false
    }
    var a = readline().split(' ').map((x, iii) => {
      if(mark[parseInt(x)] === false) return mark[parseInt(x)] = true
      if(mark[parseInt(x)] === true) mark[-parseInt(x)] = true
      return parseInt(x)
    })
    var count = 0
    for (let j = -100; j <= 100; j++) {
      count+= mark[j] ? 1:0
    }

    console.log(count)

  })
}

function solve(l, r) {
  if (l === r)
    ans[`${l}:${r}`] = l

  for (let i = l; i <= r; i++) {
    if (i === l && map[`${i + 1}:${r}`]) {
      ans[`${l}:${r}`] = i
      solve(i + 1, r)
      break
    } else if (i === r && map[`${l}:${i - 1}`]) {
      ans[`${l}:${r}`] = i
      solve(l, i - 1)
      break

    } else if (map[`${l}:${i - 1}`] && map[`${i + 1}:${r}`]) {
      ans[`${l}:${r}`] = i
      solve(l, i - 1)
      solve(i + 1, r)
      break
    }
  }
}

function check2(q, w, e) {
  if (q === w + e) return true
}

function dec2bin(dec) {
  var string = (dec >>> 0).toString(2);
  var front = ''
  for (let i = 0; i < 20 - string.length; i++) {
    front += '0'
  }
  return (front + string).split("").reverse().join("")
}

var t = parseInt(readline());

  function solve() {
    var n = parseInt(readline());
    var p = readline()
      .split(" ")
      .map((data) => +data)

    var arr = []

    for (var i = 0; i < n; i++) {
      var val1 = p[i]
      var val2 = -p[i]
      if (!arr.includes(val1)) {
        arr.push(val1)
      } else if (val1 === 0) {
        continue;
      } else if (arr.includes(val1) && arr.includes(val2)) {
        continue;
      } else {
        arr.push(val2)
      }
    }
    return arr.length
  }

  while (t--) {
    print(solve())
  }

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

/***
Good Bye 2021: 2022 is NEAR
2021-12-29

A. Integer Diversity

Lang: Node.js 12.16.3
***/

function main() {
    const t = parseInt(readline());
    for (let i=0; i<t; i++){
        const n = parseInt(readline());
        // Math.abs implicitly casts string to int
        const nums = readline().split(' ').map(x=>Math.abs(x));
        nums.sort();
        let r = 2;
        if (n < 2) {
            r = n;
        } else if (nums[0]===0 && nums[1]===0) {
            r = 1;
        }
        for (let j=2; j<n; j++){
            if (!(nums[j]===nums[j-1] &&
                (nums[j-1]===nums[j-2] || nums[j]===0))) {
                r++;
            }
        }
        console.log(r);
    }
}

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

// const lines = `3
// 4
// 1 1 2 2 2 1 1 -1
// 3
// 1 2 3
// 2
// 0 0`.split("\n");

const solveProblem = (lines) => {
  const lineNumbers = lines
    .slice(2)
    .filter((_, i) => i % 2 === 0)
    .map((line) => line.split(" ").map((x) => +x));

  const result = [];

  for (let i = 0; i < lineNumbers.length; i++) {
    const numbersFound = new Map();
    for (const number of lineNumbers[i]) {
      if (number === 0) {
        numbersFound.set(number, true);
      } else {
        if (numbersFound.has(number)) {
          numbersFound.set(-number, true);
        } else {
          numbersFound.set(number, true);
        }
      }
    }
    result.push(numbersFound.size);
  }

  console.log(result.join("\n"));
};

// solveProblem(lines);

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

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

let nl = nextLine();

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

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

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

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

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

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let i =0; i < t; i++){
		nl.num();
		let x = new Set(nl.nums().map((e) => Math.abs(e)).sort().map((e, j) => j%2 == 0?e:-e)).size;
		ans.push(x);
	}
	console.log(ans.join('\n'));
};

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

let _inputLines;
let _lineNumber = 0;
let inputReader = _inputReader();

function _main() {
  _inputLines = _inputData
    .trim()
    .split("\n")
    .map((string) => {
      return string.trim();
    });

  let t = inputReader.readNumber();

  function solve() {
    let n = inputReader.readNumber();
    let v = inputReader.readNumberArray();
    let arr = new Array(105).fill(0);
    v.forEach((x) => {
      arr[Math.abs(x)] += 1;
    });
    let ans = 0;
    arr.forEach((x, ind, arr) => {
      if (ind == 0) {
        if (x > 0) ans++;
      } else {
        if (x > 1) ans += 2;
        else if (x == 1) ans++;
        else ans += 0;
      }
    });
    console.log(ans);
  }

  while (t--) {
    solve();
  }
}

var _inputData = "";
function cacheInput(data) {
  _inputData += data;
}

process.stdin.resume();
process.stdin.setEncoding("utf8");
process.stdin.on("data", cacheInput).on("end", _main);

function _inputReader() {
  function readNumber() {
    return Number(_inputLines[_lineNumber++]);
  }

  function readNumberArray() {
    return _inputLines[_lineNumber++].split(" ").map((val) => Number(val));
  }

  return {
    readNumber,
    readNumberArray,
  };
}

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++) {
    let n = readline();
    let a = readline().split(" ").map(w => parseInt(w))
    var ans = 0;
    var s = [];
    for(var i=0;i<a.length;i++) {
        if(s[a[i]] == undefined) {
            ans++;
            s[a[i]] = true;
        } else {
            var f = (-1)*a[i]
            if(s[f] == undefined) {
                ans++;
                s[f] = true;
            }
        }
    }
    console.log(ans)
}

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => {
        let next;
        do {
            next = (await getLineGen.next());
        } while (!next.done && next.value === '');
        return next.value;
    };
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const a = (await getLine()).split(' ').map(num => parseInt(num));
        const m = {};
        let res = 0;
        for(let i = 0; i < a.length; i++) {
            const key = Math.abs(a[i]);
            if (!m[key])
                m[key] = 0;
            if ((key !== 0 && m[key] < 2) || (key === 0 && m[key] < 1)) {
                m[key] += 1;
                res += 1;
            }
        }
        console.log(res);
    }
}

solve();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

/***
Good Bye 2021: 2022 is NEAR
2021-12-29

A. Integer Diversity
***/

function main() {
    const t = parseInt(readline());
    for (let i=0; i<t; i++){
        const n = parseInt(readline());
        const nums = readline().split(' ');
        nums.sort();
        let r = 2;
        if (n < 2) {
            r = n;
        } else if (nums[0]==='0' && nums[1]==='0') {
            r = 1;
        }
        for (let j=2; j<n; j++){
            if (!(nums[j]===nums[j-1] &&
                (nums[j-1]===nums[j-2] || nums[j]==='0'))) {
                r++;
            }
        }
        console.log(r);
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

/***
Good Bye 2021: 2022 is NEAR
2021-12-29

A. Integer Diversity
***/

function main() {
    const t = parseInt(readline());
    console.log("t="+t);
    for (let i=0; i<t; i++){
        const n = parseInt(readline());
        console.log("n="+n);
        const nums = readline().split(' ');
        console.log("nums="+nums);
        nums.sort();
        let r = 2;
        if (n < 2) {
            r = n;
            console.log('hi A '+r);
        } else if (nums[0]==='0' && nums[1]==='0') {
            r = 1;
            console.log('hi B '+r);
        }
        for (let j=2; j<n; j++){
            if (!(nums[j]===nums[j-1] &&
                (nums[j-1]===nums[j-2] || nums[j]==='0'))) {
                r++;
            }
        }
        console.log(r);
    }
}

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

// const lines = `3
// 4
// 1 1 2 2
// 3
// 1 2 3
// 2
// 0 0`.split("\n");
//

const solveProblem = (lines) => {
  const lineNumbers = lines
    .slice(2)
    .filter((_, i) => i % 2 === 0)
    .map((line) => line.split(" ").map((x) => +x));

  const result = [];

  for (let i = 0; i < lineNumbers.length; i++) {
    const numbersFound = new Map();
    let lineResult = 0;
    for (const number of lineNumbers[i]) {
      if (number === 0) {
        if (!numbersFound.has(number)) {
          lineResult++;
        }
      } else {
        if (!numbersFound.has(number) || numbersFound.get(number) === 1) {
          lineResult++;
        }
      }
      numbersFound.set(number, (numbersFound.get(number) || 0) + 1);
    }
    result.push(lineResult);
  }

  console.log(result.join("\n"));
};

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

// const lines = `3
// 4
// 1 1 2 2
// 3
// 1 2 3
// 2
// 0 0`.split("\n");
//

const solveProblem = (lines) => {
  const lineNumbers = lines
    .slice(2)
    .filter((_, i) => i % 2 === 0)
    .map((line) => line.split(" ").map((x) => +x));

  const result = [];

  for (let i = 0; i < lineNumbers.length; i++) {
    const numbersFound = new Map();
    let lineResult = 0;
    for (const number of lineNumbers[i]) {
      if (number === 0) {
        if (!numbersFound.has(number)) {
          lineResult++;
        }
      } else {
        if (!numbersFound.has(number) || numbersFound.get(number) === 1) {
          lineResult++;
        }
      }
      numbersFound.set(number, (numbersFound.get(number) || 0) + 1);
    }
    result.push(lineResult);
  }

  console.log(result);
};

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

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

let nl = nextLine();

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

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

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

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

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

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let i =0; i < t; i++){
		nl.num();
		let x = new Set(nl.nums().sort().map((e, j) => j%2 == 0?e:-e)).size;
		ans.push(x);
	}
	console.log(ans.join('\n'));
};

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

let _inputLines;
let _lineNumber = 0;
let inputReader = _inputReader ();

function _main() {

	_inputLines = _inputData.trim().split('\n').map((string) => {
		return string.trim();
	});;

	let t = inputReader.readNumber();

	function solve() {
	  let n = inputReader.readNumber();
	  let v = inputReader.readNumberArray();
	  let arr = new Array(100).fill(0);
	  v.forEach(x => {
	    arr[Math.abs(x)]+=1;
	  });
	  let ans = 0;
	  arr.forEach((x, ind, arr)=>{
	    if(ind!=0) ans+=2*(x/2);
	    else {
	      if(x > 0)
	      ans+=1;
	    }
	  });
	  console.log(ans);
	}

	while (t--) {
	  solve();
	}

}

var _inputData = '';
function cacheInput(data) {
	_inputData += data;
}

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', cacheInput).on('end', _main);

function _inputReader () {
	function readNumber(){
		return Number(_inputLines[_lineNumber++]);
	}

	function readNumberArray(){
		return _inputLines[_lineNumber++].split(' ').map(val => Number(val));
	}

	return {
		readNumber,
		readNumberArray,
	}
}


var vals = readline().split(" ");
var n = parseInt(vals[0]);
var m = parseInt(vals[1]);
var fil = [];

for (var i = 1; i < n + 1; i++) {
  fil[i] = readline().split("")
  .map(function(el) {
    if (el === '.') {
      return 0;
    } else if (el === '*') {
      return 100;
    } else {
      return el;
    }
  })
  .map(function(el) {
    return parseInt(el);
  });
  fil[i].unshift(0);
  fil[i].push(0);
}

fil[0] = [];
fil[n+1] = [];
for (var j = 0; j < m + 2; j++) {
  fil[0].push(0);
  fil[n+1].push(0);
}

function calc(n, m, fil) {
  var sum;
  for (var i = 1; i < n + 1; i++) {
    for (var j = 1; j < m + 1; j++) {
      sum = fil[i-1][j-1] + fil[i][j-1] + fil[i+1][j-1] + fil[i-1][j] + fil[i+1][j] + fil[i-1][j+1] + fil[i][j+1] + fil[i+1][j+1];
      if (fil[i][j] !== 100 && Math.floor(sum / 100) !==  fil[i][j]) {
        print('NO');
        return;
      }
    }
  }
  print('YES');
}

calc(n,m,fil);

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

var rows = [];
var isGridValid = true;

function numerize(x) {
    return isNaN(Number(x)) ? x : Number(x);
}

function isCellValid(y, x) {
    var cell = rows[y][x];
    if (!cell) {
        return false;
    }

    var bombs = 0;
    for (var i = y - 1; i <= y + 1; i++) {
        if (!rows[i]) {
            continue;
        }
        for(var j = x - 1; j <= x + 1; j++) {
            if (rows[i][j] && rows[i][j] === '*') {
                bombs++;
            }
        }
    }

    if (typeof cell === 'number') {
        return bombs === cell;
    }

    return cell === '.' ? bombs === 0 : true;
}

for (var i = 0; i < n; i++) {
    var row = readline().split('').map(numerize);
    rows.push(row);
}

for (var i = 0; i < n; i++) {
    for (var j = 0; j < m; j++) {
        isGridValid = isCellValid(i, j);
        if (!isGridValid) {
            break;
        }
    }
    if (!isGridValid) {
        break;
    }
}

print(isGridValid ? 'YES' : 'NO');

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

const lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    let dims = lines[0];
    dims = dims.split(' ').map(Number);
    const n = dims[0], m = dims[1];

    const rows = [];
    let isGridValid = true;

    function numerize(x) {
        return isNaN(Number(x)) ? x : Number(x);
    }

    function isCellValid(y, x) {
        const cell = rows[y][x];
        if (!cell) {
            return false;
        }

        let bombs = 0;
        for (let i = y - 1; i <= y + 1; i++) {
            if (!rows[i]) {
                continue;
            }
            for(let j = x - 1; j <= x + 1; j++) {
                if (rows[i][j] && rows[i][j] === '*') {
                    bombs++;
                }
            }
        }

        if (typeof cell === 'number') {
            return bombs === cell;
        }

        return cell === '.' ? bombs === 0 : true;
    }

    for (let i = 1; i <= n; i++) {
        var row = lines[i].split('').map(numerize);
        rows.push(row);
    }

    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            isGridValid = isCellValid(i, j);
            if (!isGridValid) {
                break;
            }
        }
        if (!isGridValid) {
            break;
        }
    }

    process.stdout.write(isGridValid ? 'YES' : 'NO');
});

l = readline().split(' ');
n = +l[0], m = +l[1];
a = [];
for (i = 0; i < n; i++)
  a.push(readline());
dr = [-1, -1, 0, 1, 1, 1, 0, -1], dc = [0, 1, 1, 1, 0, -1, -1, -1];
function Bombs_Around(i, j) {
  ans = 0;
  for (k = 0; k < 8; k++) {
    ix = i + dr[k], jx = j + dc[k];
    if (ix < 0 || ix >= n || jx < 0 || jx >= m)
      continue;
    if (a[ix].charAt(jx) === '*')
      ans++;
  }
  return ans;
}
function Solve() {
  for (i = 0; i < n; i++)
    for (j = 0; j < m; j++) {
      cur = a[i].charAt(j);
      if (cur === '*')
        continue;
      bombs = Bombs_Around(i, j);
      if (cur === '.') {
        if (bombs > 0)
          return false;
      }
      else if (bombs != parseInt(cur))
        return false;
    }
  return true;
}
print(Solve() ? 'YES' : 'NO');

var p = readline().split(' ').map(Number);
var n = p[0];
var m = p[1];
var saper = [];
var ans = 'YES';
for (var i=0; i<n+2; i++){
	saper[i] = [];
	for (var j=0; j<m+2; j++){
		saper[i][j] = +0;
	}
}
for (var i=1; i<n+1; i++){
	var str = readline().split('');
	for (var j=1; j<m+1; j++){
		if (str[j-1] == '*') saper[i][j] = '*';
		else if (str[j-1] == '.') saper[i][j] = +0;
		else saper[i][j] = +str[j-1];
	}
}
for (var i=1; i<n+1; i++){
	for (var j=1; j<m+1; j++){
		if (saper[i][j] != '*') {
			var count = 0;
			if (saper[i-1][j-1] == '*') count++;
			if (saper[i-1][j] == '*') count++;
			if (saper[i-1][j+1] == '*') count++;
			if (saper[i][j-1] == '*') count++;
			if (saper[i][j+1] == '*') count++;
			if (saper[i+1][j-1] == '*') count++;
			if (saper[i+1][j] == '*') count++;
			if (saper[i+1][j+1] == '*') count++;
			print (count);
			if (saper[i][j] != count) ans = 'NO';
		}
	}
}
print (ans);

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

var rows = [];
var isGridValid = true;

function numerize(x) {
    return isNaN(Number(x)) ? x : Number(x);
}

function isCellValid(x, y, cell) {
    var bombs = 0;
    for (var i = y - 1; i <= y + 1; i++) {
        if (!rows[i]) {
            continue;
        }
        for(var j = x - 1; j <= x + 1; j++) {
            if (rows[i][j] && rows[i][j] === '*') {
                bombs++;
            }
        }
    }

    if (typeof cell === 'number') {
        return bombs === cell;
    }

    return cell === '.' ? bombs === 0 : true;
}

for (var i = 0; i < n; i++) {
    var row = readline().split('').map(numerize);
    rows.push(row);
}

for (var i = 0; i < n; i++) {
    for (var j = 0; j < m; j++) {
        isGridValid = isCellValid(j, i, rows[i][j]);
        if (!isGridValid) {
            break;
        }
    }
}

print(isGridValid ? 'YES' : 'NO');


"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() {
    let t = parseInt(readline())
    while(t--){
        let n = parseInt(readline())
        let k = readline().split(" ")
        let v = []
        for(let i in k) v.push(parseInt(k[i]))
        if(v[n-2] > v[n-1]){
            console.log(-1)
        }else{
            let i = n-3
            let ct = 0
            let a = new Array(n).fill(false)
            while(i>=0){
                if(v[i] > v[i+1]){
                    ct++
                    v[i] = v[i+1] - v[n-1]
                    a[i] = true
                }
                i--
            }
            let flag = true
            for(let i = 1;i<n;i++){
                if(v[i]<v[i-1]){
                    flag = false;
                    break;
                }
            }
            if(flag){
                let i = n-3
                console.log(ct)
                while(i>=0){
                    if(a[i]){
                        console.log(`${i+1} ${i+2} ${n}`)
                    }
                    i--;
                }
            }else console.log(-1)
        }
    }

}

"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() {
    let t = parseInt(readline())
    while(t--){
        let n = parseInt(readline())
        let v = readline().split(" ")
        if(parseInt(v[n-2]) > parseInt(v[n-1])){
            console.log(-1)
        }else{
            let i = n-3
            let ct = 0
            let a = new Array(n).fill(false)
            while(i>=0){
                if(parseInt(v[i]) > parseInt(v[i+1])){
                    ct++
                    v[i] = v[i+1] - v[n-1]
                    a[i] = true
                }
                i--
            }
            let flag = true
            for(let i = 1;i<n;i++){
                if(parseInt(v[i])<parseInt(v[i-1])){
                    flag = false;
                    break;
                }
            }
            if(flag){
                let i = n-3
                console.log(ct)
                while(i>=0){
                    if(a[i]){
                        console.log(`${i+1} ${i+2} ${n}`)
                    }
                    i--;
                }
            }else console.log(-1)
        }
    }

}

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

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

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		let ok = true;
		for (let i = 0; i < n-1; i++) {
			if (a[i] > a[i+1]) ok = false;
		}

		if (ok) {
			console.log(0);
		} else if (a[n-2] <= a[n-1] && a[n-1] >= 0) {
			console.log(n-2);
			for (let i = 0; i < n-2; i++) {
				console.log(i+1, n-1, n);
			}
		} else {
			console.log(-1);
		}
	}
}

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

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

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		let ok = true;
		for (let i = 1; i < n; i++) {
			ok = ok && a[i-1] <= a[i];
		}

		if (ok) {
			console.log(0);
		} else if (a[a.length-2] <= a[a.length-1] && a[a.length-1] >= 0) {
			console.log(n-2);
			for (let i = 0; i < n-2; i++) {
				console.log(i+1, n-1, n);
			}
		} else {
			console.log(-1);
		}
	}
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    const check = (arr) => {
      for (let i = 1; i < arr.length; i++)
        if (arr[i - 1] > arr[i]) return false;
      return true;
    };
    if (check(arr)) {
      console.log(0);
      continue;
    }
    if (arr[n - 1] < 0 && arr[n - 2] < 0) {
      console.log(-1);
      continue;
    }
    if (arr[n - 1] < arr[n - 2]) {
      console.log(-1);
      continue;
    }
    let o = n - 3;
    let k = o;
    console.log(o + 1);
    while (o >= 0) {
      console.log(`${o + 1} ${k + 2} ${k + 3}`);
      o--;
    }
  }
};
solve();

'use strict';

function solve(n, a) {
  const dif = new Array(n);
  let max = n - 1;
  for (let i = n - 2; i >= 0; i--) {
    var _dif$, _dif;
    const cur = a[i] - a[max];
    if (cur < ((_dif$ = (_dif = dif[i + 1]) === null || _dif === void 0 ? void 0 : _dif[0]) !== null && _dif$ !== void 0 ? _dif$ : Infinity)) {
      dif[i] = [cur, i, max];
    } else {
      dif[i] = [...dif[i + 1]];
    }
    if (a[i] > a[max]) max = i;
  }
  const nums = new Array(n),
        res = [];
  nums[n - 1] = a[n - 1];
  nums[n - 2] = a[n - 2];
  for (let i = 0; i < n - 2; i++) {
    nums[i] = dif[i + 1][0];
    if (nums[i] < a[i]) res.push([i, dif[i + 1][1], dif[i + 1][2]]);else nums[i] = a[i];
  }
  for (let i = 0; i < n - 1; i++) {
    if (nums[i] > nums[i + 1]) return -1;
  }
  if (res.length) return `${res.length}\n${res.map(arr => arr.map(num => num + 1).join(' ')).join('\n')}`;
  return 0;
}

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

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

"use strict";
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() {
    let t = parseInt(readline())
    while(t--){
        let n = parseInt(readline())
        let k = readline().split(" ")
        let v = []
        for(let i in k) v.push(parseInt(v[i]))
        if(parseInt(v[n-2]) > parseInt(v[n-1])){
            console.log(-1)
        }else{
            let i = n-3
            let ct = 0
            let a = new Array(n).fill(false)
            while(i>=0){
                if(v[i] > v[i+1]){
                    ct++
                    v[i] = v[i+1] - v[n-1]
                    a[i] = true
                }
                i--
            }
            let flag = true
            for(let i = 1;i<n;i++){
                if(v[i]<v[i-1]){
                    flag = false;
                    break;
                }
            }
            if(flag){
                let i = n-3
                console.log(ct)
                while(i>=0){
                    if(a[i]){
                        console.log(`${i+1} ${i+2} ${n}`)
                    }
                    i--;
                }
            }else console.log(-1)
        }
    }

}

"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() {
    let t = parseInt(readline())
    while(t--){
        let n = parseInt(readline())
        let v = readline().split(" ")
        if(parseInt(v[n-2]) > parseInt(v[n-1])){
            console.log(-1)
        }else{
            let i = n-3
            let ct = 0
            let a = new Array(n).fill(false)
            while(i>=0){
                if(v[i] > v[i+1]){
                    ct++
                    v[i] = v[i+1] - v[n-1]
                    a[i] = true
                }
                i--
            }
            let flag = true
            for(let i = 1;i<n;i++){
                if(v[i]<v[i-1]){
                    flag = false;
                    break;
                }
            }
            if(flag){
                let i = n-3
                console.log(ct)
                while(i>=0){
                    if(a[i]){
                        console.log(`${i+1} ${i+2} ${n}`)
                    }
                    i--;
                }
            }else console.log(-1)
        }
    }

}

"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() {
    let t = parseInt(readline())
    while(t--){
        let n = parseInt(readline())
        let v = readline().split(" ")
        if(parseInt(v[n-2]) > parseInt(v[n-1])){
            console.log(-1)
        }else{
            let i = n-3
            let ct = 0
            let a = new Array(n).fill(false)
            while(i>=0){
                if(v[i] > v[i+1]){
                    ct++
                    v[i] = v[i+1] - v[n-1]
                    a[i] = true
                }
                i--
            }
            let flag = true
            for(let i = 1;i<n;i++){
                if(v[i]<v[i-1]){
                    flag = false;
                    break;
                }
            }
            if(flag){
                let i = n-3
                console.log(ct)
                while(i>=0){
                    if(a[i]){
                        console.log(`${i} ${i+1} ${n-1}`)
                    }
                    i--;
                }
            }else console.log(-1)
        }
    }

}

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

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

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		if (a[a.length-2] > a[a.length-1]) {
			console.log(-1);
		} else {
			console.log(n-2);
			for (let i = 0; i < n-2; i++) {
				console.log(i+1, n-1, n);
			}
		}
	}
}

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

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

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		if (a[a.length-2] > a[a.length-1]) {
			console.log(-1);
		} else {
			console.log(n-2);
			for (let i = 0; i < n-2; i++) {
				console.log(i+1, n-1, n-2);
			}
		}
	}
}