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

    var res = '';
    var t = read.number();
    for(var j = 0; j < t; j++) {
        var n = read.number();
        var d = read.arrNumber(' ').sort((a,b)=> b - a);

        var x = d[0] * d[n - 1];

        var check = true;

        for(var i = 1; i < Math.ceil(n/2); i++) {
            if(d[i] * d[n - 1 - i] !== x) {
                check = false;
                break;
            }
        }

        if(check) {
            var del = [];
            for(var i = d[0]; i >=2 ; i--) {
                if(x % i === 0) {
                    del.push(i);
                }
            }

            if(del.length != n) {
                check = false;
            }
            else {
                for(var i = 0; i < n;i++) {
                    if(d[i] != del[i]) {
                        check = false;
                        break;
                    }
                }
            }
        }

        if(check) {
            res += x + '\n';
        }
        else {
            res += '-1\n';
        }
    }
    print(res);
}());

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

    var res = '';
    var t = read.number();
    for(var j = 0; j < t; j++) {
        var n = read.number();
        var d = read.arrNumber(' ').sort((a,b)=> b - a);

        var x = d[0] * d[n - 1];

        var check = true;

        if(check) {
            var del = [];
            for(var i = d[0]; i >=2 ; i--) {
                if(x % i === 0) {
                    del.push(i);
                }
            }

            if(del.length != n) {
                check = false;
            }
            else {
                for(var i = 0; i < n;i++) {
                    if(d[i] != del[i]) {
                        check = false;
                        break;
                    }
                }
            }
        }

        if(check) {
            res += x + '\n';
        }
        else {
            res += '-1\n';
        }
    }
    print(res);
}());

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

    var res = '';
    var t = read.number();
    for(var j = 0; j < t; j++) {
        var n = read.number();
        var d = read.arrNumber(' ');

        var max = d[0];
        for(var i = 1;i < n; i++) {
            if(d[i] > max) {
                max = d[i];
            }
        }

        var x = max * 2;

        var check = true;
        for(var i = 0; i < n; i++) {
            if(x % d[i]) {
                check = false;
                break;
            }
        }

        if(check) {
            res += x + '\n';
        }
        else {
            res += '-1\n';
        }
    }
    print(res);
}());


// 07/02/22 night

const pr = console.log;

const preSum = (a) => { let pre = [0]; for (let i = 0; i < a.length; i++) { pre.push(pre[i] + a[i]); } return pre; };
const subArraySum = (a, l, r) => a[r + 1] - a[l];

const main = () => {
    const readLine = () => input[currentLine++];
    const ni = () => readLine() - '0';
    const nas = () => readLine().split(" ");
    const nai = () => nas().map(Number);
    const nall = () => nas().map(BigInt);
    let input = '', currentLine = 0;
    process.stdin.on('data', (stdin) => input += stdin)
    process.stdin.on('end', () => {
        input = input.split('\n');
        let [n, q] = nai(), a = nai();
        a.sort((x, y) => y - x);
        let pre = preSum(a);
        // pr(n, q, a)
        for (let i = 0; i < q; i++) {
            let [x, y] = nai();
            let r = x - 1, l = Math.max(0, x - y);
            // pr(l, r, a.slice(l, r + 1), a.slice(0, x), pre)
            let sum = subArraySum(pre, l, r);
            pr(sum);
        }
    });
};

main();

'use strict';

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

class INPUT {
    constructor() {
        this.inputString = ''
        this.curLine = 0
    }

    appendline(str) {
        this.inputString += str;
    }

    prepare() {
        this.inputString = this.inputString.split('\n').map(str => str.trim());
    }

    readline() {
        return this.inputString[this.curLine++];
    }

    readInts() {
        return this.readline().split(' ').map(x => parseInt(x, 10))
    }
}

const input = new INPUT()

process.stdin.on('data', str => {
    input.appendline(str)
});

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

function main() {
    const [n, q] = input.readInts()
    const a = input.readInts().sort((x, y) => x - y)

    for (let i = 1; i < a.length; i += 1) {
        a[i] += a[i - 1]
    }

    for (let i = 0; i < q; i += 1) {
        const [x, y] = input.readInts()
        const l = n - x
        const r = n - x + y - 1
        console.log(a[r] - (l > 0 ? a[l - 1] : 0))
    }
}

'use strict';

function solve(n, m, a, b) {
  a.sort((a, b) => a - b);
  const sum = [];
  for (let i = 0; i < n; i++) {
    var _sum;
    sum[i] = ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0) + a[i];
  }
  const res = [];
  for (let [i, [x, y]] of b.entries()) {
    if (x > n) res[i] = 0;else {
      var _sum$l;
      let l = n - x - 1,
          r = l + y;
      res[i] = sum[r] - ((_sum$l = sum[l]) !== null && _sum$l !== void 0 ? _sum$l : 0);
    }
  }
  return res.join('\n');
}

async function main(read) {
  try {
    let res = [];
    let t = 1;
    while (t--) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      const b = [];
      let tmp = m;
      while (tmp--) {
        b.push((await read()).split(' ').map(Number));
      }
      res.push(await solve(n, m, a, b));
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

// 5 3
// 5 3 1 5 2
// 3 2
// 1 1
// 5 3

var n = readline().split(" ");
var arr = readline()
	.split(" ")
	.map(function (item) {
		return +item;
	})
	.sort(function (a, b) {
		return a - b;
	})
	.reverse()
	.reduce(
		function (curent, value) {
			curent.push(curent[curent.length - 1] + value);
			return curent;
		},
		[0]
	);
var t = parseInt(n[1]);
while (t--) {
	var q = readline().split(" ");
	var x = parseInt(q[0]);
	var y = parseInt(q[1]);
	write(arr[x] - arr[x - y]);
	print();
}

// 07/02/22 night

const pr = console.log;

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

const preSum = (a) => { let pre = [0]; for (let i = 0; i < a.length; i++) { pre.push(pre[i] + a[i]); } return pre; };
const subArraySum = (a, l, r) => a[r + 1] - a[l];

const readLine = () => input[currentLine++];
const ni = () => readLine() - '0';
const nas = () => readLine().split(" ");
const nai = () => nas().map(Number);
const nall = () => nas().map(BigInt);
let input = '', currentLine = 0;
process.stdin.on('data', (stdin) => input += stdin)
process.stdin.on('end', () => {
    input = input.split('\n');
    let [n, q] = nai(), a = nai();
    a.sort((x, y) => y - x);
    let pre = preSum(a);
    // pr(n, q, a)
    for (let i = 0; i < q; i++) {
        let [x, y] = nai();
        let r = x - 1, l = Math.max(0, x - y);
        // pr(l, r, a.slice(l, r + 1), a.slice(0, x), pre)
        let sum = subArraySum(pre, l, r);
        pr(sum);
    }
});

// 07/02/22 night

const pr = console.log;

const preSum = (a) => { let pre = [0]; for (let i = 0; i < a.length; i++) { pre.push(pre[i] + a[i]); } return pre; };
const subArraySum = (a, l, r) => a[r + 1] - a[l];

const solve = (n, q, a, query) => {
    a.sort((x, y) => y - x);
    let pre = preSum(a);
    for (const [x, y] of query) {
        let r = x - 1, l = Math.max(0, x - y);
        let sum = subArraySum(pre, l, r);
        pr(sum);
    }
};

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

main()

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
function readLine() {
    return inputString[currentLine++];
};
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
    // cmd(not powershell): node cp.js < input.txt
});

function main() {
    // let t = parseInt(readLine());
    // while (t-- > 0) {
    // console.log(solve());
    // }
    solve();
}
function solve() {
    let [n, q] = readLine().split(" ").map(i => i - 0);
    let arr = readLine().split(" ").map(i => i - 0).sort((a, b) => a - b);
    let prefixsum = [0];
    for (let i = 0; i < arr.length; i++) {
        prefixsum[i + 1] = prefixsum[i] + arr[i];
    }
    while (q-- > 0) {
        let [x, y] = readLine().split(" ").map(i => i - 0);
        let l = n - x;
        let r = l + y
        console.log(prefixsum[r] - prefixsum[l]);
    }
}

'use strict';

process.stdin.resume();

class INPUT {
	constructor() {
		this.input = [];
		this.curLine = 0;
	}

	append(chunk) {
		this.input.push(chunk);
	}

	prepare() {
	    this.input = Buffer.concat(this.input).toString()
		this.input = this.input.split('\n').map((str) => str.trim());
	}

	readline() {
		return this.input[this.curLine++];
	}

	readInts() {
		return this.readline()
			.split(' ')
			.map((x) => parseInt(x, 10));
	}
}

const input = new INPUT()

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

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

function main() {
    const [n, q] = input.readInts()
    const a = input.readInts().sort((x, y) => x - y)

    for (let i = 1; i < a.length; i += 1) {
        a[i] += a[i - 1]
    }

    for (let i = 0; i < q; i += 1) {
        const [x, y] = input.readInts()
        const l = n - x
        const r = n - x + y - 1
        process.stdout.write(a[r] - (l > 0 ? a[l - 1] : 0) + "\n")
    }
}

'use strict';

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

class INPUT {
    constructor() {
        this.inputString = ''
        this.curLine = 0
    }

    appendline(str) {
        this.inputString += str;
    }

