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()),
		numSubjects = data[0], chapterCost = data[1],
		subjects = tokenizeIntegers(readline()),
		total = 0;
	subjects.sort(function (a, b) {
		return a - b;
	});
	for (var i = 0; i < numSubjects; ++i) {
		total += subjects[i] * chapterCost;
		chapterCost = Math.max(1, chapterCost-1);
	}
	print(total);
}

main();

//var n = 3, x = 3,
//    chapters = [1, 1, 1],
//    totalTime = 0;

var in1 = readline().split(" "),
    n = Number(in1[0]),
    x = Number(in1[1]),
    chapters = parseArrayString(readline()),
    totalTime = 0;

chapters.sort(function (a, b) {
    return a - b;
});

for (var i = 0; i < chapters.length; i++) {
    var item = chapters[i];

    totalTime += item * x;
    x--;
    x = x <= 0 ? 1 : x;
}

//console.log( totalTime );
print(totalTime);

function parseArrayString(str) {
    return str.split(" ").map(function (x) {
        return x >> 0;
    });
}

var firstLine = readline().split(" ").map(function(a){return parseInt(a, 10)});
var n = firstLine[0];
var x = firstLine[1];
var chapters = readline().split(" ").map(function(a){return parseInt(a,10)});
chapters.sort(function(a, b){return a - b;})
var hours = 0;
for(var i = 0; i < chapters.length; i++){
	hours += chapters[i] * x
	if(x > 1){
		x--;
	}
}

print(hours)

if (!this.readline) print = console.log, readline = require('./readline');

print(function(n, x) {
	var c = readline().split(' ').map(Number);
	c.sort(function(a, b) {
		return a - b;
	});

	var ans = 0;
	for (var i = 0; i < n; i++) {
		ans += c[i] * x;
		if (x > 1)
			x--;
	}
	return ans;

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

var info = readline().split(' ').map(Number);
var Arr = readline().split(' ').map(Number);
var sArr = Arr.sort(function(a, b){return a-b});
var speed = info[1];
var result = 0;
for (var i=0; i<info[0]; i++) {
    if (speed<1) { speed = 1; }
    result += sArr[i] * speed;
    speed -= 1;
}
print(result);

;(function () {

	var n = readline().split(' ');
	var x = +n[1];
	n = +n[0];

	var c = readline().split(' ').map(Number).sort(function (a, b) { return b - a; });

	var r = 0;
	while (n--) {
		r += x * c[n];
		x = (x > 1) ? (x - 1) : 1;
	}

	print(r);

}).call(this);

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
    //console.log("main")

    const inArray = readline().split(" ");
    const n = parseInt(inArray[0])
    let x = parseInt(inArray[1])
    let cs = readline().split(" ").map(x => parseInt(x));

    cs.sort(function(a,b){return a-b})
    let total = 0
    cs.forEach(c => {
        total += c*x
        x--
        x = Math.max(x,1);
    });
    console.log(total)

}

//var n = 3, x = 3,
//    chapters = [1, 1, 1],
//    totalTime = 0;

var in1 = readline().split(" "),
    n = Number(in1[0]),
    x = Number(in1[1]),
    chapters = parseArrayString(readline()),
    totalTime = 0;

chapters.sort();

for (var i = 0; i < chapters.length; i++) {
    var item = chapters[i];

    totalTime += item * x;
    x--;
    x = x <= 0 ? 1 : x;
}

//console.log( totalTime );
print(totalTime);

function parseArrayString(str) {
    return str.split(" ").map(function (x) {
        return x >> 0;
    });
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
    //console.log("main")

    const inArray = readline().split(" ");
    const n = parseInt(inArray[0])
    let x = parseInt(inArray[1])
    let cs = readline().split(" ").map(x => parseInt(x));
    console.log(cs)
    cs.sort(function(a,b){return a-b})
    console.log(cs)
    let total = 0
    cs.forEach(c => {
    console.log(`${c} mul ${x}`)
        total += c*x
        x--
        x = Math.max(x,1);
    });
    console.log(total)

}
function foo(x) {
    process.stdout.write("hello: ");   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}


var readline = require('readline');

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

const solve = (d1, d2, k, res) => {
    try{
        if(d1.length >0 || d2.length > 0){
            if(d1.length && d1[0] === 0){
                res.push(d1[0])
                return solve(d1.slice(1), d2, k+1, res)
            }else if(d2.length && d2[0] === 0){
                res.push(d2[0])
                return solve(d1, d2.slice(1), k+1, res)
            }else if(d1.length && d1[0] <= k){
                res.push(d1[0])
                return solve(d1.slice(1), d2, k, res)
            }else if(d2.length && d2[0] <= k){
                res.push(d2[0])
                return solve(d1, d2.slice(1), k, res)
            }else{
                return -1
            }

        }else{
            return res.join(' ');
        }
    }catch (ex){
        console.log('ex:', ex)
    }
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');

let currentline = 0;
function readline(){
    return input[currentline++];
}

let t = +readline()
while(t--){
    readline()
    let [k,n,m] = readline().split(' ').map(x=>+x);
    let a = readline().split(' ').map(x=>+x)
    let b = readline().split(' ').map(x=>+x)
    console.log(`${solve(a, b, n, m, k)}`);
}

function solve(a, b, n, m, k){
    let idx_a = 0;
    let idx_b = 0;
    let result = '';

    while(idx_a < n || idx_b < m){
        if(a[idx_a] === 0){
            result += ` ${0}`;
            idx_a++;
            k++
        }else if(b[idx_b] === 0){
            result += ` ${0}`;
            idx_b++;
            k++;
        }else if(a[idx_a] <= k){
            result += ` ${a[idx_a]}`;
            idx_a++;
        }else if(b[idx_b] <= k){
            result += ` ${b[idx_b]}`;
            idx_b++;
        }else return -1;
    }
    return result.trim();
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');

let currentline = 0;
function readline(){
    return input[currentline++];
}

let t = +readline()
while(t--){
    readline()
    let [k,n,m] = readline().split(' ').map(x=>+x);
    let a = readline().split(' ').map(x=>+x)
    let b = readline().split(' ').map(x=>+x)
    console.log(`${solve(a, b, n, m, k)}`);
}

function solve(a, b, n, m, k){
    let idx_a = 0;
    let idx_b = 0;
    let result = [];

    while(idx_a < n || idx_b < m){
        if(a[idx_a] === 0){
            result.push(0);
            idx_a++;
            k++
        }else if(b[idx_b] === 0){
            result.push(0);
            idx_b++;
            k++;
        }else if(a[idx_a] <= k){
            result.push(a[idx_a]);
            idx_a++;
        }else if(b[idx_b] <= k){
            result.push(b[idx_b]);
            idx_b++;
        }else return -1;
    }
    return result.join(' ');
}

"use strict";

const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    readline();
    let [k, n, m] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr1 = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr2 = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let i = 0,
      j = 0,
      res = [];
    while (i < n || j < m) {
      if (i < n && arr1[i] === 0) {
        res.push(arr1[i++]);
        k++;
      } else if (j < m && arr2[j] === 0) {
        res.push(arr2[j++]);
        k++;
      } else if (i < n && arr1[i] <= k) res.push(arr1[i++]);
      else if (j < m && arr2[j] <= k) res.push(arr2[j++]);
      else break;
    }
    if (res.length === n + m) console.log(res.join(" "));
    else console.log(-1);
  }
};
solve();

//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] = BigInt(next());
		}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 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 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 s = next();
		var K = nextInt();
		var N = nextInt();
		var M = nextInt();
		var alist = nextIntArray(N);
		var blist = nextIntArray(M);
		var output = [];
		while(alist.length + blist.length > 0){
			if(alist.length > 0){
				if(alist[0] == 0){
					output.push(alist.shift());
					K++;
					continue;
				}else if(alist[0] <= K){
					output.push(alist.shift());
					continue;
				}
			}
			if(blist.length > 0){
				if(blist[0] == 0){
					output.push(blist.shift());
					K++;
					continue;
				}else if(blist[0] <= K){
					output.push(blist.shift());
					continue;
				}
			}
			output = -1;
			break;
		}
		if(output == -1){
			myout(output);
		}else{
			myout(myconv(output, 8));
		}
	}
}

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