    prepare() {
        this.inputString = this.inputString.split('\n').map(str => str.trim());
    }

    readline() {
        return this.inputString[this.curLine++];
    }

    readInts() {
        return this.readline().split(' ').map(x => parseInt(x, 10))
    }
}

const input = new INPUT()

process.stdin.on('data', str => {
    input.appendline(str)
});

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

function main() {
    const [n, q] = input.readInts()
    const a = input.readInts().sort((x, y) => x - y)

    for (let i = 1; i < a.length; i += 1) {
        a[i] += a[i - 1]
    }

    for (let i = 0; i < q; i += 1) {
        const [x, y] = input.readInts()
        const l = n - x
        const r = n - x + y - 1
        process.stdout.write(a[r] - (l > 0 ? a[l - 1] : 0) + "\n")
    }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
function readLine() {
    return inputString[currentLine++];
};
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
    // cmd(not powershell): node cp.js < input.txt
});

function main() {
    // let t = parseInt(readLine());
    // while (t-- > 0) {
    solve();
    // }
}
function solve() {
    let [n, q] = readLine().split(" ").map(i => parseInt(i));
    let arr = readLine().split(" ").map(i => parseInt(i)).sort((a, b) => a - b);
    while (q-- > 0) {
        const [x, y] = readLine().split(" ").map(i => parseInt(i));
        let res = 0;
        for (let i = arr.length - x; i <= arr.length - y; i++) {
            res += arr[i];
        }
        console.log(res)
    }

}

// 5 3
// 5 3 1 5 2
// 3 2
// 1 1
// 5 3

var n = readline().split(" ");
var arr = readline()
	.split(" ")
	.map(function (item) {
		return +item;
	})
	.sort(function (a, b) {
		return a - b;
	})
	.reverse()
	.reduce(
		function (curent, value) {
			curent.push(curent[curent.length - 1] + value);
			return curent;
		},
		[0]
	);
var t = parseInt(n[1]);
while (t--) {
	var q = readline().split(" ");
	var x = parseInt(q[0]);
	var y = parseInt(q[1]);
	write(arr[x] - arr[y - 1]);
	print();
}

// 5 3
// 5 3 1 5 2
// 3 2
// 1 1
// 5 3

var n = readline().split(" ");
var arr = readline()
	.split(" ")
	.map(function (item) {
		return +item;
	})
	.sort(function (a, b) {
		return a - b;
	})
	.reverse()
	.reduce(
		function (curent, value) {
			curent.push(curent[curent.length - 1] + value);
			return curent;
		},
		[0]
	);
var t = parseInt(n[1]);
print("arr: ", arr);
while (t--) {
	var q = readline().split(" ");
	var x = parseInt(q[0]);
	var y = parseInt(q[1]);
	write(arr[x] - arr[y - 1]);
	print();
}


const readline = require('readline')

const TreeMultiSet = (function () {
var{TreeMultiSet:t}=function(t){
/*! *****************************************************************************
        Copyright (c) Microsoft Corporation.

        Permission to use, copy, modify, and/or distribute this software for any
        purpose with or without fee is hereby granted.

        THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
        REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
        AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
        INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
        LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
        OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
        PERFORMANCE OF THIS SOFTWARE.
        ***************************************************************************** */
var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)};function n(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}function r(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function o(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function i(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o<i;o++)!r&&o in e||(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}var s,u=function(){function t(t,e){this.it_=t,this.last_=e}return t.prototype.next=function(){if(this.it_.equals(this.last_))return{done:!0,value:void 0};var t=this.it_;return this.it_=this.it_.next(),{done:!1,value:t.value}},t.prototype[Symbol.iterator]=function(){return this},t}(),a=function(){function t(){}return t.prototype.empty=function(){return 0===this.size()},t.prototype.rbegin=function(){return this.end().reverse()},t.prototype.rend=function(){return this.begin().reverse()},t.prototype[Symbol.iterator]=function(){return new u(this.begin(),this.end())},t.prototype.toJSON=function(){var t,e,n=[];try{for(var o=r(this),i=o.next();!i.done;i=o.next()){var s=i.value;n.push(s)}}catch(e){t={error:e}}finally{try{i&&!i.done&&(e=o.return)&&e.call(o)}finally{if(t)throw t.error}}return n},t}(),c=function(){function t(t,e){this.data_=t,this.index_=e}return t.prototype.index=function(){return this.index_},Object.defineProperty(t.prototype,"value",{get:function(){return this.data_[this.index_]},enumerable:!1,configurable:!0}),t.prototype.prev=function(){return--this.index_,this},t.prototype.next=function(){return++this.index_,this},t.prototype.advance=function(t){return this.index_+=t,this},t.prototype.equals=function(t){return this.data_===t.data_&&this.index_===t.index_},t.prototype.swap=function(t){var e,n;e=o([t.data_,this.data_],2),this.data_=e[0],t.data_=e[1],n=o([t.index_,this.index_],2),this.index_=n[0],t.index_=n[1]},t}(),_=function(t){function e(e){var n=t.call(this)||this;return n.data_=e(n),n}return n(e,t),e.prototype.assign=function(t,e){this.clear(),this.insert(t,e)},e.prototype.clear=function(){this.data_.clear()},e.prototype.begin=function(){return this.data_.begin()},e.prototype.end=function(){return this.data_.end()},e.prototype.has=function(t){return!this.find(t).equals(this.end())},e.prototype.size=function(){return this.data_.size()},e.prototype.push=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if(0===t.length)return this.size();var n=new c(t,0),r=new c(t,t.length);return this._Insert_by_range(n,r),this.size()},e.prototype.insert=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 1===t.length?this._Insert_by_key(t[0]):t[0].next instanceof Function&&t[1].next instanceof Function?this._Insert_by_range(t[0],t[1]):this._Insert_by_hint(t[0],t[1])},e.prototype.erase=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 1!==t.length||t[0]instanceof this.end().constructor&&t[0].source()===this?1===t.length?this._Erase_by_range(t[0]):this._Erase_by_range(t[0],t[1]):this._Erase_by_val(t[0])},e.prototype._Erase_by_range=function(t,e){void 0===e&&(e=t.next());var n=this.data_.erase(t,e);return this._Handle_erase(t,e),n},e}(a),l=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.insert=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return t.prototype.insert.apply(this,i([],o(e),!1))},e.prototype._Erase_by_val=function(t){var e=this.find(t);if(!0===e.equals(this.end()))return 0;for(var n=e.next(),r=1;!n.equals(this.end())&&this._Key_eq(t,n.value);)n=n.next(),++r;return this._Erase_by_range(e,n),r},e.prototype.merge=function(t){this.insert(t.begin(),t.end()),t.clear()},e}(_);!function(t){t.construct=function(t){for(var e,n,r=[],s=1;s<arguments.length;s++)r[s-1]=arguments[s];return r.length>=1&&r[0]instanceof Array?(e=function(){var e=r[0];t.push.apply(t,i([],o(e),!1))},n=r.slice(1)):r.length>=2&&r[0].next instanceof Function&&r[1].next instanceof Function?(e=function(){var e=r[0],n=r[1];t.assign(e,n)},n=r.slice(2)):(e=null,n=r),{ramda:e,tail:n}}}(s||(s={}));var h=null;function p(){return null===y&&(null===h&&(h="object"==typeof global&&"object"==typeof global.process&&"object"==typeof global.process.versions&&void 0!==global.process.versions.node),void 0===(y=h?global:self).__s_iUID&&(y.__s_iUID=0)),y}var f,y=null;function v(t){if(t instanceof Object){if(!1===t.hasOwnProperty("__get_m_iUID")){var e=++p().__s_iUID;Object.defineProperty(t,"__get_m_iUID",{value:function(){return e}})}return t.__get_m_iUID()}return void 0===t?-1:0}function d(t,e){return t=t?t.valueOf():t,e=e?e.valueOf():e,t instanceof Object&&t.equals instanceof Function?t.equals(e):t===e}function g(t,e){return t=t.valueOf(),e=e.valueOf(),t instanceof Object?t.less instanceof Function?t.less(e):v(t)<v(e):t<e}function b(t,e){return e^=t?1:0,e*=k}function m(t,e){return x(t.toString(),e)}function x(t,e){for(var n=0;n<t.length;++n)e^=t.charCodeAt(n),e*=k;return Math.abs(e)}!function(t){t.construct=function(t,e,n){for(var r=[],u=3;u<arguments.length;u++)r[u-3]=arguments[u];var a=null,c=g;if(1===r.length&&r[0]instanceof e){var _=r[0];c=_.key_comp(),a=function(){var e=_.begin(),n=_.end();t.assign(e,n)}}else{var l=s.construct.apply(s,i([t],o(r),!1));a=l.ramda,l.tail.length>=1&&(c=l.tail[0])}n(c),null!==a&&a()},t.emplacable=function(t,e,n){var r=e.prev(),o=r.equals(t.end())||t.value_comp()(r.value,n);return o=o&&(e.equals(t.end())||t.value_comp()(n,e.value))}}(f||(f={}));var w,I=2166136261,k=16777619,q=function(){function t(t,e){this.first=t,this.second=e}return t.prototype.equals=function(t){return d(this.first,t.first)&&d(this.second,t.second)},t.prototype.less=function(t){return!1===d(this.first,t.first)?g(this.first,t.first):g(this.second,t.second)},t.prototype.hashCode=function(){return function(){for(var t,e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var i=I;try{for(var s=r(n),u=s.next();!u.done;u=s.next()){var a=u.value,c=typeof(a=a?a.valueOf():a);if("boolean"===c)i=b(a,i);else if("number"===c||"bigint"===c)i=m(a,i);else if("string"===c)i=x(a,i);else if(a instanceof Object&&a.hashCode instanceof Function){var _=a.hashCode();if(1===n.length)return _;i^=_,i*=k}else i=m(v(a),i)}}catch(e){t={error:e}}finally{try{u&&!u.done&&(e=s.return)&&e.call(s)}finally{if(t)throw t.error}}return Math.abs(i)}(this.first,this.second)},t}(),E=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.find=function(t){var e=this.lower_bound(t);return!e.equals(this.end())&&this._Key_eq(t,e.value)?e:this.end()},e.prototype.count=function(t){for(var e=this.find(t),n=0;!e.equals(this.end())&&this._Key_eq(e.value,t);e=e.next())++n;return n},e.prototype.equal_range=function(t){return new q(this.lower_bound(t),this.upper_bound(t))},e.prototype.value_comp=function(){return this.key_comp()},e.prototype._Key_eq=function(t,e){return!this.key_comp()(t,e)&&!this.key_comp()(e,t)},e.prototype._Insert_by_key=function(t){var e=this.upper_bound(t);return e=this.data_.insert(e,t),this._Handle_insert(e,e.next()),e},e.prototype._Insert_by_hint=function(t,e){if(f.emplacable(this,t,e)){var n=this.data_.insert(t,e);return this._Handle_insert(n,n.next()),n}return this._Insert_by_key(e)},e.prototype._Insert_by_range=function(t,e){for(var n=t;!n.equals(e);n=n.next())this._Insert_by_key(n.value)},e}(l),O=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e}(function(t){function e(e){var n=this.constructor,r=t.call(this,e)||this,o=n.prototype;return Object.setPrototypeOf?Object.setPrototypeOf(r,o):r.__proto__=o,r}return n(e,t),Object.defineProperty(e.prototype,"name",{get:function(){return this.constructor.name},enumerable:!1,configurable:!0}),e.prototype.what=function(){return this.message},e.prototype.toJSON=function(){return{name:this.name,message:this.message,stack:this.stack}},e}(Error)),F=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e}(O),S=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e}(O);!function(t){function e(t){if("string"==typeof t)return t;var e=t.constructor.name;return t.constructor.__MODULE&&(e=t.constructor.__MODULE+"."+e),"std."+e}t.get_class_name=e,t.empty=function(t,n){return new S("Error on "+e(t)+"."+n+"(): it's empty container.")},t.negative_index=function(t,n,r){return new S("Error on "+e(t)+"."+n+"(): parametric index is negative -> (index = "+r+").")},t.excessive_index=function(t,n,r,o){return new S("Error on "+e(t)+"."+n+"(): parametric index is equal or greater than size -> (index = "+r+", size: "+o+").")},t.not_my_iterator=function(t,n){return new F("Error on "+e(t)+"."+n+"(): parametric iterator is not this container's own.")},t.erased_iterator=function(t,n){return new F("Error on "+e(t)+"."+n+"(): parametric iterator, it already has been erased.")},t.negative_iterator=function(t,n,r){return new S("Error on "+e(t)+"."+n+"(): parametric iterator is directing negative position -> (index = "+r+").")},t.iterator_end_value=function(t,n){void 0===n&&(n="end");var r=e(t);return new S("Error on "+r+".Iterator.value: cannot access to the "+r+"."+n+"().value.")},t.key_nout_found=function(t,n,r){throw new S("Error on "+e(t)+"."+n+"(): unable to find the matched key -> "+r)}}(w||(w={}));var j=function(){function t(t,e,n){this.prev_=t,this.next_=e,this.value_=n}return t._Set_prev=function(t,e){t.prev_=e},t._Set_next=function(t,e){t.next_=e},t.prototype.prev=function(){return this.prev_},t.prototype.next=function(){return this.next_},Object.defineProperty(t.prototype,"value",{get:function(){return this._Try_value(),this.value_},enumerable:!1,configurable:!0}),t.prototype._Try_value=function(){if(void 0===this.value_&&!0===this.equals(this.source().end()))throw w.iterator_end_value(this.source())},t.prototype.equals=function(t){return this===t},t}(),z=function(){function t(t,e){this.index_=t,this.value_=e}return t.prototype.index=function(){return this.index_},Object.defineProperty(t.prototype,"value",{get:function(){return this.value_},enumerable:!1,configurable:!0}),t.prototype.next=function(){return++this.index_,this},t.prototype.equals=function(t){return this.index_===t.index_},t}();var R=function(t){function e(){var e=t.call(this)||this;return e.end_=e._Create_iterator(null,null),e.clear(),e}return n(e,t),e.prototype.assign=function(t,e){this.clear(),this.insert(this.end(),t,e)},e.prototype.clear=function(){j._Set_prev(this.end_,this.end_),j._Set_next(this.end_,this.end_),this.begin_=this.end_,this.size_=0},e.prototype.resize=function(t){var e=t-this.size();e>0?this.insert(this.end(),e,void 0):e<0&&this.erase(function(t,e){if(0===e)return t;if(t.advance instanceof Function)return t.advance(e);var n;if(e<0){if(!(t.prev instanceof Function))throw new F("Error on std.advance(): parametric iterator is not a bi-directional iterator, thus advancing to negative direction is not possible.");n=function(t){return t.prev()},e=-e}else n=function(t){return t.next()};for(;e-- >0;)t=n(t);return t}(this.end(),-e),this.end())},e.prototype.begin=function(){return this.begin_},e.prototype.end=function(){return this.end_},e.prototype.size=function(){return this.size_},e.prototype.push_front=function(t){this.insert(this.begin_,t)},e.prototype.push_back=function(t){this.insert(this.end_,t)},e.prototype.pop_front=function(){if(!0===this.empty())throw w.empty(this.end_.source().constructor.name,"pop_front");this.erase(this.begin_)},e.prototype.pop_back=function(){if(!0===this.empty())throw w.empty(this.end_.source().constructor.name,"pop_back");this.erase(this.end_.prev())},e.prototype.push=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if(0===t.length)return this.size();var n=new c(t,0),r=new c(t,t.length);return this._Insert_by_range(this.end(),n,r),this.size()},e.prototype.insert=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t.source()!==this.end_.source())throw w.not_my_iterator(this.end_.source(),"insert");if(!0===t.erased_)throw w.erased_iterator(this.end_.source(),"insert");return 1===e.length?this._Insert_by_repeating_val(t,1,e[0]):2===e.length&&"number"==typeof e[0]?this._Insert_by_repeating_val(t,e[0],e[1]):this._Insert_by_range(t,e[0],e[1])},e.prototype._Insert_by_repeating_val=function(t,e,n){var r=new z(0,n),o=new z(e);return this._Insert_by_range(t,r,o)},e.prototype._Insert_by_range=function(t,e,n){for(var r=t.prev(),o=null,i=0,s=e;!1===s.equals(n);s=s.next()){var u=this._Create_iterator(r,null,s.value);0===i&&(o=u),j._Set_next(r,u),r=u,++i}return!0===t.equals(this.begin())&&(this.begin_=o),j._Set_next(r,t),j._Set_prev(t,r),this.size_+=i,o},e.prototype.erase=function(t,e){return void 0===e&&(e=t.next()),this._Erase_by_range(t,e)},e.prototype._Erase_by_range=function(t,e){if(t.source()!==this.end_.source())throw w.not_my_iterator(this.end_.source(),"insert");if(!0===t.erased_)throw w.erased_iterator(this.end_.source(),"insert");if(t.equals(this.end_))return this.end_;var n=t.prev();j._Set_next(n,e),j._Set_prev(e,n);for(var r=t;!r.equals(e);r=r.next())r.erased_=!0,--this.size_;return t.equals(this.begin_)&&(this.begin_=e),e},e.prototype.swap=function(t){var e,n,r;e=o([t.begin_,this.begin_],2),this.begin_=e[0],t.begin_=e[1],n=o([t.end_,this.end_],2),this.end_=n[0],t.end_=n[1],r=o([t.size_,this.size_],2),this.size_=r[0],t.size_=r[1]},e}(a),P=function(){function t(t){this.base_=t.prev()}return t.prototype.source=function(){return this.base_.source()},t.prototype.base=function(){return this.base_.next()},Object.defineProperty(t.prototype,"value",{get:function(){return this.base_.value},enumerable:!1,configurable:!0}),t.prototype.prev=function(){return this._Create_neighbor(this.base().next())},t.prototype.next=function(){return this._Create_neighbor(this.base_)},t.prototype.equals=function(t){return this.base_.equals(t.base_)},t}(),C=function(t){function e(e){var n=t.call(this)||this;return n.associative_=e,n}return n(e,t),e.prototype._Create_iterator=function(t,n,r){return e.Iterator.create(this,t,n,r)},e._Swap_associative=function(t,e){var n;n=o([e.associative_,t.associative_],2),t.associative_=n[0],e.associative_=n[1]},e.prototype.associative=function(){return this.associative_},e}(R);!function(t){var e=function(t){function e(e,n,r,o){var i=t.call(this,n,r,o)||this;return i.source_=e,i}return n(e,t),e.create=function(t,n,r,o){return new e(t,n,r,o)},e.prototype.reverse=function(){return new r(this)},e.prototype.source=function(){return this.source_.associative()},e}(j);t.Iterator=e;var r=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype._Create_neighbor=function(t){return new e(t)},e}(P);t.ReverseIterator=r}(C||(C={}));var M=function(){function t(t,e){this.value=t,this.color=e,this.parent=null,this.left=null,this.right=null}return Object.defineProperty(t.prototype,"grand",{get:function(){return this.parent.parent},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sibling",{get:function(){return this===this.parent.left?this.parent.right:this.parent.left},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uncle",{get:function(){return this.parent.sibling},enumerable:!1,configurable:!0}),t}(),D=function(t){function e(e,n){return t.call(this,e,n,(function(t,e){var r=n(t.value,e.value);return r||n(e.value,t.value)?r:v(t)<v(e)}))||this}return n(e,t),e.prototype.insert=function(e){v(e),t.prototype.insert.call(this,e)},e.prototype._Nearest_by_key=function(t,e){if(null===this.root_)return null;for(var n=this.root_,r=null;;){var o=n.value,i=null;if(this.key_comp()(t,o.value)?i=n.left:this.key_comp()(o.value,t)?i=n.right:(r=n,i=e(n)),null===i)break;n=i}return null!==r?r:n},e.prototype.nearest_by_key=function(t){return this._Nearest_by_key(t,(function(t){return t.left}))},e.prototype.upper_bound=function(t){var e=this._Nearest_by_key(t,(function(t){return t.right}));if(null===e)return this.source().end();var n=e.value;return this.key_comp()(t,n.value)?n:n.next()},e}(function(t){function e(e,n,r){var o=t.call(this,r)||this;return o.source_=e,o.key_comp_=n,o.key_eq_=function(t,e){return!n(t,e)&&!n(e,t)},o}return n(e,t),e._Swap_source=function(t,e){var n;n=o([e.source_,t.source_],2),t.source_=n[0],e.source_=n[1]},e.prototype.get_by_key=function(t){var e=this.nearest_by_key(t);return null!==e&&this.key_eq_(t,e.value.value)?e:null},e.prototype.lower_bound=function(t){var e=this.nearest_by_key(t);return null===e?this.source_.end():this.key_comp_(e.value.value,t)?e.value.next():e.value},e.prototype.equal_range=function(t){return new q(this.lower_bound(t),this.upper_bound(t))},e.prototype.source=function(){return this.source_},e.prototype.key_comp=function(){return this.key_comp_},e.prototype.key_eq=function(){return this.key_eq_},e.prototype.value_comp=function(){return this.key_comp_},e}(function(){function t(t){this.root_=null,this.comp_=t,this.equal_=function(e,n){return!t(e,n)&&!t(n,e)}}return t.prototype.clear=function(){this.root_=null},t.prototype.root=function(){return this.root_},t.prototype.get=function(t){var e=this.nearest(t);return null!==e&&this.equal_(t,e.value)?e:null},t.prototype.nearest=function(t){if(null===this.root_)return null;for(var e=this.root_;;){var n=null;if(this.comp_(t,e.value))n=e.left;else{if(!this.comp_(e.value,t))return e;n=e.right}if(null===n)break;e=n}return e},t.prototype._Fetch_maximum=function(t){for(;null!==t.right;)t=t.right;return t},t.prototype.insert=function(t){var e=this.nearest(t),n=new M(t,1);null===e?this.root_=n:(n.parent=e,this.comp_(n.value,e.value)?e.left=n:e.right=n),this._Insert_case1(n)},t.prototype._Insert_case1=function(t){null===t.parent?t.color=0:this._Insert_case2(t)},t.prototype._Insert_case2=function(t){0!==this._Fetch_color(t.parent)&&this._Insert_case3(t)},t.prototype._Insert_case3=function(t){1===this._Fetch_color(t.uncle)?(t.parent.color=0,t.uncle.color=0,t.grand.color=1,this._Insert_case1(t.grand)):this._Insert_case4(t)},t.prototype._Insert_case4=function(t){t===t.parent.right&&t.parent===t.grand.left?(this._Rotate_left(t.parent),t=t.left):t===t.parent.left&&t.parent===t.grand.right&&(this._Rotate_right(t.parent),t=t.right),this._Insert_case5(t)},t.prototype._Insert_case5=function(t){t.parent.color=0,t.grand.color=1,t===t.parent.left&&t.parent===t.grand.left?this._Rotate_right(t.grand):this._Rotate_left(t.grand)},t.prototype.erase=function(t){var e=this.get(t);if(null!==e){if(null!==e.left&&null!==e.right){var n=this._Fetch_maximum(e.left);e.value=n.value,e=n}var r=null===e.right?e.left:e.right;0===this._Fetch_color(e)&&(e.color=this._Fetch_color(r),this._Erase_case1(e)),this._Replace_node(e,r),1===this._Fetch_color(this.root_)&&(this.root_.color=0)}},t.prototype._Erase_case1=function(t){null!==t.parent&&this._Erase_case2(t)},t.prototype._Erase_case2=function(t){1===this._Fetch_color(t.sibling)&&(t.parent.color=1,t.sibling.color=0,t===t.parent.left?this._Rotate_left(t.parent):this._Rotate_right(t.parent)),this._Erase_case3(t)},t.prototype._Erase_case3=function(t){0===this._Fetch_color(t.parent)&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,this._Erase_case1(t.parent)):this._Erase_case4(t)},t.prototype._Erase_case4=function(t){1===this._Fetch_color(t.parent)&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,t.parent.color=0):this._Erase_case5(t)},t.prototype._Erase_case5=function(t){t===t.parent.left&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&1===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,t.sibling.left.color=0,this._Rotate_right(t.sibling)):t===t.parent.right&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&1===this._Fetch_color(t.sibling.right)&&(t.sibling.color=1,t.sibling.right.color=0,this._Rotate_left(t.sibling)),this._Erase_case6(t)},t.prototype._Erase_case6=function(t){t.sibling.color=this._Fetch_color(t.parent),t.parent.color=0,t===t.parent.left?(t.sibling.right.color=0,this._Rotate_left(t.parent)):(t.sibling.left.color=0,this._Rotate_right(t.parent))},t.prototype._Rotate_left=function(t){var e=t.right;this._Replace_node(t,e),t.right=e.left,null!==e.left&&(e.left.parent=t),e.left=t,t.parent=e},t.prototype._Rotate_right=function(t){var e=t.left;this._Replace_node(t,e),t.left=e.right,null!==e.right&&(e.right.parent=t),e.right=t,t.parent=e},t.prototype._Replace_node=function(t,e){null===t.parent?this.root_=e:t===t.parent.left?t.parent.left=e:t.parent.right=e,null!==e&&(e.parent=t.parent)},t.prototype._Fetch_color=function(t){return null===t?0:t.color},t}()));return t.TreeMultiSet=function(t){function e(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var s=t.call(this,(function(t){return new C(t)}))||this;return f.construct.apply(f,i([s,e,function(t){s.tree_=new D(s,t)}],o(n),!1)),s}return n(e,t),e.prototype.clear=function(){t.prototype.clear.call(this),this.tree_.clear()},e.prototype.swap=function(t){var e,n;e=o([t.data_,this.data_],2),this.data_=e[0],t.data_=e[1],C._Swap_associative(this.data_,t.data_),D._Swap_source(this.tree_,t.tree_),n=o([t.tree_,this.tree_],2),this.tree_=n[0],t.tree_=n[1]},e.prototype.key_comp=function(){return this.tree_.key_comp()},e.prototype.lower_bound=function(t){return this.tree_.lower_bound(t)},e.prototype.upper_bound=function(t){return this.tree_.upper_bound(t)},e.prototype._Handle_insert=function(t,e){for(;!t.equals(e);t=t.next())this.tree_.insert(t)},e.prototype._Handle_erase=function(t,e){for(;!t.equals(e);t=t.next())this.tree_.erase(t)},e}(E),function(t){t.Iterator=C.Iterator,t.ReverseIterator=C.ReverseIterator}(t.TreeMultiSet||(t.TreeMultiSet={})),Object.defineProperty(t,"__esModule",{value:!0}),t}({});