let chng;

function main () {
	let T = rn();
	while (T--) {
		rl();
		let [k, n, m] = rna();
		const a = rna();
		const b = rna();

		function go (ar) {
			while (ar.length && ar[0] <= k) {
				if (ar[0] == 0) k++;
				ans.push(ar[0]);
				ar.shift();
				chng = true;
			}
		}

		let ans = [];
		let i = 0, j = 0;
		while (a.length || b.length) {
			chng = false;
			go(a);
			go(b);

			if (!chng) {
				ans = false;
				break;
			}
		}

		console.log(ans ? ans.join(' ') : -1);
	}
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

const acode = 'a'.charCodeAt(0);
const zcode = 'z'.charCodeAt(0);
const arr = [];
for (let i = acode; i <= zcode; i++) {
   arr.push(String.fromCharCode(i));
}

function solve() {
   read();
   const [k, n, m] = readArray(Number);
   const a = readArray(Number);
   const b = readArray(Number);
   const ans = [];
   let curn = k;
   let ia = 0;
   let ib = 0;
   for (let i = 0; i < n + m; i++) {
      if (a[ia] === 0) {
         ans.push(0);
         ia++;
         curn++;
         continue;
      }
      if (b[ib] === 0) {
         ans.push(0);
         ib++;
         curn++;
         continue;
      }
      if (a[ia] <= curn) {
         ans.push(a[ia]);
         ia++;
         continue;
      }
      if (b[ib] <= curn) {
         ans.push(b[ib]);
         ib++;
         continue;
      }
      write(-1);
      return;
   }
   write(ans.join(' '));
}

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

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

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(str => str.trim());

    main();
});

function readLine() {
    return inputString[currentLine++];
}
function main()
{
    //const name=readLine();
    //console.log(name);

    let test=readLine();
    while(test--)
    {
       // let p1x,p1y,p2x,p2y,p3x,p3y;

        readLine();
        p1=readLine();
        p2=readLine();
        p3=readLine();
        p1=p1.split(" ");
        p2=p2.split(" ");
        p3=p3.split(" ");
        k=parseInt(p1[0]);
        n=parseInt(p1[1]);
        m=parseInt(p1[2]);
        //console.log(n,m,k);
        vec1=[],vec2=[],vec=[];
        for(i=0;i<n;i++)
        {
            //console.log("hh ",i);
            vec1.push(parseInt(p2[i]));
        }
        for(i=0;i<m;i++)
        {
            vec2.push(parseInt(p3[i]));
        }
        //console.log(vec1);
        //console.log(vec2);
        for( i=0,pos1=0,pos2=0;i<n+m;i++)
        {
            if(pos1===n)
            {
                for( j=pos2;j<m;j++)
                {
                    vec.push(vec2[pos2++]);
                }
                break;
            }
            if(pos2===m)
            {
                for(j=pos1;j<n;j++)
                {
                    vec.push(vec1[pos1++]);
                }
                break;
            }

            if(vec1[pos1]<=vec2[pos2])
            {
                vec.push(vec1[pos1]);
                pos1++;
            }
            else
            {
                vec.push(vec2[pos2]);
                pos2++;
            }
        }
        cnt=k;
        chk=true;
        for(i=0;i<n+m;i++)
        {
            if(vec[i]==0)
            {
                cnt++;
                continue;
            }
            val=vec[i];
            if(val>cnt)
            {
                chk=false;
                break;
            }

        }
        //console.log("hello ",chk);
        if(chk===false)
        {
            console.log(-1);
            //cout<<-1<<endl;
        }
        else
        {
            out="";
            for(i=0;i<n+m;i++)
                out+=vec[i]+" ";
            console.log(out);
                //console.log(vec[i]," ");
        }

    }
}

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
// import * as readline from 'readline'
// const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
// const ask = (query: string) => new Promise<string>((resolve) => rl.question(query, resolve))
// // Don't forget `rl.close()`.
const INT = Math.floor;
Array.prototype.last = function () {
    return this.length === 0 ? undefined : this[this.length - 1];
};
Array.prototype.isEmpty = function () {
    return this.length === 0;
};
const less = (a, b) => (a == b ? 0 : a < b ? -1 : 1);
const greater = (a, b) => (a == b ? 0 : a < b ? 1 : -1);
const bigIntMax = (...args) => args.reduce((m, e) => (e > m ? e : m));
const bigIntMin = (...args) => args.reduce((m, e) => (e < m ? e : m));
const bigIntAbs = (arg) => (arg < 0 ? -arg : arg);
function read_stdin() {
    return fs.readFileSync(process.env.NODE_ENV === 'debug' ? stdin : process.stdin.fd, 'utf8');
}
class Input {
    constructor(str) {
        this.index = 0;
        this.inputs = (str ? str : read_stdin()).split(/\s+/);
    }
    number() {
        return Number(this.inputs[this.index++]);
    }
    numbers(n) {
        return this.inputs.slice(this.index, (this.index += n)).map(Number);
    }
    bigint() {
        return BigInt(this.inputs[this.index++]);
    }
    bigints(n) {
        return this.inputs.slice(this.index, (this.index += n)).map(BigInt);
    }
    word() {
        return this.inputs[this.index++];
    }
    words(n) {
        return this.inputs.slice(this.index, (this.index += n));
    }
}
function array(len, init) {
    return Array(len).fill(init);
}
function array2(h, w, init) {
    return array(h, 0).map(() => array(w, init));
}
function main() {
    const input = new Input();
    const t = input.number();
    const ans = Array(t);
    loop: for (let i = 0; i < t; i++) {
        let [k, n, m] = input.numbers(3);
        const A = input.numbers(n);
        const B = input.numbers(m);
        A.reverse();
        B.reverse();
        const seq = [];
        for (let j = 0; j < n + m; j++) {
            if (!A.isEmpty() && A.last() === 0) {
                k++;
                seq.push(A.pop());
            }
            else if (!B.isEmpty() && B.last() === 0) {
                k++;
                seq.push(B.pop());
            }
            else {
                if (!A.isEmpty() && !B.isEmpty()) {
                    if (A.last() < B.last()) {
                        const line = A.pop();
                        if (line > k) {
                            ans[i] = [-1];
                            continue loop;
                        }
                        seq.push(line);
                    }
                    else {
                        const line = B.pop();
                        if (line > k) {
                            ans[i] = [-1];
                            continue loop;
                        }
                        seq.push(line);
                    }
                }
                else if (!A.isEmpty()) {
                    const line = A.pop();
                    if (line > k) {
                        ans[i] = [-1];
                        continue loop;
                    }
                    seq.push(line);
                }
                else {
                    const line = B.pop();
                    if (line > k) {
                        ans[i] = [-1];
                        continue loop;
                    }
                    seq.push(line);
                }
            }
        }
        ans[i] = seq;
    }
    console.log(ans.map((seq) => seq.join(' ')).join('\n'));
}
main();
//# sourceMappingURL=aoj.js.map

process.stdin.resume();

process.stdin.setEncoding('utf8');

var input = '';

process.stdin.on('data' , data=>{
    input += data;
});
process.stdin.on('end' , ()=>{
    main(input);
});