return t
})();

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        l++
        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) {
    let max = arr[0]
    // const segs = [[arr[0], 0, 0]]
    const segs = new TreeMultiSet((a, b) => a[1] < b[1])
    segs.insert([arr[0], 0, 0])
    arr.forEach((x, i) => {
        if (x < max) {
            // segs.push([x, i, i]) // speed, begin, end
            segs.insert([x, i, i])
            max = x
        } else {
            // segs[segs.length - 1][2] = i
            segs.rbegin().value[2] = i
        }
    })
    // printSet(segs)
// console.log(segs)
    return qs.map(([k, d]) => {
        k--
        // const idx = binarySearch(0, segs.length - 1, x => segs[x][1] <= k)
        // const last = binarySearch(idx, segs.length - 1, x => segs[x][0] >= arr[k] - d)
        const iter = segs.upper_bound([0, k, k]).prev()
        const value = iter.value
        // idx, last
        // if (arr[k] - d < segs[idx][0]) {
        if (arr[k] - d < value[0]) {
            let last = iter
            while (last.next() !== segs.end()
                    && last.next().value[0] >= arr[k] - d) {
                last = last.next()
            }
        // console.log('last', last.value)
            // const add = [arr[k] - d, k, segs[last][2]]
            const add = [arr[k] - d, k, last.value[2]]
            let start = iter
            if (value[1] < k) {
                value[2] = k - 1
                // start = idx + 1
                start = iter.next()
            }
            // segs.splice(start, last - start + 1, add)
            // console.log(
            //     start === segs.end(), last === segs.end())
            if (start !== segs.end() && start.value[1] <= last.value[1]) {
                // console.log(segs.size(), start.value, last.value)
                segs.erase(start, last.next())
            }
            segs.insert(add)
        }
        arr[k] -= d
        // console.log(segs)
        // printSet(segs)
        return segs.size()
        // return segs.length
    }).join(' ')
}
function printSet(segs) {
    let iter = segs.begin()
    const ans = []
    while (iter !== segs.end()) {
        ans.push(iter.value)
        iter = iter.next()
    }
    console.log(ans.join(' '))
}
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';

function solve(n, m, a, b) {
  const N = n - 1;
  const segTree = new SegTree(N);
  a[0];
  b = b.map(([i, num]) => [i - 1, num]);
  a[b[0][0]] -= b[0][1];
  for (let i = 0, j = 0; i < n; i = j + 1) {
    while (j + 1 < n && a[j + 1] >= a[i]) {
      j++;
    }
    segTree.update(i, j, a[i]);
  }
  const res = new Array(m);
  res[0] = segTree.query(0, N)[2];
  for (let i = 1; i < m; i++) {
    const [j, num] = b[i];
    a[j] -= num;
    segTree.update(j, n, a[j]);
    res[i] = segTree.query(0, N)[2];
  }
  return res.join(' ');
}
class SegTree {
  constructor(n) {
    this.n = n;
    this.root = this._newNode();
    this.update = (x, y, z) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      this._update(this.root, 0, n, x, y, z);
    };
    this.query = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._query(this.root, 0, n, x, y);
    };
  }
  _newNode(left = null, right = null) {
    return {
      left,
      right,
      l: Infinity,
      r: Infinity,
      count: 0,
      flag: 0
    };
  }
  _down(node, l, r) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    if (node.flag) {
      left.l = left.r = right.l = right.r = node.flag;
      left.count = right.count = 1;
      left.flag = right.flag = node.flag;
      node.flag = 0;
    }
  }
  _up(node) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    node.l = left.l;
    node.r = right.r;
    node.count = left.count + right.count;
    if (left.r === right.l) node.count--;
  }
  _update(node, l, r, x, y, z) {
    if (!node) return;
    if (node.l <= z) return;
    if (l === r) {
      node.l = z;
      node.r = z;
      node.count = 1;
      node.flag = z;
      return;
    }
    if (l === x && r === y) {
      if (node.l === node.r) {
        node.l = z;
        node.r = z;
        node.count = 1;
        node.flag = z;
        return;
      }
      if (node.r !== Infinity && node.r >= z) {
        node.l = z;
        node.r = z;
        node.count = 1;
        node.flag = z;
        return;
      }
    }
    const mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    this._down(node, l, r);
    if (y <= mid) this._update(node.left, l, mid, x, y, z);else if (x > mid) this._update(node.right, mid + 1, r, x, y, z);else this._update(node.left, l, mid, x, mid, z), this._update(node.right, mid + 1, r, mid + 1, y, z);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return [Infinity, Infinity, 0];
    if (!node) return [Infinity, Infinity, 0];
    if (node.l === node.r) return [node.l, node.r, 1];
    if (l === x && r === y) return [node.l, node.r, node.count];
    let res,
        mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    this._down(node, l, r);
    if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else {
      let res1 = this._query(node.left, l, mid, x, mid),
          res2 = this._query(node.right, mid + 1, r, mid + 1, y);
      res = [res1[0], res2[1], res1[2] + res2[2]];
      if (res1[1] === res2[0]) res[2]--;
    }
    this._up(node);
    return res;
  }
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      await read();
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      const b = [];
      let tmp = m;
      while (tmp--) {
        b.push((await read()).split(' ').map(Number));
      }
      res.push(solve(n, m, a, b));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

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

  return obj;
}