function main(input) {
    input = input.trim().split("\n");
    let z = 0;
    let testCases = +input[z++].trim();

    while(testCases--){
        let blank = input[z++];
        let [k, n, m] = input[z++].trim().split(' ').map(Number);
        let arrN = input[z++].trim().split(' ').map(Number);
        let arrM = input[z++].trim().split(' ').map(Number);

        let a = 0, b = 0;
        let lines = k;
        let result = [];
        let flag = true;
        for (let i = 0; i < n+ m; i++){
            if(arrN[a] === 0){
                result.push(arrN[a]);
                lines++;
                a++;
            }else if(arrN[a] !== 0 && arrN[a] <= lines){
                result.push(arrN[a]);
                a++;
            }
            else if(arrM[b] === 0){
                result.push(arrM[b]);
                lines++;
                b++;
            }else if(arrM[b] !== 0 && arrM[b] <= lines){
                result.push(arrM[b]);
                b++;
            }
            else{
                flag = false;
            }
        }
        let ans = flag ? result : [-1];
        console.log(...ans);
    }
}

var readline = require('readline');

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

function solve(k, n, m, a1, a2) {
    // console.log(a1, a2)
    let i = 0
    let j = 0
    const r = []
    while (i < n && j < m) {
        const b1 = a1[i] && a1[i] > k
        const b2 = a2[j] && a2[j] > k
        if (b1 && b2) {
            return -1
        } else if (b1) {
            if (!a2[j]) k++
            r.push(a2[j++])
        } else if (b2) {
            if (!a1[i]) k++
            r.push(a1[i++])
        } else {
            if (!a1[i]) k++
            if (!a2[j]) k++
            r.push(a1[i++])
            r.push(a2[j++])
        }
    }
    while (i < n) {
        if (a1[i] > k) return -1
        if (!a1[i]) k++
        r.push(a1[i++])
    }
    while (j < m) {
        if (a2[j] > k) return -1
        if (!a2[j]) k++
        r.push(a2[j++])
    }
    return r.join(' ')
}

process.stdin.resume();

process.stdin.setEncoding('utf8');

var input = '';

process.stdin.on('data' , data=>{
    input += data;
});
process.stdin.on('end' , ()=>{
    main(input);
});

function main(input) {
    input = input.trim().split("\n");
    let z = 0;
    let testCases = +input[z++].trim();

    while(testCases--){
        let blank = input[z++];
        let [k, n, m] = input[z++].trim().split(' ').map(Number);
        let arrN = input[z++].trim().split(' ').map(Number);
        let arrM = input[z++].trim().split(' ').map(Number);

        let line = +k;
        for (let i = 0; i < n; i++) {
            if(arrN[i] === 0) line++;
        }
        for (let i = 0; i < m; i++) {
            if(arrM[i] === 0) line++;
        }

        let maxN = Math.max(...arrN);
        let maxM = Math.max(...arrM);
        let max = Math.max(maxM, maxN);

        if(line >= max){
            let result = [];
            let counter = 0;
            for (let i = 0; i < n+ m; i++){
                if(arrN[counter] < arrM[counter]){
                    result.push(arrN[counter]);
                    result.push(arrM[counter]);
                }else{
                    result.push(arrM[counter]);
                    result.push(arrN[counter]);
                }
                counter++;
            }
            result = result.filter(x=>x!= undefined);
            console.log(...result);
        }
        else{
            console.log(-1);
        }
    }
}

process.stdin.resume();

process.stdin.setEncoding('utf8');

var input = '';

process.stdin.on('data' , data=>{
    input += data;
});
process.stdin.on('end' , ()=>{
    main(input);
});

function main(input) {
    input = input.trim().split("\n");
    let z = 0;
    let testCases = +input[z++].trim();

    while(testCases--){
        let blank = input[z++];
        let [k, n, m] = input[z++].trim().split(' ').map(Number);
        let arrN = input[z++].trim().split(' ').map(Number);
        let arrM = input[z++].trim().split(' ').map(Number);

        let line = +k;
        for (let i = 0; i < n; i++) {
            if(arrN[i] === 0) line++;
        }
        for (let i = 0; i < m; i++) {
            if(arrM[i] === 0) line++;
        }

        let maxN = Math.max(...arrN);
        let maxM = Math.max(...arrM);
        let max = Math.max(maxM, maxN);

        if(line >= max){
            let result = [];
            let counter = 0;
            for (let i = 0; i < n+ m; i+=2){
                if(arrN[counter] < arrM[counter]){
                    result.push(arrN[counter]);
                    result.push(arrM[counter]);
                }else{
                    result.push(arrM[counter]);
                    result.push(arrN[counter]);
                }
                counter++;
            }
            result = result.filter(x=>x!= undefined);
            console.log(...result);
        }
        else{
            console.log(-1);
        }
    }
}

var readline = require('readline');

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

function solve(k, n, m, a1, a2) {
    // console.log(a1, a2)
    let i = 0
    let j = 0
    const r = []
    while (i < n && j < m) {
        const b1 = a1[i] && a1[i] > k
        const b2 = a2[j] && a2[j] > k
        if (b1 && b2) {
            return -1
        } else if (b1) {
            if (!a2[j]) k++
            r.push(a2[j++])
        } else if (b2) {
            if (!a1[i]) k++
            r.push(a1[i++])
        } else {
            if (!a1[i]) k++
            if (!a2[j]) k++
            r.push(a1[i++])
            r.push(a2[j++])
        }
    }
    while (i < n) {
        if (a1[i] > k) return -1
        if (!a1[i]) k++
        r.push(a1[i++])
    }
    while (j < m) {
        if (a2[j] > k) return -1
        r.push(a2[j++])
        r.push(a2[j++])
    }
    return r.join(' ')
}

var readline = require('readline');

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

function solve(k, n, m, a1, a2) {
    // console.log(a1, a2)
    let i = 0
    let j = 0
    const r = []
    while (i < n && j < m) {
        const b1 = a1[i] && a1[i] > k
        const b2 = a2[j] && a2[j] > k
        if (b1 && b2) {
            return -1
        } else if (b1) {
            if (!a2[j]) k++
            r.push(a2[j++])
        } else if (b2) {
            if (!a1[i]) k++
            r.push(a1[i++])
        } else {
            if (!a1[i]) k++
            if (!a2[j]) k++
            r.push(a1[i++])
            r.push(a2[j++])
        }
    }
    while (i < n) {
        if (a1[i] > k) return -1
        r.push(a1[i++])
    }
    while (j < m) {
        if (a2[j] > k) return -1
        r.push(a2[j++])
    }
    return r.join(' ')
}

"use strict";

const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    readline();
    let [k, n, m] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr1 = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr2 = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let res = "";
    let i = 0,
      j = 0,
      flag = 1;
    while (i < n && j < m) {
      if (arr1[i] === 0 && arr2[j] === 0) {
        res += 0 + " " + 0 + " ";
        k += 2;
      } else if (arr1[i] === 0) {
        res += 0 + " ";
        k++;
        if (arr2[j] <= k) res += arr2[j] + " ";
        else {
          flag = 0;
          break;
        }
      } else if (arr2[j] === 0) {
        res += 0 + " ";
        k++;
        if (arr1[i] <= k) res += arr1[j] + " ";
        else {
          flag = 0;
          break;
        }
      } else {
        if (arr1[i] <= k && arr2[j] <= k) res += arr1[i] + " " + arr2[j] + " ";
        else {
          flag = 0;
          break;
        }
      }
      i++;
      j++;
    }
    if (flag === 0) {
      console.log(-1);
      continue;
    }
    while (i < n) res += arr1[i++] + " ";
    while (j < m) res += arr2[j++] + " ";
    console.log(res);
  }
};
solve();