function solve(n, m, a, b) {
  const bst = new BinarySearchTree((a, b) => a[0] - b[0]);
  b = b.map(([i, num]) => [i - 1, num]);
  a[b[0][0]] -= b[0][1];
  let count = 0;
  for (let i = 0, j = 0; i < n; i = j + 1) {
    while (j + 1 < n && a[j + 1] >= a[i]) j++;
    bst.insert([i, j, a[i]]);
    count++;
  }
  const res = new Array(m);
  res[0] = count;
  for (let i = 1; i < m; i++) {
    const [j, num] = b[i];
    a[j] -= num;
    const cur = bst.floor([j, j, 0]);
    if (cur[2] > a[j]) {
      bst.delete(cur);
      if (cur[0] < j) {
        bst.insert([cur[0], j - 1, cur[2]]);
        count++;
        cur[0] = j;
      }
      cur[2] = a[j];
      let next = bst.ceiling(cur);
      while (((_next$ = (_next = next) === null || _next === void 0 ? void 0 : _next[2]) !== null && _next$ !== void 0 ? _next$ : -Infinity) >= a[j]) {
        var _next$, _next;
        count--;
        bst.delete(next);
        cur[1] = next[1];
        next = bst.ceiling(cur);
      }
      bst.insert(cur);
    }
    res[i] = count;
  }
  return res.join(' ');
}
class BinarySearchTree {
  constructor(_compare = (a, b) => a - b) {
    _defineProperty(this, "root", null);
    _defineProperty(this, "length", 0);
    _defineProperty(this, "min", null);
    _defineProperty(this, "max", null);
    _defineProperty(this, "minCache", true);
    _defineProperty(this, "maxCache", true);
    this._compare = _compare;
    this.compare = this.compare.bind(this);
  }
  isT(t) {
    return t !== undefined && t !== null;
  }
  compare(a, b) {
    const {
      isT
    } = this;
    if (isT(a) && isT(b)) return this._compare(a, b);
    if (isT(a)) return 1;
    if (isT(b)) return -1;
    return 0;
  }
  isEmpty() {
    return !this.root;
  }
  size() {
    return this.root ? this.root.size : 0;
  }
  getRoot() {
    return this.root;
  }
  getMin() {
    if (this.minCache) {
      return this.min;
    }
    const min = this.searchKth(this.size());
    this.min = min;
    this.minCache = true;
    return min;
  }
  getMax() {
    if (this.maxCache) {
      return this.max;
    }
    const max = this.searchKth(1);
    this.max = max;
    this.maxCache = true;
    return max;
  }
  balance(node) {
    node.height = this.getHeight(node);
    const blance = this.getBalance(node);
    let res;
    if (Math.abs(blance) === 2) {
      if (blance > 0) {
        var _node$left$left$heigh, _node$left, _node$left$left, _node$left$right$heig, _node$left2, _node$left2$right;
        const heightDif = ((_node$left$left$heigh = (_node$left = node.left) === null || _node$left === void 0 ? void 0 : (_node$left$left = _node$left.left) === null || _node$left$left === void 0 ? void 0 : _node$left$left.height) !== null && _node$left$left$heigh !== void 0 ? _node$left$left$heigh : 0) - ((_node$left$right$heig = (_node$left2 = node.left) === null || _node$left2 === void 0 ? void 0 : (_node$left2$right = _node$left2.right) === null || _node$left2$right === void 0 ? void 0 : _node$left2$right.height) !== null && _node$left$right$heig !== void 0 ? _node$left$right$heig : 0);
        if (heightDif > 0) {
          res = this.rotateRight(node);
        } else if (heightDif < 0) {
          res = this.rotateLeftRight(node);
        }
      } else {
        var _node$right$left$heig, _node$right, _node$right$left, _node$right$right$hei, _node$right2, _node$right2$right;
        const heightDif = ((_node$right$left$heig = (_node$right = node.right) === null || _node$right === void 0 ? void 0 : (_node$right$left = _node$right.left) === null || _node$right$left === void 0 ? void 0 : _node$right$left.height) !== null && _node$right$left$heig !== void 0 ? _node$right$left$heig : 0) - ((_node$right$right$hei = (_node$right2 = node.right) === null || _node$right2 === void 0 ? void 0 : (_node$right2$right = _node$right2.right) === null || _node$right2$right === void 0 ? void 0 : _node$right2$right.height) !== null && _node$right$right$hei !== void 0 ? _node$right$right$hei : 0);
        if (heightDif > 0) {
          res = this.rotateRightLeft(node);
        } else if (heightDif < 0) {
          res = this.rotateLeft(node);
        }
      }
    }
    return res ? res : node;
  }
  rotateRight(node) {
    const left = node.left;
    const leftRight = left.right;
    left.right = node;
    node.left = leftRight;
    node.height = this.getHeight(node);
    left.height = this.getHeight(left);
    node.size = this.getSize(node);
    left.size = this.getSize(left);
    return left;
  }
  rotateLeft(node) {
    const right = node.right;
    const rightLeft = right.left;
    right.left = node;
    node.right = rightLeft;
    node.height = this.getHeight(node);
    right.height = this.getHeight(right);
    node.size = this.getSize(node);
    right.size = this.getSize(right);
    return right;
  }
  rotateLeftRight(node) {
    node.left = this.rotateLeft(node.left);
    return this.rotateRight(node);
  }
  rotateRightLeft(node) {
    node.right = this.rotateRight(node.right);
    return this.rotateLeft(node);
  }
  getBalance(node) {
    return this.getHeight(node.left) - this.getHeight(node.right);
  }
  getHeight(node) {
    var _node$left$height, _node$left3, _node$right$height, _node$right3;
    if (!node) return 0;
    return Math.max((_node$left$height = (_node$left3 = node.left) === null || _node$left3 === void 0 ? void 0 : _node$left3.height) !== null && _node$left$height !== void 0 ? _node$left$height : 0, (_node$right$height = (_node$right3 = node.right) === null || _node$right3 === void 0 ? void 0 : _node$right3.height) !== null && _node$right$height !== void 0 ? _node$right$height : 0) + 1;
  }
  getSize(node) {
    var _node$left$size, _node$left4, _node$right$size, _node$right4;
    if (!node) return 0;
    return ((_node$left$size = (_node$left4 = node.left) === null || _node$left4 === void 0 ? void 0 : _node$left4.size) !== null && _node$left$size !== void 0 ? _node$left$size : 0) + ((_node$right$size = (_node$right4 = node.right) === null || _node$right4 === void 0 ? void 0 : _node$right4.size) !== null && _node$right$size !== void 0 ? _node$right$size : 0) + node.count;
  }
  createNode(val) {
    return {
      id: Math.random() * new Date().valueOf(),
      val,
      left: null,
      right: null,
      size: 1,
      height: 1,
      count: 1
    };
  }
  insert(val) {
    let cur = this.createNode(val);
    if (this.isEmpty()) {
      this.root = cur;
      this.length++;
    } else {
      [, cur] = this.insertNode(this.root, cur);
    }
    if (this.min === null || this.compare(this.min, val) > 0) {
      this.min = val;
    }
    if (this.max === null || this.compare(this.max, val) < 0) {
      this.max = val;
    }
  }
  insertNode(node, cur, parent = null) {
    node.size++;
    const compareResult = this.compare(cur.val, node.val);
    let res;
    if (compareResult === 0) {
      node.count++;
      return [false, node];
    } else if (compareResult > 0) {
      if (node.right) {
        res = this.insertNode(node.right, cur, node);
        if (!res[0]) return res;
      } else {
        node.right = cur;
        this.length++;
        res = [true, cur];
      }
    } else {
      if (node.left) {
        res = this.insertNode(node.left, cur, node);
        if (!res[0]) return res;
      } else {
        node.left = cur;
        this.length++;
        res = [true, cur];
      }
    }
    let preHeight = node.height;
    const newNode = this.balance(node);
    if (newNode === node && node.height === preHeight) {
      res = [false, res[1]];
    } else if (newNode !== node) {
      if (parent) {
        parent.left === node ? parent.left = newNode : parent.right = newNode;
      } else {
        this.root = newNode;
      }
      res = [false, res[1]];
    }
    return res;
  }
  delete(val) {
    if (!this.root) return;
    this.deleteNode(val, this.root, null);
  }
  deleteNode(val, node, parent) {
    if (!node) return null;
    let res = this.compare(val, node.val);
    if (res === 0) {
      node.count--;
      node.size--;
      if (node.count > 0) return node;
      if (!node.left || !node.right) {
        if (this.min === val) {
          this.minCache = false;
        }
        if (this.max === val) {
          this.maxCache = false;
        }
        this.length--;
        if (!parent) {
          var _node$left5;
          this.root = (_node$left5 = node.left) !== null && _node$left5 !== void 0 ? _node$left5 : node.right;
          return this.root;
        } else {
          var _node$left6;
          return (_node$left6 = node.left) !== null && _node$left6 !== void 0 ? _node$left6 : node.right;
        }
      } else {
        const selectLeft = node.left.height > node.right.height;
        let replaceNode = selectLeft ? this.pre(node) : this.next(node),
            name = selectLeft ? 'left' : 'right';
        node.val = replaceNode.val;
        node.count = replaceNode.count;
        replaceNode.count = 0;
        node[name] = this.deleteNode(replaceNode.val, node[name], node);
      }
    } else if (res > 0) {
      node.right = this.deleteNode(val, node.right, node);
    } else {
      node.left = this.deleteNode(val, node.left, node);
    }
    node.size = this.getSize(node);
    node.height;
    const newNode = this.balance(node);
    if (parent) {
      parent.left === node ? parent.left = newNode : parent.right = newNode;
    } else {
      this.root = newNode;
    }
    return newNode;
  }
  next(node) {
    let next = node.right;
    while ((_next2 = next) !== null && _next2 !== void 0 && _next2.left) {
      var _next2;
      next = next.left;
    }
    return next;
  }
  pre(node) {
    let pre = node.left;
    while ((_pre = pre) !== null && _pre !== void 0 && _pre.right) {
      var _pre;
      pre = pre.right;
    }
    return pre;
  }
  search(val, compare) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, compare !== null && compare !== void 0 ? compare : this.compare);
    return node.val;
  }
  searchCeilingNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        return this.searchCeilingNode(node.right, val, compare, node);
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        const [p, value] = this.searchCeilingNode(node.left, val, compare, node);
        if (compare(value.val, val) < 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    }
  }
  ceiling(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, this.compare);
    return this.compare(node.val, val) >= 0 ? node.val : null;
  }
  searchFloorNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        const [p, value] = this.searchFloorNode(node.right, val, compare, node);
        if (compare(value.val, val) > 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        return this.searchFloorNode(node.left, val, compare, node);
      } else {
        return [parent, node];
      }
    }
  }
  floor(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchFloorNode(this.root, val, this.compare);
    return this.compare(node.val, val) <= 0 ? node.val : null;
  }
  searchKth(k) {
    if (this.isEmpty()) {
      return null;
    }
    if (k <= 0 || k > this.size()) {
      return null;
    }
    const node = this.searchNodeKth(this.root, k);
    return node.val;
  }
  searchNodeKth(node, k) {
    var _node$right$size2, _node$right5, _node$right$size3, _node$right6;
    const rSize = (_node$right$size2 = (_node$right5 = node.right) === null || _node$right5 === void 0 ? void 0 : _node$right5.size) !== null && _node$right$size2 !== void 0 ? _node$right$size2 : 0;
    if (rSize === k - 1 || rSize < k && rSize + node.count >= k) return node;
    if (node.right && rSize > k - 1) return this.searchNodeKth(node.right, k);else return this.searchNodeKth(node.left, k - ((_node$right$size3 = (_node$right6 = node.right) === null || _node$right6 === void 0 ? void 0 : _node$right6.size) !== null && _node$right$size3 !== void 0 ? _node$right$size3 : 0) - node.count);
  }
  countGreaterThanEq(val) {
    if (!this.root) return 0;
    return this.countCompare(val, (a, b) => this._compare(a, b), this.root);
  }
  countCompare(val, compare, node, pre = 0) {
    const res = compare(val, node.val);
    if (res === 0) {
      var _node$right$size4, _node$right7;
      return pre + ((_node$right$size4 = (_node$right7 = node.right) === null || _node$right7 === void 0 ? void 0 : _node$right7.size) !== null && _node$right$size4 !== void 0 ? _node$right$size4 : 0) + node.count;
    } else if (res > 0) {
      if (node.right) {
        return this.countCompare(val, compare, node.right, pre);
      } else {
        return pre;
      }
    } else {
      var _node$right$size5, _node$right8;
      let count = pre + ((_node$right$size5 = (_node$right8 = node.right) === null || _node$right8 === void 0 ? void 0 : _node$right8.size) !== null && _node$right$size5 !== void 0 ? _node$right$size5 : 0) + node.count;
      if (node.left) {
        return this.countCompare(val, compare, node.left, count);
      } else {
        return count;
      }
    }
  }
  toArray() {
    if (!this.root) return [];
    const res = [];
    const dfs = node => {
      if (node.left) dfs(node.left);
      res.push(node.val);
      if (node.right) dfs(node.right);
    };
    dfs(this.root);
    return res;
  }
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      await read();
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      const b = [];
      let tmp = m;
      while (tmp--) {
        b.push((await read()).split(' ').map(Number));
      }
      res.push(solve(n, m, a, b));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