//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] = BigInt(next());
		}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 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 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 s = next();
		var K = nextInt();
		var N = nextInt();
		var M = nextInt();
		var alist = nextIntArray(N);
		var blist = nextIntArray(M);
		var output = [];
		while(alist.length + blist.length > 0){
			if(alist.length > 0){
				if(alist[0] == 0){
					output.push(alist.shift());
					K++;
					continue;
				}else if(alist[0] - 1 <= K){
					output.push(alist.shift());
					continue;
				}
			}
			if(blist.length > 0){
				if(blist[0] == 0){
					output.push(blist.shift());
					K++;
					continue;
				}else if(blist[0] - 1 <= K){
					output.push(blist.shift());
					continue;
				}
			}
			output = -1;
			break;
		}
		if(output == -1){
			myout(output);
		}else{
			myout(myconv(output, 8));
		}
	}
}


const readline = require('readline')

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

function solve(n, arr, qs) {
    const sum = Array(n)
    sum[0] = arr[0]
    const xor = Array(n)
    xor[0] = arr[0]
    for (let i = 1; i < arr.length; i++) {
        sum[i] = sum[i - 1] + arr[i]
        xor[i] = xor[i - 1] ^ arr[i]
    }
    //
    const even = {}
    even[0] = [-1]
    const odd = {}
    let x = 0
    for (let i = 0; i < arr.length; i++) {
        x ^= arr[i]
        const [get, set] = (i & 1) ? [odd, even] : [even, odd]
        set[x] = (set[x] || [])
        ;set[x].push(i)
    }
// console.log(even, odd)
    return qs.map(([l, r]) => {
        l--; r--
        if (!rangeSum(l, r)) return 0
        if (rangeXor(l, r)) return -1
        const len = r - l + 1
        if (len & 1) return 1
        // [l, x] = 0
        const [get, set] = (r & 1) ? [odd, even] : [even, odd]
        const lst = get[xor[r]] || []
        const j = binarySearch(0, lst.length - 1, x => lst[x] <= r)
// console.log(l, r, lst, j)
        return lst[j] >= l ? ((!arr[l] || !arr[r]) ? 1 : 2) : -1
    }).join('\n')

    function rangeXor(l, r) {
        return xor[r] ^ (xor[l - 1] || 0)
    }
    function rangeSum(l, r) {
        return sum[r] - (sum[l - 1] || 0)
    }
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

'use strict';

var fs = require('fs');

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

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const [n, q] = rns(),
        a = rns(),
        b = [];
  const xorsum = [0],
        sum = [0],
        res = [];
  for (let i = 1; i <= n; i++) {
    xorsum[i] = xorsum[i - 1] ^ a[i - 1];
    sum[i] = sum[i - 1] + a[i - 1];
  }
  for (let i = 0; i < q; i++) {
    let [x, y] = rns();
    if ((xorsum[y] ^ xorsum[x - 1]) !== 0) {
      res[i] = -1;
    } else if (sum[y] - sum[x - 1] === 0) {
      res[i] = 0;
    } else {
      let d = y - x + 1;
      if (d & 1) {
        res[i] = 1;
      } else {
        b.push([x, y, i]);
      }
    }
  }
  b.sort((a, b) => a[1] - b[1]);
  let map = new Map();
  map.set(0, [0]);
  for (let i = 1, j = 0; i <= n; i++) {
    var _map$get;
    const cur = xorsum[i];
    let l = (_map$get = map.get(cur)) === null || _map$get === void 0 ? void 0 : _map$get[i & 1 ^ 1];
    while (j < b.length && b[j][1] === i) {
      const [x, y, k] = b[j];
      if (l !== undefined && l >= x) {
        if (a[x - 1] === 0 || a[y - 1] === 0) {
          res[k] = 1;
        } else {
          res[k] = 2;
        }
      } else {
        res[k] = -1;
      }
      j++;
    }
    if (!map.has(cur)) map.set(cur, []);
    map.get(cur)[i & 1] = i;
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

'use strict';

var fs = require('fs');

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

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const [n, q] = rns(),
        a = rns(),
        b = [];
  const xorsum = [0],
        sum = [0],
        res = [];
  for (let i = 1; i <= n; i++) {
    xorsum[i] = xorsum[i - 1] ^ a[i - 1];
    sum[i] = sum[i - 1] + a[i - 1];
  }
  for (let i = 0; i < q; i++) {
    let [x, y] = rns();
    if ((xorsum[y] ^ xorsum[x - 1]) !== 0) {
      res[i] = -1;
    } else if (sum[y] - sum[x - 1] === 0) {
      res[i] = 0;
    } else {
      let d = y - x + 1;
      if (d & 1) {
        res[i] = 1;
      } else {
        b.push([x, y, i]);
      }
    }
  }
  b.sort((a, b) => a[1] - b[1]);
  const map = new Map();
  map.set(0, [0]);
  for (let i = 1, j = 0; i <= n; i++) {
    var _map$get;
    const cur = xorsum[i];
    let k = i & 1 ^ 1;
    let l = (_map$get = map.get(cur)) === null || _map$get === void 0 ? void 0 : _map$get[k];
    while (j < b.length && b[j][1] === i) {
      if (l !== undefined && l > b[j][0]) {
        var _sum$l;
        if (sum[i] - ((_sum$l = sum[l]) !== null && _sum$l !== void 0 ? _sum$l : 0) === 0) {
          res[b[j][2]] = 1;
        } else {
          res[b[j][2]] = 2;
        }
      } else {
        res[b[j][2]] = -1;
      }
      j++;
    }
    if (!map.has(cur)) map.set(cur, []);
    map.get(cur)[i & 1] = i;
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

'use strict';

var fs = require('fs');

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

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const [n, q] = rns(),
        a = rns(),
        b = [];
  const xorsum = [],
        sum = [],
        res = [];
  for (let i = 0; i < n; i++) {
    var _xorsum, _sum;
    xorsum[i] = ((_xorsum = xorsum[i - 1]) !== null && _xorsum !== void 0 ? _xorsum : 0) ^ a[i];
    sum[i] = ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0) + a[i];
  }
  for (let i = 0; i < q; i++) {
    var _xorsum2, _sum2;
    let [x, y] = rns();
    x--;
    y--;
    if ((xorsum[y] ^ ((_xorsum2 = xorsum[x - 1]) !== null && _xorsum2 !== void 0 ? _xorsum2 : 0)) !== 0) {
      res[i] = -1;
    } else if (sum[y] - ((_sum2 = sum[x - 1]) !== null && _sum2 !== void 0 ? _sum2 : 0) === 0) {
      res[i] = 0;
    } else {
      let d = y - x + 1;
      if (d & 1) {
        res[i] = 1;
      } else {
        b.push([x, y, i]);
      }
    }
  }
  b.sort((a, b) => a[1] - b[1]);
  const map = new Map();
  map.set(0, [, -1]);
  for (let i = 0, j = 0; i < n; i++) {
    const cur = xorsum[i];
    let k = i & 1 ^ 1;
    while (j < b.length && b[j][1] === i) {
      var _map$get;
      let l = (_map$get = map.get(cur)) === null || _map$get === void 0 ? void 0 : _map$get[k];
      if (l !== undefined && l > b[j][0]) {
        var _sum$l;
        if (sum[i] - ((_sum$l = sum[l]) !== null && _sum$l !== void 0 ? _sum$l : 0) === 0) {
          res[b[j][2]] = 1;
        } else {
          res[b[j][2]] = 2;
        }
      } else {
        res[b[j][2]] = -1;
      }
      j++;
    }
    if (!map.has(cur)) map.set(cur, []);
    map.get(cur)[i & 1] = i;
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(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 = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, q] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        const qs = lines.slice(l, l + q).map(str => str.trim().split(' ').map(Number))
        l += q
        output[i] = solve(n, arr, qs)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr, qs) {
    const sum = Array(n)
    sum[0] = arr[0]
    const xor = Array(n)
    xor[0] = arr[0]
    for (let i = 1; i < arr.length; i++) {
        sum[i] = sum[i - 1] + arr[i]
        xor[i] = xor[i - 1] ^ arr[i]
    }
    //
    const even = {}
    even[0] = [-1]
    const odd = {}
    let x = 0
    for (let i = 0; i < arr.length; i++) {
        x ^= arr[i]
        const [get, set] = (i & 1) ? [odd, even] : [even, odd]
        set[x] = (set[x] || [])
        ;set[x].push(i)
    }
// console.log(even, odd)
    return qs.map(([l, r]) => {
        l--; r--
        if (!rangeSum(l, r)) return 0
        if (rangeXor(l, r)) return -1
        const len = r - l + 1
        if (len & 1) return 1
        // [l, x] = 0
        const [get, set] = (r & 1) ? [odd, even] : [even, odd]
        const lst = get[xor[r]] || []
        const j = binarySearch(0, lst.length - 1, x => lst[x] <= r)
// console.log(l, r, lst, j)
        return lst[j] >= l ? 2 : -1
    }).join('\n')

    function rangeXor(l, r) {
        return xor[r] ^ (xor[l - 1] || 0)
    }
    function rangeSum(l, r) {
        return sum[r] - (sum[l - 1] || 0)
    }
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}


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

var lines = [];
rl.on('line', (line) => {
  lines.push(line.trim());
  if (lines.length === 3) {
      main();
  }
}).on('close', () => {
  process.exit(0);
});

function main() {
    // parse input
    // throw away count line
    var costs = lines[1].split(" ").map(function(x) { return parseInt(x); })
    var bills = lines[2].split(" ").map(function(x) { return parseInt(x); })
    console.log(solve(costs, bills));
}

function solve(costs, bills) {
    // console.log('costs ', costs, ' bills ', bills);
    var billIndex = 0;
    var purchasedGames = 0;
    for (var i = 0; i < costs.length; i++) {
        // console.log('Comparing cost ', costs[i], ' and bill ', bills[billIndex]);
        if (bills[billIndex] >= costs[i]) {
            // console.log('can afford');
            // we can afford this game
            purchasedGames++;
            billIndex++;
            // console.log('purchased Games: ', purchasedGames, ' and billIndex: ', billIndex);
            // console.log('bills length', bills.length);
            if (billIndex === bills.length) {
                // console.log('breaking');
                // no more money left
                break;
            }
        } // else if we can't afford the game, keep looping to next cost
    }
    return purchasedGames;
}

// uncomment for testing
// console.log(solve([2,4,5,2,4], [5,3,4,6]));
// console.log(solve([20,40,50,20,40], [19,20]));
// console.log(solve([4,8,15,16,23,42], [1000,1000,1000,1000]));

// uncomment for submission
//main();

function main() {
  const is = new Scanner();
  const [n, m] = is.nextArray().map(Number);
  const games = is.nextArray();
  const bills = is.nextArray();
  for (let i = 0; i < n; i += 1) {
    games[i] = parseInt(games[i], 10);
  }
  for (let i = 0; i < bills.length; i += 1) {
    bills[i] = parseInt(bills[i], 10);
  }

  let i = 0, j = 0;
  while (i < n && j < m) {
    if (bills[j] >= games[i]) {
      j += 1;
    }
    i += 1;
  }

  console.log(j);
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

//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↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
	};
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var one = nextIntArray();
	var N = one[0];
	var M = one[1];
	var nlist = nextIntArray();
	var mlist = nextIntArray();
	var count = 0;
	for(var i = 0; i < N; i++){
		if(mlist.length == 0){
			break;
		}
		if(nlist[i] <= mlist[0]){
			count++;
			mlist.shift();
		}
	}
	myout(count);
}

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    [n, m] = d.split(' ').map(Number);
    return;
  }

  if (c === 1) {
    games = d.split(' ').map(Number);
    c++;
    return;
  }

  money = d.split(' ').map(Number);

  let ans = 0;
  let bill = 0;

  for (let i = 0; i < games.length; i++) {
    if (money[bill] >= games[i]) {
      ans++;
      bill++;
    }
  }

  console.log(ans);

  c++;
});

var n = readline().split(' ')
var c = readline().split(' ').map(Number)
var a = readline().split(' ').map(Number)

var k = 0

for(var i = 0;i < n[0];i++){
	if(c[i] <= a[k]){
		k++
	}
	if(k >= n[1]) break
}

print(k)

var k = readline().split(" ").map(function(d){
  return parseInt(d)
})

var c = readline().split(' ').map(function(d){
  return parseInt(d)
})
var a =readline().split(' ').map(function(d){
  return parseInt(d)
})
var idx = 0,counter=0;
 for(var i=0;i<c.length;i++)
    {

      if(c[i]<=a[idx]  )
        {
          counter++;
          idx++;
          if(idx==a.length){

             break;
      }
        }

    }

print(counter)

var k = readline().split(' ').map(function(d){
  return parseInt(k)
})

var c = readline().split(' ').map(function(d){
  return parseInt(k)
})
var a =readline().split(' ').map(function(d){
  return parseInt(k)
})
var idx = 0,counter=0;
 for(var i=0;i<c.length;i++)
    {

      if(c[i]<=a[idx]  )
        {
          counter++;
          idx++;
          if(idx==a.length){

             break;
      }
        }

    }

print(counter)


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

let s = "";
process.stdin.on("data", (data) => {
  s += data;
});

process.stdin.on("end", (data) => {
  s = s
    .split("\n")
    .filter(Boolean)
    .map((s) => s.split(" ").map(Number));
  main();
});

function main() {
  const tests = s[1];

  tests.forEach((num) => {
    solution(num);
  });
}

function solution(num) {
  if (num === 0) {
    console.log(0);
    return;
  }
  let min = 15;
  for (let i = 0; i < 16; i++) {
    if (min <= i) {
      break;
    }
    min = Math.min(min, i + solveForTwo(num + i, min - i));
  }
  console.log(min);
}

function solveForTwo(num, limit) {
  let twoFact = 0;
  let n = num;
  if (num % 2 ** (15 - limit) !== 0) {
    return Infinity;
  }
  n /= 2 ** (15 - limit);
  twoFact = 15 - limit;
  while (n % 2 === 0) {
    twoFact++;
    n = n / 2;
  }
  return 15 - twoFact;
}

'use strict';
 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  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 : ()=>{};

module.exports = E;

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

const MOD = 32768;

let cache = new Map();

let get_v1s = n=>{
  if (n%2)
    return [];
  n = n/2;
  let ans = [n];
  let c = n|(1<<14)
  if (c<MOD)
    ans.push(c)
  return ans;
};

const calc = (arr)=>{
  let queue = [], qi = 0;
  queue.push([0, 0])
  let m = new Map();
  m.set(0, 0)
  while (qi<queue.length){
    let [num, path] = queue[qi++];
    let v1s = get_v1s(num);
    for (let v1 of v1s){
      if (!m.has(v1)){
        queue.push([v1, path+1]);
        m.set(v1, path+1);
      }
    }
    let p2 = num==0 ? MOD-1 : num-1;
    if (!m.has(p2)){
      queue.push([p2, path+1]);
      m.set(p2, path+1);
    }
  }
  return arr.map(n=>m.get(n));
};

function main() {
    let T = 1|| +readline()
    while (T--){
      let [n] = ra();
      let a = ra();
      l('ans')
      print(calc(a).join(' '));
    }
}

E.calc = calc;

const readline = require('readline')

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