function solve(n, m, a, b) {
  const N=n-1
  const segTree = new SegTree(N);
  a[0];
  b = b.map(([i, num]) => [i - 1, num]);
  a[b[0][0]] -= b[0][1];
  for (let i = 0, j = 0; i < n; i = j + 1) {
    while (a[j + 1] >= a[i]) {
      j++;
    }
    segTree.update(i, j, a[i]);
  }
  const res = new Array(m);
  res[0] = segTree.query(0, N)[2];
  for (let i = 1; i < m; i++) {
    const [j, num] = b[i];
    a[j] -= num;
    segTree.update(j, n, a[j]);
    res[i] = segTree.query(0, N)[2];
  }
  return res.join(' ');
}
class SegTree {
  constructor(n) {
    this.n = n;
    this.root = this._newNode();
    this.update = (x, y, z) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      this._update(this.root, 0, n, x, y, z);
    };
    this.query = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._query(this.root, 0, n, x, y);
    };
  }
  _newNode(left = null, right = null) {
    return {
      left,
      right,
      l: Infinity,
      r: Infinity,
      count: 0,
      flag: 0
    };
  }
  _down(node, l, r) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    if (node.flag) {
      left.l = left.r = right.l = right.r = node.l;
      left.count = right.count = 1;
      left.flag = right.flag = node.flag;
    }
  }
  _up(node) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    node.l = left.l;
    node.r = right.r;
    node.count = left.count + right.count;
    if (left.r === right.l) node.count--;
  }
  _update(node, l, r, x, y, z) {
    if (!node) return;
    if (node.l <= z) return;
    if (l === r) {
      node.l = z;
      node.r = z;
      node.count = 1;
      node.flag = z;
      return;
    }
    if (l === x && r === y && node.r !== Infinity && node.r >= z) {
      node.l = z;
      node.r = z;
      node.count = 1;
      node.flag = z;
      return;
    }
    const mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    this._down(node, l, r);
    if (y <= mid) this._update(node.left, l, mid, x, y, z);else if (x > mid) this._update(node.right, mid + 1, r, x, y, z);else this._update(node.left, l, mid, x, mid, z), this._update(node.right, mid + 1, r, mid + 1, y, z);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return [Infinity, Infinity, 0];
    if (!node) return [Infinity, Infinity, 0];
    if (node.l === node.r) return [node.l, node.r, 1];
    if (l === x && r === y) return [node.l, node.r, node.count];
    let res,
        mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    this._down(node, l, r);
    if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else {
      let res1 = this._query(node.left, l, mid, x, mid),
          res2 = this._query(node.right, mid + 1, r, mid + 1, y);
      res = [res1[0], res2[1], res1[2] + res2[2]];
      if (res1[1] === res2[0]) res[2]--;
    }
    this._up(node);
    return res;
  }
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      await read();
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      const b = [];
      let tmp = m;
      while (tmp--) {
        b.push((await read()).split(' ').map(Number));
      }
      res.push(solve(n, m, a, b));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

function solve(n, m, a, b) {
  const segTree = new SegTree(n);
  a[0];
  b = b.map(([i, num]) => [i - 1, num]);
  a[b[0][0]] -= b[0][1];
  for (let i = 0, j = 0; i < n; i = j + 1) {
    while (a[j + 1] >= a[i]) {
      j++;
    }
    segTree.update(i, j, a[i]);
  }
  const res = new Array(m);
  res[0] = segTree.query(0, n)[2];
  for (let i = 1; i < m; i++) {
    const [j, num] = b[i];
    a[j] -= num;
    segTree.update(j, n, a[j]);
    res[i] = segTree.query(0, n)[2];
  }
  return res.join(' ');
}
class SegTree {
  constructor(n) {
    this.n = n;
    this.root = this._newNode();
    this.update = (x, y, z) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      this._update(this.root, 0, n, x, y, z);
    };
    this.query = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._query(this.root, 0, n, x, y);
    };
  }
  _newNode(left = null, right = null) {
    return {
      left,
      right,
      l: Infinity,
      r: Infinity,
      count: 0,
      flag: 0
    };
  }
  _down(node, l, r) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    if (node.flag) {
      left.l = left.r = right.l = right.r = node.flag;
      left.count = right.count = 1;
      left.flag = right.flag = node.flag;
    }
  }
  _up(node) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    node.l = left.l;
    node.r = right.r;
    node.count = left.count + right.count;
    if (left.r === right.l) node.count--;
  }
  _update(node, l, r, x, y, z) {
    if (!node) return;
    if (node.l <= z) return;
    if (l === r) {
      node.l = z;
      node.r = z;
      node.count = 1;
      node.flag = z;
      return;
    }
    if (l === x && r === y && node.r !== Infinity && node.r >= z) {
      node.l = z;
      node.r = z;
      node.count = 1;
      node.flag = z;
      return;
    }
    const mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    this._down(node, l, r);
    if (y <= mid) this._update(node.left, l, mid, x, y, z);else if (x > mid) this._update(node.right, mid + 1, r, x, y, z);else this._update(node.left, l, mid, x, mid, z), this._update(node.right, mid + 1, r, mid + 1, y, z);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return [Infinity, Infinity, 0];
    if (!node) return [Infinity, Infinity, 0];
    if (node.l === node.r) return [node.l, node.r, 1];
    if (l === x && r === y) return [node.l, node.r, node.count];
    let res,
        mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    this._down(node, l, r);
    if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else {
      let res1 = this._query(node.left, l, mid, x, mid),
          res2 = this._query(node.right, mid + 1, r, mid + 1, y);
      res = [res1[0], res2[1], res1[2] + res2[2]];
      if (res1[1] === res2[0]) res[2]--;
    }
    this._up(node);
    return res;
  }
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      await read();
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      const b = [];
      let tmp = m;
      while (tmp--) {
        b.push((await read()).split(' ').map(Number));
      }
      res.push(solve(n, m, a, b));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

function solve(n, m, a, b) {
  const segTree = new SegTree(n);
  a[0];
  b = b.map(([i, num]) => [i - 1, num]);
  a[b[0][0]] -= b[0][1];
  for (let i = 0, j = 0; i < n; i = j + 1) {
    while (a[j + 1] >= a[i]) {
      j++;
    }
    segTree.update(i, j, a[i]);
  }
  const res = new Array(m);
  res[0] = segTree.query(0, n)[2];
  for (let i = 1; i < m; i++) {
    const [j, num] = b[i];
    a[j] -= num;
    segTree.update(j, n, a[j]);
    res[i] = segTree.query(0, n)[2];
  }
  return res.join(' ');
}
class SegTree {
  constructor(n) {
    this.n = n;
    this.root = this._newNode();
    this.update = (x, y, z) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      this._update(this.root, 0, n, x, y, z);
    };
    this.query = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._query(this.root, 0, n, x, y);
    };
  }
  _newNode(left = null, right = null) {
    return {
      left,
      right,
      l: Infinity,
      r: Infinity,
      count: 0,
      flag: 0
    };
  }
  _down(node, l, r) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    if (node.flag) {
      left.l = left.r = right.l = right.r = node.l;
      left.count = right.count = 1;
      left.flag = right.flag = node.flag;
    }
  }
  _up(node) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    node.l = left.l;
    node.r = right.r;
    node.count = left.count + right.count;
    if (left.r === right.l) node.count--;
  }
  _update(node, l, r, x, y, z) {
    if (!node) return;
    if (node.l <= z) return;
    if (l === r) {
      node.l = z;
      node.r = z;
      node.count = 1;
      node.flag = z;
      return;
    }
    if (l === x && r === y && node.r !== Infinity && node.r >= z) {
      node.l = z;
      node.r = z;
      node.count = 1;
      node.flag = z;
      return;
    }
    const mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    this._down(node, l, r);
    if (y <= mid) this._update(node.left, l, mid, x, y, z);else if (x > mid) this._update(node.right, mid + 1, r, x, y, z);else this._update(node.left, l, mid, x, mid, z), this._update(node.right, mid + 1, r, mid + 1, y, z);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return [Infinity, Infinity, 0];
    if (!node) return [Infinity, Infinity, 0];
    if (node.l === node.r) return [node.l, node.r, 1];
    if (l === x && r === y) return [node.l, node.r, node.count];
    let res,
        mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    this._down(node, l, r);
    if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else {
      let res1 = this._query(node.left, l, mid, x, mid),
          res2 = this._query(node.right, mid + 1, r, mid + 1, y);
      res = [res1[0], res2[1], res1[2] + res2[2]];
      if (res1[1] === res2[0]) res[2]--;
    }
    this._up(node);
    return res;
  }
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      await read();
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      const b = [];
      let tmp = m;
      while (tmp--) {
        b.push((await read()).split(' ').map(Number));
      }
      res.push(solve(n, m, a, b));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

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

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        l++
        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) {
    let max = arr[0]
    const segs = [[arr[0], 0, 0]]
    arr.forEach((x, i) => {
        if (x < max) {
            segs.push([x, i, i]) // speed, begin, end
            max = x
        } else {
            segs[segs.length - 1][2] = i
        }
    })
// console.log(segs)
    return qs.map(([k, d]) => {
        k--
        const idx = binarySearch(0, segs.length - 1, x => segs[x][1] <= k)
        const last = binarySearch(idx, segs.length - 1, x => segs[x][0] >= arr[k] - d)
        // idx, last
        if (arr[k] - d < segs[idx][0]) {
            let start = idx
            if (segs[idx][1] < k) {
                segs[idx][2] = k - 1
                start = idx + 1
            }
            const add = [arr[k] - d, k, segs[last][2]]
            segs.splice(start, last - start + 1, add)
        }
        // console.log(segs)
        return segs.length
    }).join(' ')
}
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
}


    var s = readline().split(' ');
    var n = +s[0], k = +s[1];
    if (k>n/2)k = n - k;
    var x = 0, ans = [], t = [];
    for (var i=0; i<n; i++)
        t[i] = 0;
    function _get(r){
        var result = 0;
	for (; r >= 0; r = (r & (r+1)) - 1)
            result += t[r];
	return result;
    }
    function _inc(i, delta)
    {
	for (; i < n; i = (i | (i+1)))
            t[i] += delta;
    }
    function inc(from, to){
        _inc(from%n, 1);
        _inc(to%n, 1);
    }
    function get(from, to){
        from = from%n;
        to = to%n;
        if (to<from)
            return get(0, to)+get(from, n-1);
        return _get(to)-_get(from-1);
    }
    cur = 2;
    for (var i=0; i<n; i++)
    {
        inc(x, x+k);
        x = (x + k)%n;
        ans.push(cur);
        cur += get(x+1, x+k-1)+1;
    }
    print(ans.join(' '));