function solve(arr) {
    const dp = Array(32769).fill(Infinity)
    const q = [0, 32768]
    let d = 0
    while (q.length) {
        const nq = {}
        while (q.length) {
            const u = q.shift()
            if (d >= dp[u]) continue
            dp[u] = d

            const a = (u - 1 + 32768) % 32768
            if (d + 1 < dp[a]) nq[a] = 1
            if (!(u & 1)) {
                const b = u / 2
                if (d + 1 < dp[b]) nq[b] = 1
                const c = (u + 32768) / 2
                if (d + 1 < dp[c]) nq[c] = 1
            }
        }
        for (let k in nq) q.push(+k)
        d++
    }
    // console.log(dp.join(','))
    return arr.map(x => dp[x]).join(' ')
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
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 stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const solve = () => {
  let t = 1;
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    const helper = (num) => {
      let cnt = 0;
      while (num % 2 === 0) {
        cnt++;
        num /= 2;
      }
      return cnt;
    };
    for (let i = 0; i < n; i++) {
      if (32768 - arr[i] <= 15) console.log(32768 - arr[i]);
      else if(arr[i]===0) console.log(0);
      else {
        let a = Infinity;
        for (let j = 1, k = 0; j <= 15; j++, arr[i]++, k++) {
          let h = helper(arr[i]);
          if (h === 0) continue;
          else a = Math.min(15 - h + k, a);
        }
        console.log(a);
      }
    }
  }
};
solve();

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 memo = new Map();

const mod = 32768;

const factor2 = (num) => {
    let res = 0;
    while (num % 2 === 0) {
        res++;
        num /= 2;
    }
    return res;
};

const memo2 = new Map();

const calc = (number)=>{
    if (number === 0) return 0;

    let num2 = factor2(number);
    // if (memo2.has(number)) {
    //     num2 = memo.get(number);
    // } else {
    //     num2 = factor2(number);
    //     memo2.set(number, num2);
    // }
    // if(typeof num2 === 'undefined') console.log('DEBUG number', number);

    let res = 15 - num2;

    for (let i = 1; i <= 15; i++) {
        let curnum = number + i;
        num2 = factor2(curnum);
        // if (memo2.has(curnum)) {
        //     num2 = memo.get(curnum);
        // } else {
        //     num2 = factor2(curnum);
        //     memo2.set(curnum, num2);
        // }
        // console.log('DEBUG num2', num2);
        res = Math.min(res, i + (15 - num2));
    }

    return res;
};

function main() {
    // let T = +readline();
    // for (let t = 1; t <= T; t++){
    //     let n = +readline();
    //     let a = ra();
    //     let b = ra();
    //     console.log(`${calc(n, a, b)}`);
    // }
    let n = +readline();
    let a = ra();
    console.log(`${a.map((item) => {
        return calc(item);
    }).join(' ')}`);
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
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 stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const solve = () => {
  let t = 1;
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    const gcd = (a, b) => (a % b === 0 ? b : gcd(b, a % b));
    let ans = [];
    for (let i = 0; i < n; i++) {
      let cnt = 0;
      if (32768 - arr[i] <= 15) {
        ans.push(32768 - arr[i]);
        continue;
      }
      while (true) {
        let j = gcd(arr[i], 32768);
        if (j === 1) {
          cnt++;
          arr[i]++;
        } else {
          let k = 32768 / j;
          k = Math.log2(k);
          cnt += k;
          break;
        }
      }
      ans.push(cnt);
    }
    console.log(ans.join(" "));
  }
};
solve();

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 memo = new Map();

const mod = 32768;

const factor2 = (num) => {
    let res = 0;
    while (num % 2 === 0) {
        res++;
        num /= 2;
    }
    return res;
};

const memo2 = new Map();

const calc = (number)=>{
    if (number === 0) return 0;

    let num2 = factor2(number);
    // if (memo2.has(number)) {
    //     num2 = memo.get(number);
    // } else {
    //     num2 = factor2(number);
    //     memo2.set(number, num2);
    // }
    // if(typeof num2 === 'undefined') console.log('DEBUG number', number);

    let res = 15 - num2;

    for (let i = 1; i <= 15; i++) {
        let curnum = number + i;
        num2 = factor2(number);
        // if (memo2.has(curnum)) {
        //     num2 = memo.get(curnum);
        // } else {
        //     num2 = factor2(curnum);
        //     memo2.set(curnum, num2);
        // }
        // console.log('DEBUG num2', num2);
        res = Math.min(res, i + (15 - num2));
    }

    return res;
};

function main() {
    // let T = +readline();
    // for (let t = 1; t <= T; t++){
    //     let n = +readline();
    //     let a = ra();
    //     let b = ra();
    //     console.log(`${calc(n, a, b)}`);
    // }
    let n = +readline();
    let a = ra();
    console.log(`${a.map((item) => {
        return calc(item);
    }).join(' ')}`);
}

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 memo = new Map();

const mod = 32768;

const factor2 = (num) => {
    let res = 0;
    while (num % 2 === 0) {
        res++;
        num /= 2;
    }
    return res;
};

const memo2 = new Map();

const calc = (number)=>{
    if (number === 0) return 0;

    let num2;
    if (memo2.has(number)) {
        num2 = memo.get(number);
    } else {
        num2 = factor2(number);
        memo2.set(number, num2);
    }

    let res = 15 - num2;

    for (let i = 1; i <= 15; i++) {
        let curnum = number + i;
        if (memo2.has(curnum)) {
            num2 = memo.get(curnum);
        } else {
            num2 = factor2(curnum);
            memo2.set(curnum, num2);
        }
        res = Math.min(res, i + (15 - num2));
    }

    return res;
};

function main() {
    // let T = +readline();
    // for (let t = 1; t <= T; t++){
    //     let n = +readline();
    //     let a = ra();
    //     let b = ra();
    //     console.log(`${calc(n, a, b)}`);
    // }
    let n = +readline();
    let a = ra();
    console.log(`${a.map((item) => {
        return calc(item);
    }).join(' ')}`);
}

const readline = require('readline')

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

function solve(arr) {
    const dp = Array(32769).fill(Infinity)
    const q = [32768]
    let d = 0
    while (q.length) {
        const nq = {}
        while (q.length) {
            const u = q.shift()
            if (d >= dp[u]) continue
            dp[u] = d

            const a = (u - 1 + 32768) % 32768
            if (d + 1 < dp[a]) nq[a] = 1
            if (!(u & 1)) {
                const b = u / 2
                if (d + 1 < dp[b]) nq[b] = 1
                const c = (u + 32768) / 2
                if (d + 1 < dp[c]) nq[c] = 1
            }
        }
        for (let k in nq) q.push(+k)
        d++
    }
    return arr.map(x => dp[x]).join(' ')
}