var s=readline().split(' ')
var n=+s[0]
var k=+s[1]
if (k+k>n){k=n-k;}
var x=1
var res=1
var d=1
var q=[]
for (var i=0;i<n-1;i++)
{
    if (x+k<=n)
    {
        res+=d
        x+=k
        q.push(res)
    }
    else
    {
        d++
        res+=d
        d++
        x+=k
        x-=n
        q.push(res)
    }
}
q.push(n*k+1)
print(q.join(' '))

    var s = readline().split(' ');
    var n = +s[0], k = +s[1];
    var x = 0, ans = [], t = [];
    for (var i=0; i<n; i++)
        t[i] = 0;
    function _get(r){
        var result = 0;
	for (; r >= 0; r = (r & (r+1)) - 1)
            result += t[r];
	return result;
    }
    function _inc(i, delta)
    {
	for (; i < n; i = (i | (i+1)))
            t[i] += delta;
    }
    function inc(from, to){
        _inc(from%n, 1);
        _inc(to%n, 1);
    }
    function get(from, to){
        from = from%n;
        to = to%n;
        if (to<from)
            return get(0, to)+get(from, n-1);
        return _get(to)-_get(from-1);
    }
    cur = 2;
    for (var i=0; i<n; i++)
    {
        inc(x, x+k);
        x = (x + k)%n;
        ans.push(cur);
        cur += get(x+1, x+k-1)+1;
    }
    print(ans.join(' '));


var input = readline().split(' ').map(Number), n = input[0], a = input[1], b = input[2];
var val = 1;
var flag = 0;
if (n > a * b) write('-1');
else
    while (a > 0) {
        if (flag === 0) {
            for (var i = 0; i < b; i++, val++)
                if (val > n) write('0 ');
                else write((val) + ' ');

        } else if (flag == 1) {
            if (val + b - 1 > n) write('0 ');
            else { write ((val + b - 1) + ' '); }

            for (var i = 1; i < b; i++, val++)
                if (val > n) write('0 ');
                else write((val) + ' ');
            val++;
        }
        write('\n');
        a--;
        if (b % 2 === 0) flag = 1 - flag;
    }

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

var cnt = tmp[0];
var row = tmp[1];
var col = tmp[2];

if(row * col < cnt) {print(-1); quit(0)}

var p = 1;
if(col % 2 !== 0)
{
  for(var i = 0; i < row; i++)
  {
    for(var j = 0; j < col; j++)
    {
        write((p <= cnt? p++: 0));
        if(j !== col - 1)
          write(' ');
    }
    write("\n");
  }
} else
{
  for(var i = 0; i < row; i++)
  {
      if(i % 2 === 0)
        for(var j = 0; j < col; j++)
        {
            write(p <= cnt? p++: 0);
            if(j !== col - 1)
              write(' ');
        }
      else
      {
          var s = '';
          for(var j = 0; j < col; j++)
          {
              s = (p <= cnt? p++: 0) + ' ' + s;
          }
          write(s);

      }
    write("\n");
  }
}

var input = readline().split(' ')

var n = input[0],
    a = input[1],
    b = input[2]

if (n > a * b) {

    print('-1')

} else {

    for (var i = 0, deputy = 1; i < a; i++) {
        var row = []
        var op = i % 2 === 0 ? 'push' : 'unshift'
        for (var j = 0; j < b; j++, deputy++) {
            row[op](deputy > n ? 0 : deputy)
        }
        print(row.join(' '))
    }

}

var input = readline().split(' ')
  , n = +input[0]
  , a = +input[1]
  , b = +input[2]
  , p = 0
  , result = [];

if (a * b < n) {
    print(-1);
    quit();
}
if ( b % 2 === 1 ) {
    for (var i = 0; i < a; i++ ) {
        result.push([]);
        for (var j = 0; j < b; j++ ) {
            if (p < n) {
                result[i][j] = ++p;
            } else {
                result[i][j] = 0;
            }
        }
        print(result[i].join(' '));
    }
} else {
    for (var i = 0; i < a; i++ ) {
        result.push([]);
        for (var j = 0; j < b; j++ ) {
            if (p < n) {
                result[i][j] = ++p;
            } else {
                result[i][j] = 0;
            }
        }

        if (i % 2 === 0) {
            print(result[i].join(' '));
        } else {
            print(result[i].reverse().join(' '));
        }
    }
}

var input = readline().split(' ');
var n = input[0];
var a = input[1];
var b = input[2];

if (n && a && b && n >= 1 && n <= 10000 && a >= 1 && a <= 100 && b >= 1 && b <= 100 && a * b >= n)
{
    var all = [];
    for (i = 1; i <= n; i++) all.push(i);
    for (i = 1; i <= a; i++)
    {
        var buf = all.splice(0, b);
        while (buf.length < b) buf.push(0);
        if (b%2===0 && i%2===0) buf = buf.reverse();
        print(buf.join(' '));
    }

}
else
{
    print(-1);
}

var args = readline().split(' ');
var parlament = (n, a, b) => {
  var i = 0;
  var j = 0;
  var p = 1;
  var x = a * b;
  var seats = [];
  seats[0] = [];
  if (n > x) {
    print(-1);
    return;
  }
  b--;
  a--;
  while (x--) {
    i % 2 ? seats[i][b - j] = p : seats[i][j] = p;
    j++;
    p = (p < n && p) ? ++p : 0;
    if (j === b + 1 && i !== a) {
      j = 0;
      i++;
      seats[i] = [];
    }
  }
  seats.forEach(function(item) {
    var str = '';
    item.forEach(function(item) {
      str = str + item + ' ';
    });
    print(str);
  });
};
var n = args[0];
var a = args[1];
var b = args[2];
parlament(n, a, b)

var readInt = () => parseInt(readline())
var readIntArray = () => readline().split(' ').map(item => parseInt(item))
function range(a, b) {
    var res = []
    for (var i = a; i <= b; i++) {
        res.push(i)
    }
    return res
}

var inputData = readIntArray()
var n = inputData[0]
var a = inputData[1]
var b = inputData[2]

if (n > a*b) {
    print(-1)
}
else {
    var shift = b % 2 === 0
    var k = 1
    for (var i = 0; i < a; i++) {
        var ar = range(i*b+1, (i+1)*b)
        if (shift && i % 2 !== 0) {
            var temp = ar.shift()
            ar.push(temp)
        }
        print(ar.map(m => m > n ? 0 : m).join(' '))
    }
}

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

var cnt = tmp[0];
var row = tmp[1];
var col = tmp[2];

if(row * col < cnt) {print(-1); exit(0)}

var p = 1;
if(col % 2 !== 0)
{
  for(var i = 0; i < row; i++)
  {
    for(var j = 0; j < col; j++)
    {
        write((p <= cnt? p++: 0) + ' ');
    }
    write("\n");
  }
} else
{
  for(var i = 0; i < row; i++)
  {
      if(i % 2 === 0)
        for(var j = 0; j < col; j++)
        {
            write((p <= cnt? p++: 0) + ' ');
        }
      else
      {
          p += col -1;
          for(var j = 0; j < col; j++)
          {
              write((p <= cnt? p--: 0) + ' ');
          }
          p += col +1;
      }
    write("\n");
  }
}

var input = readline().split(' ')

var n = input[0],
    a = input[1],
    b = input[2]

if (n > a * b) {
    print('-1')
} else {

    for (var i = 0, deputy = 1; i < a; i++) {
        var row = []
        for (var j = 0; j < b; j++, deputy++) {
            if (deputy > n) { row.push(0) }
            else if (i % 2 === 0) { row.push(deputy) }
            else { row.unshift(deputy) }
        }
        print(row.join(' '))
    }

}

var input = readline().split(' ')
  , n = +input[0]
  , a = +input[1]
  , b = +input[2]
  , p = 0
  , result = [];

if (a * b < n) {
    print(-1);
    quit();
}
if ( b % 2 === 1 ) {
    for (var i = 0; i < a; i++ ) {
        result.push([]);
        for (var j = 0; j < b; j++ ) {
            if (p < n) {
                result[i][j] = ++p;
            } else {
                result[i][j] = 0;
            }
        }
        print(result[i].join(' '));
    }
} else {
    for (var i = 0; i < a; i++ ) {
        result.push([]);
        for (var j = 0; j < b; j++ ) {
            if (p < n) {
                if (i % 2 === 0) {
                    result[i][j] = ++p;
                } else {
                    result[i][b-j-1] = ++p;
                }
            } else {
                result[i][j] = 0;
            }
        }
        print(result[i].join(' '));
    }
}