print(function(n, m) {

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

	var a1 = 0;
	var i = 0;
	var j = 0;
	a.sort(function(a, b) {
		return a - b;
	});

	var b = [].concat(a);

	while (true) {
		if (i >= n) break;
		//if (j >= m) break;
		a1 += a[j];
		a[j]--;
		if (a[j] === 0) j++;
		i++;
	}

	var a2 = 0;
	var i = 0;
	var x = b[b.length - 1];

	out: while (true) {
		for (var j = 0; j < m; j++) {
			if (b[j] === x) {
				b[j]--;
				i++;
				a2 += x;
				if (i === n) break out;
			}
		}
		x--;
		// if (x === 0) break;
	}

	return a2 + ' ' + a1;

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

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let [passengers, plains] = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  const arr = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  let [minCount, maxCount] = [0, 0];
  const copyArr = [...arr];

  let i = 1;
  while (i <= passengers) {
    let max = Math.max(...arr);
    const maxIndex = arr.findIndex((n) => n === max);
    arr[maxIndex]--;

    const { min, minIndex } = findMin(copyArr);
    copyArr[minIndex]--;

    maxCount += max;
    minCount += min;
    i++;
  }
  console.log(`${maxCount} ${minCount}`);
}

function findMin(arr) {
  let [min, minIndex] = [Number.MAX_SAFE_INTEGER, -1];
  return arr.reduce(
    (obj, num, index) => {
      const { min, minIndex } = obj;
      if (num > 0 && num < min) {
        obj["min"] = num;
        obj["minIndex"] = index;
      }
      return obj;
    },
    { min, minIndex }
  );
}

print(function(n, m) {

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

	var a1 = 0;
	var i = 0;
	var j = 0;
	a.sort(function(a, b) {
		return a - b;
	});

	var b = [].concat(a);

	while (true) {
		if (i >= n) break;
		if (j >= m) break;
		a1 += a[j];
		a[j]--;
		if (a[j] === 0) j++;
		i++;
	}

	var a2 = 0;
	var i = 0;
	var x = b[b.length - 1];

	out: while (true) {
		for (var j = 0; j < m; j++) {
			if (b[j] === x) {
				b[j]--;
				i++;
				a2 += x;
				if (i === n) break out;
			}
		}
		x--;
		if (x === 0) break;
	}

	return a2 + ' ' + a1;

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

var nm= readline().trim().split(' ').map((x)=>parseInt(x));
var n=nm[0],m=nm[1];
var n1=n2=n;

var x = readline().trim().split(' ').map((x)=>parseInt(x));
var maxi=0,mini=0;

x.sort((a,b)=>a-b)
for(var i=0;i<x.length;i++){
    if(n1==0)
        break;
    if(n1>=x[i]){
        n1-=x[i];
        mini+=x[i]*(x[i]+1)/2;
    }else{
        mini+=x[i]*(x[i]+1)/2 -(x[i]-n1)*(x[i]-n1+1)/2;
        n1=0;
    }
}
var maxx = x[x.length-1];

var values={};
for(var i=0;i<x.length;i++){
    for(var j=1;j<=x[i];j++){
        if(values[j]==undefined)
            values[j]=0
         values[j]++
    }
}

for(var i=maxx;i>=1;i--){
    maxi+=i*Math.min(n2,values[i]);
    n2-=Math.min(n2,values[i]);
    if(n2==0)
        break;
}
print(maxi+' '+mini)

;(function () {
	print(function (n, m, a) {
		return [

			function (n, M, r) {
				while (n) {
					var t = a.filter(function (e) { return e >= M; }).length;
					if (t > n) t = n;
					r += M-- * t;
					n -= t;
				} return r;
			}(n, Math.max.apply(null, a), 0),

			function (n, r) {
				while (n) {
					var t = Math.min.apply(null, a);
					r += t * (t + 1) / 2;
					if (t > n) {
						t -= n;
						r -= t * (t + 1) / 2;
						return r;
					} else {
						n -= t;
						a.splice(a.indexOf(t), 1);
					}
				} return r;
			}(n, 0)

		].join(' ');
	}.apply(null, readline().split(' ').map(Number).concat([readline().split(' ').map(Number)])));
}).call(this);

var l = readline(),
    l2 = readline(),
    p = l2.split(' ').sort((a, b) => a - b).map(item => +item),
    p2 = l2.split(' ').sort((a, b) => a - b).map(item => +item),
    n = +l.split(' ')[0],
    cp = +l.split(' ')[1],
    min = 0,
    max = 0,
    si = 0;

for (var i = 0; i < n; i++) {
  var s = p.length - 1;
  while (p[s] < p[s - 1]) {
    var tmp = p[s - 1];
    p[s - 1] = p[s];
    p[s] = tmp;
    s--;
  }

  if (p2[si] === 0) {
    si++;
  }

  max += p[p.length - 1]--;
  min += p2[si]--;
}

//console.log(max + " " + min)
print(max + " " + min);

"use strict"
if (typeof print === 'undefined') var print = console.log;
if (typeof readline == 'undefined') {
    let id = 0, lines = require('fs').readFileSync('/dev/stdin').toString().split('\n');
    var readline = () => lines[id ++];
}

let nums = () => readline().split(' ').map(x => +x);

let t = nums(), n = t[0], m = t[1];
let a = nums(), b = [...a];

function findmin() {
    let ans = 0;
    b.sort((a, b) => a - b);
    for (let i = -1; ++i < n; ) {
        while (b.length && b[0] == 0) b.shift();
        if (!b.length) break;
        ans += b[0]--;
    }
    return ans;
}

function findmax() {
    let ans = 0;
    for (let i = -1; ++i < n; ) {
        let t = 0;
        for (let f = 0; ++f < m; )
            if (a[t] < a[f]) t = f;
        if (a[t] == 0) break;
        ans += a[t]--;
    }
    return ans;
}

print(findmax() + ' ' + findmin());

print(function(n, m) {

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

	var a1 = 0;
	var i = 0;
	var j = 0;
	a.sort(function(a, b) {
		return a - b;
	});

	var b = [].concat(a);

	while (true) {
		if (i >= n) break;
		if (j >= m) break;
		a1 += a[j];
		a[j]--;
		if (a[j] === 0) j++;
		i++;
	}

	var a2 = 0;
	var i = 0;
	var m = b[b.length - 1];
	out: while (true) {
		for (var j = 0; j < n; j++) {
			if (b[j] === m) {
				b[j]--;
				i++;
				a2 += m;
				if (i === n) break out;
			}
		}
		m--;
		if (m === 0) break;
	}

	return a2 + ' ' + a1;

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

var l = readline(),
    l2 = readline(),
    p = l2.split(' ').sort((a, b) => a - b).map(item => +item),
    p2 = l2.split(' ').sort((a, b) => a - b).map(item => +item),
    n = l.split(' ')[0],
    cp = l.split(' ')[1],
    min = 0,
    max = 0,
    si = 0,
    li = p.length - 1;

for (var i = 0; i < n; i++) {
  if (li > 0 && p[li] < p[li - 1]) {
    li--;
  } else if(li + 1 < p.length && p[li] < p[li + 1]) {
    li++
  }

  if (p2[si] === 0) {
    si++;
  }

  max += p[li]--;
  min += p2[si]--;
}

//console.log(max + " " + min)
print(max + " " + min);

"use strict"
if (typeof print === 'undefined') var print = console.log;
if (typeof readline == 'undefined') {
    let id = 0, lines = require('fs').readFileSync('/dev/stdin').toString().split('\n');
    var readline = () => lines[id ++];
}

let nums = () => readline().split(' ').map(x => +x);

let t = nums(), n = t[0], m = t[0];
let a = nums(), b = [...a];

function findmin() {
    let ans = 0;
    for (let i = -1; ++i < n; ) {
        while (b.length && b[0] == 0) b.shift();
        if (!b.length) break;
        ans += b[0]--;
    }
    return ans;
}

function findmax() {
    let ans = 0;
    for (let i = -1; ++i < n; ) {
        let t = 0;
        for (let f = 0; ++f < m; )
            if (a[t] < a[f]) t = f;
        if (a[t] == 0) break;
        ans += a[t]--;
    }
    return ans;
}

print(findmax() + ' ' + findmin());

"use strict"
if (typeof print === 'undefined') var print = console.log;
if (typeof readline == 'undefined') {
    let id = 0, lines = require('fs').readFileSync('/dev/stdin').toString().split('\n');
    var readline = () => lines[id ++];
}

let nums = () => readline().split(' ').map(x => +x);

let t = nums(), n = t[0], m = t[0];
let a = nums(), b = [...a];

function findmin() {
    let ans = 0;
    b.sort((a, b) => a - b);
    for (let i = -1; ++i < n; ) {
        while (b.length && b[0] == 0) b.shift();
        if (!b.length) break;
        ans += b[0]--;
    }
    return ans;
}

function findmax() {
    let ans = 0;
    for (let i = -1; ++i < n; ) {
        let t = 0;
        for (let f = 0; ++f < m; )
            if (a[t] < a[f]) t = f;
        if (a[t] == 0) break;
        ans += a[t]--;
    }
    return ans;
}

print(findmax() + ' ' + findmin());


function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return mid;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
let MOD = 998244353
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + MOD) % MOD;
}

// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let [n, q] = $(2), a = $(n)
  let b = Arr(n, i => ({ d: i + 1 - a[i] }))
  let fen = Array(n + 1).fill(0)
  let fenUp = (i, x) => { for (; i <= n; i += i & -i) fen[i] += x; }
  let fenDown = i => { let res = 0; for (; i; i -= i & -i) res += fen[i]; return res }
  // let c = [];
  let find = (k) => {
    // let l = 1, r = n, m;
    // while (l < r) {
    //   m = (l + r) >> 1;
    //   if (fenDown(m) < k) l = m + 1;
    //   else r = m;
    // }
    // return l
    let sum = 0, pos = 0
    for (let i = 1 << Math.log2(n) | 0; i; i >>= 1) {
      if (pos + i < n && sum + fen[pos + i] < k) {
        sum += fen[pos + i];
        pos += i;
      }
    }
    return pos + 1;
  }
  b.forEach((v, i) => {
    if (v.d == 0) {
      fenUp(i + 1, 1);
      v.p = [i];
      // c.push(i);
      return;
    }
    if (v.d < 0) return;
    let x = fenDown(i + 1);
    if (x < v.d) return;
    // log(Arr(n + 1, i => fenDown(i)).join(' '), '+', x - v.d + 1)
    x = find(x - v.d + 1);
    // log(v, x, b[x - 1])
    fenUp(x, 1);
    b[x - 1].p.push(i);
  })

  // log(b)
  fen.fill(0);
  b.forEach(v => v.p ? v.p.forEach(v => fenUp(v + 1, 1)) : 0);

  let qe = Arr(q, i => ({ i, l: $(), r: $() })).sort((q1, q2) => q1.l - q2.l)
  let li = 0;
  let remove = l => {
    while (li < l) {
      if (b[li].p) b[li].p.forEach(v => fenUp(v + 1, -1));
      li++
    }
  }
  qe.forEach(q => {
    remove(q.l)
    q.ans = fenDown(n - q.r)
  })
  log(qe.sort((q1, q2) => q1.i - q2.i).map(q => q.ans).join('\n'))
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return mid;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
let MOD = 998244353
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + MOD) % MOD;
}

// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let [n, q] = $(2), a = $(n)
  let b = Arr(n, i => ({ d: i + 1 - a[i] }))
  let fen = Array(n + 1).fill(0)
  let fenUp = (i, x) => { for (; i <= n; i += i & -i) fen[i] += x; }
  let fenDown = i => { let res = 0; for (; i; i -= i & -i) res += fen[i]; return res }
  // let c = [];
  let find = (k) => {
    let l = 1, r = n, m;
    while (l < r) {
      m = (l + r) >> 1;
      if (fenDown(m) < k) l = m + 1;
      else r = m;
    }
    return l
  }
  b.forEach((v, i) => {
    if (v.d == 0) {
      fenUp(i + 1, 1);
      v.p = [i];
      // c.push(i);
      return;
    }
    if (v.d < 0) return;
    let x = fenDown(i + 1);
    if (x < v.d) return;
    // log(Arr(n + 1, i => fenDown(i)).join(' '), '+', x - v.d + 1)
    x = find(x - v.d + 1);
    // log(v, x, b[x - 1])
    fenUp(x, 1);
    b[x - 1].p.push(i);
  })

  // log(b)
  fen.fill(0);
  b.forEach(v => v.p ? v.p.forEach(v => fenUp(v + 1, 1)) : 0);

  let qe = Arr(q, i => ({ i, l: $(), r: $() })).sort((q1, q2) => q1.l - q2.l)
  let li = 0;
  let remove = l => {
    while (li < l) {
      if (b[li].p) b[li].p.forEach(v => fenUp(v + 1, -1));
      li++
    }
  }
  qe.forEach(q => {
    remove(q.l)
    q.ans = fenDown(n - q.r)
  })
  log(qe.sort((q1, q2) => q1.i - q2.i).map(q => q.ans).join('\n'))
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return mid;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
let MOD = 998244353
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + MOD) % MOD;
}

// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let [n, q] = $(2), a = $(n)
  let b = Arr(n, i => ({ i, d: i + 1 - a[i] }))
  let fen = Array(n + 1).fill(0)
  let fenUp = (i, x) => { for (; i <= n; i += i & -i) fen[i] += x; }
  let fenDown = i => { let res = 0; for (; i; i -= i & -i) res += fen[i]; return res }
  let c = [];
  let find = (k) => {
    let l = 0, r = c.length - 1, m;
    while (l < r) {
      m = (l + r) >> 1;
      if (fenDown(c[m] + 1) < k) l = m + 1;
      else r = m;
    }
    return c[l]
  }
  b.forEach(v => {
    if (v.d == 0) {
      fenUp(v.i + 1, 1);
      v.p = [v.i];
      c.push(v.i);
      return;
    }
    if (v.d < 0) return;
    let x = fenDown(v.i + 1);
    if (x < v.d) return;
    // log(c.map(v => `(${v},${fenDown(v + 1)})`).join(' '))
    x = find(x - v.d + 1);
    // log(v, c, x, b[x])
    fenUp(x + 1, 1);
    b[x].p.push(v.i);
  })

  // log(b)
  fen.fill(0);
  b.forEach(v => v.p ? v.p.forEach(v => fenUp(v + 1, 1)) : 0);

  let qe = Arr(q, i => ({ i, l: $(), r: $() })).sort((q1, q2) => q1.l - q2.l)
  let li = 0;
  let remove = l => {
    let qu = [], x
    while (li < l) {
      if (b[li].p) b[li].p.forEach(v => fenUp(v + 1, -1));
      li++
    }
    // log(l, qu)
  }
  qe.forEach(q => {
    remove(q.l)
    // log(Arr(1, n, i => `(${i},${fenDown(i) > fenDown(i - 1) ? 1 : 0})`).join(' '))
    q.ans = fenDown(n - q.r)
  })
  log(qe.sort((q1,q2) => q1.i-q2.i).map(q=>q.ans).join('\n'))
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return mid;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
let MOD = 998244353
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + MOD) % MOD;
}

// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let [n, q] = $(2), a = $(n)
  let b = Arr(n, i => ({ d: i + 1 - a[i] }))
  let fen = Array(n + 1).fill(0)
  let fenUp = (i, x) => { for (; i <= n; i += i & -i) fen[i] += x; }
  let fenDown = i => { let res = 0; for (; i; i -= i & -i) res += fen[i]; return res }
  let c = [];
  let find = (k) => {
    let l = 0, r = c.length - 1, m;
    while (l < r) {
      m = (l + r) >> 1;
      if (fenDown(c[m] + 1) < k) l = m + 1;
      else r = m;
    }
    return c[l]
  }
  b.forEach((v, i) => {
    if (v.d == 0) {
      fenUp(i + 1, 1);
      v.p = [i];
      c.push(i);
      return;
    }
    if (v.d < 0) return;
    let x = fenDown(i + 1);
    if (x < v.d) return;
    // log(c.map(v => `(${v},${fenDown(v + 1)})`).join(' '))
    x = find(x - v.d + 1);
    // log(v, c, x, b[x])
    fenUp(x + 1, 1);
    b[x].p.push(i);
  })

  // log(b)
  fen.fill(0);
  b.forEach(v => v.p ? v.p.forEach(v => fenUp(v + 1, 1)) : 0);

  let qe = Arr(q, i => ({ i, l: $(), r: $() })).sort((q1, q2) => q1.l - q2.l)
  let li = 0;
  let remove = l => {
    while (li < l) {
      if (b[li].p) b[li].p.forEach(v => fenUp(v + 1, -1));
      li++
    }
  }
  qe.forEach(q => {
    remove(q.l)
    q.ans = fenDown(n - q.r)
  })
  log(qe.sort((q1, q2) => q1.i - q2.i).map(q => q.ans).join('\n'))
}