const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')
const N = Number(inputs[0])
inputs.shift()
main(N, inputs)
function main(N, inputs) {
  next: for (let _ = 0; _ < N; _++) {
    const n = Number(inputs[_ * 2]),
      nums = inputs[_ * 2 + 1].split(' ').map(Number)
    let has0 = nums.some(num => num === 0),
      has1 = nums.some(num => num === 1)
    if (has0 && has1) {
      console.log('NO')
    } else if (!has1) {
      console.log('YES')
    } else {
      nums.sort((a, b) => b - a)
      for (let i = 1; i < n; i++) {
        if (nums[i] === nums[i - 1] - 1) {
          console.log('NO')
          continue next
        }
      }

      console.log('YES')
    }
  }
}

const solve = (n,arr)=>{
     arr = arr.sort((a,b)=>a-b);
     if(arr[0]>=2) return "YES";
     else if(arr[0]===0){
          for(let i=1;i<n;i++)
               if(arr[i]===1) return "NO";
               else if(arr[i]>=2) break;
     }
     else{
     for(let i=1;i<n;i++){
          if(arr[i]===2) return "NO";
          else if((arr[i]-arr[i-1])===1) return "NO";
     }
     }
     return "YES";
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       console.log(solve(n,arr));
  }
}
main();

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

const EPS = 1e-6;

function main() {
    let T = +readline();
    while (T--){
      let [n] = readline().split(' ').map(a=>+a);
      let arr = readline().split(' ').map(a=>+a);
      let can_turn_all_to_0 = true
      let can_turn_all_to_1 = true
      let has_1 = false
      let all_same = true;
      for (let a of arr){
        if (arr[0]!=a)
          all_same = false;
        if (a==1)
          can_turn_all_to_0 = false;
        if (a==1)
          has_1 = true;
        if (a==2 || a==0)
          can_turn_all_to_1 = false;
      }
      if (!has_1 || all_same){
        print('yes');
      } else {
        arr.sort((a, b)=>a-b);
        let fail;
        for (let i=0; i<n-1; i++)
        {
          if (arr[i]+1==arr[i+1])
          {
            fail = true;
            break;
          }
        }
        print(!fail ? 'yes' : 'no')
      }
    }
}

const solve = (n,arr)=>{
     arr = arr.sort((a,b)=>a-b);
     let one = false;
     let consec = false;
     for(let i=0;i<n;i++){
          if(arr[i]===1) one = true;
          if((i<n-1)&&(arr[i]+1===arr[i+1])) consec = true;
     }
     return (one && consec)? "NO":"YES"
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       console.log(solve(n,arr));
  }
}
main();

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
        }else{
            var a = lines[i].split(' ').map(Number).sort(function(a, b){return a - b});
            var flag1 = 0, flag2 = 0;
            for(j = 0; j < n; j++){
                if(a[j] == 1){
                    flag1 = 1;
                }
                if(j < n - 1 && a[j + 1] - a[j] == 1){
                    flag2 = 1;
                }
            }
            console.log(flag1 && flag2 ? 'NO' : 'YES');
        }
    }
});

const solve = (n,arr)=>{
     arr = arr.sort((a,b)=>a-b);
     if(arr[0]>=2) return "YES";
     else if(arr[0]===0){
          for(let i=1;i<n;i++)
               if(arr[i]===1) return "NO";
               else if(arr[i]>=2) break;
     }
     let arr1 = [arr[0]];
     for(let i=1;i<n;i++){
          if(arr[i]===2) return "NO";
          else if((arr[i]-arr[i-1])===1) return "NO";
     }
     return "YES";
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       console.log(solve(n,arr));
  }
}
main();

const solve = (n,arr)=>{
     arr = arr.sort((a,b)=>a-b);
     if(arr[0]===0){
          let flag = 1;
          for(let i=1;i<n-1;i++){
               if((arr[i]===1)&&(arr[i+1]>=2)) return "NO";
               else if(arr[i]>=2) break;
          }
     }
     else if(arr[0]===1){
          for(let i=1;i<n;i++){
               if(arr[i]===2) return "NO";
               else if(arr[i]>2){
                    for(let j=i+1;j<n;i++){
                         if(arr[j]%arr[i]!==1) return "NO";
                    }
               }
          }
     }
     return "YES";
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       console.log(solve(n,arr));
  }
}
main();

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')
const N = Number(inputs[0])
inputs.shift()
main(N, inputs)
function main(N, inputs) {
  next: for (let _ = 0; _ < N; _++) {
    const n = Number(inputs[_ * 2]),
      nums = inputs[_ * 2 + 1].split(' ').map(Number)
    let has0 = nums.some(num => num === 0),
      has1 = nums.some(num => num === 1)
    if (has0 && has1) {
      console.log('NO')
    } else if (!has1) {
      console.log('YES')
    } else {
      nums.sort((a, b) => b - a)
      for (let i = 1; i < n; i++) {
        console.log(i, nums[i], nums[i - 1])
        if (nums[i] === nums[i - 1] - 1) {
          console.log('NO')
          continue next
        }
      }

      console.log('YES')
    }
  }
}

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')
const N = Number(inputs[0])
inputs.shift()
main(N, inputs)
function main(N, inputs) {
  next: for (let _ = 0; _ < N; _++) {
    const n = Number(inputs[_ * 2]),
      nums = inputs[_ * 2 + 1].split(' ').map(Number)
    let has0 = nums.some(num => num === 0),
      has1 = nums.some(num => num === 1)
    if (has0 && has1) {
      console.log('NO')
    } else if (!has1) {
      console.log('YES')
    } else {
      nums.sort((a, b) => b - a)
      console.log(nums, n)
      for (let i = 1; i < n; i++) {
        console.log(i, nums[i], nums[i - 1])
        if (nums[i] === nums[i - 1] - 1) {
          console.log('NO')
          continue next
        }
      }

      console.log('YES')
    }
  }
}

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

const EPS = 1e-6;

function main() {
    let T = +readline();
    while (T--){
      let [n] = readline().split(' ').map(a=>+a);
      let arr = readline().split(' ').map(a=>+a);
      let can_turn_all_to_0 = true
      let can_turn_all_to_1 = true
      let all_same = true;
      for (let a of arr){
        if (arr[0]!=a)
          all_same = false;
        if (a==1)
          can_turn_all_to_0 = false;
        if (a==2 || a==0)
          can_turn_all_to_1 = false;
      }
      print(all_same || can_turn_all_to_0 || can_turn_all_to_1 ? 'yes' : 'no')
    }
}


let i = '';
process.stdin.on('data', (c) => {
  i += c;
});
process.stdin.on('end', () => {
  const { EOL } = require('os');
  const lines = i.split(EOL);
  let count = 2;
  // console.log(lines);
  while (count < lines.length) {
    let input = lines[count].split(' ');
    input = input.map(str => parseInt(str, 10));
    canDance(input);
    count += 2;
  }
});

function canDance(arr) {
  let index = arr.indexOf(1);
  if (index === -1) {
    console.log('NO');
    return;
  }

  // clockwise
  const startIndex = index;
  let curr = 1;
  index++;
  while (index !== startIndex) {
    if (index === arr.length) index = 0;
    if (arr[index] === curr + 1) {
      curr++;
      index++;
    } else {
      break;
    }
  }

  if (index === startIndex) {
    console.log('YES');
    return;
  }

  curr = 1;
  index = startIndex - 1;
  while (index !== startIndex) {
    if (index === -1) index = arr.length - 1;
    if (arr[index] === curr + 1) {
      curr++;
      index--;
    } else {
      break;
    }
  }
  if (index === startIndex) {
    console.log('YES');
  } else {
    console.log('NO');
  }
}

'use strict'

const roundelay = (n, p) => {
    let i = 1;
    while (i < n && (p[i] === p[i-1] + 1 || p[i-1] === n && p[i] === 1)) i++;
    if (i === n) return 'YES';
    i = 1;
    while (i < n && (p[i] === p[i-1] - 1 || p[i-1] === 1 && p[i] === n)) i++;
    if (i === n) return 'YES';
    return 'NO';
}

const q = parseInt(readline());
for (let i = 0; i < q; i++) {
    write(roundelay(parseInt(readline()), readline().split(' ').map(Number)) + '\n');
}

rVal = () => +readline();
rArr = () => readline().split(' ').map(item => +item);

var q = rVal();

for(var i = 0; i < q; i++) {
  var n = rVal();
  var arr = rArr();

  if(n === 1) {
    print('YES');
    continue;
  }

  for(var j = 0; j < n; j++) {
    if(arr[j] === 1) {
      index = j;
      break;
    }
  }

  var j = 0;

  for(j = 0, k = index; j < n - 1; j++) {
    var k2 = k + 1;
    if(k2 === n) {
      k2 = 0;
    }
    if(arr[k2] - arr[k] === 1) {
      k = k2;
    } else {
      break;
    }
  }

  if(j === n - 1) {
    print('YES');
    continue;
  }

  for(var j = 0, k = index; j < n - 1; j++) {
    var k2 = k - 1;
    if(k2 < 0) {
      k2 = n - 1;
    }
    if(arr[k2] - arr[k] === 1) {
      k = k2;
    } else {
      break;
    }
  }

  if(j === n - 1) {
    print('YES');
    continue;
  }

  print('NO');
}

'use strict'

var t=Number(readline());

while(t--)
{
    var n=parseInt(readline());
    var data=readline().split(' ').map(Number);

    var start_idx=-1;
    for(var i=0;i<n;i++){
        if(data[i]==1) start_idx=i;
    }

    var flag= true;
    var clockW=start_idx;

    for(var i=1;i<n;i++){
        var tmp=data[clockW];
        clockW++;
        if(clockW>=n) clockW=0;
        if((data[clockW]-tmp)!=1){
            flag=false;
            break;
        }
    }

    if(!flag){
        flag=true;
        clockW=start_idx;

        for(var i=1;i<n;i++){
            var tmp=data[clockW];
            clockW--;
            if(clockW<0) clockW=n-1;

            if( (data[clockW]-tmp)!=1 ){
                flag=false;
                break;
            }
        }
    }

    print((flag)?"YES":"NO");
}

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

function query(arr){
    let n = arr.length;
    let arr2 = arr.concat(arr);
    let f = arr2.indexOf(1);
    for (let i=0; i<n; i++)
    {
        if (arr2[f+i]!=i+1)
            return false;
    }
    return true;
}

function main() {
    var q = +readline();
    while (q--)
    {
        var n = +readline();
        let arr = readline().split(' ').map(n=>+n);
        if (query(arr) || query(arr.reverse()))
            print('YES')
        else
            print('NO');
    }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data) {

        function can1 (data) {
            return data.reduce((agr, value, index, array) => {
                if (!agr) return false;
                if (index === array.length - 1) return agr;
                return value === array[index + 1] - 1 || array[index + 1] === 1;
            }, true);
        }

        function can0 (data) {
            return data.reduceRight((agr, value, index, array) => {
                if (!agr) return false;
                if (index === 0) return agr;
                return value === array[index - 1] - 1 || array[index - 1] === 1;
            }, true);
        }

        return can1(data) || can0(data);
    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let data = lines[testCount * 2].split(" ").map(Number);
        //console.log(data);
        let result = foo(data);
        answer += (result ? "YES" : "NO") +"\n";
        testCount++;
    }
    console.log(answer);
})

'use strict'

const roundelay = (n, p) => {
    let i = 1;
    while (i < n && (p[i] === p[i-1] + 1 || p[i-1] === n && p[i] === 1)) i++;
    if (i === n) return 'OK';
    i = 1;
    while (i < n && (p[i] === p[i-1] - 1 || p[i-1] === 1 && p[i] === n)) i++;
    if (i === n) return 'OK';
    return 'NO';
}

const q = parseInt(readline());
for (let i = 0; i < q; i++) {
    roundelay(parseInt(readline()), readline().split(' ').map(Number));
}

'use strict'

const roundelay = (n, p) => {
    let i = 1;
    while (i < n && (p[i] === p[i-1] + 1 || p[i-1] === n && p[i] === 1)) i++;
    if (i === n) return 'OK';
    i = 1;
    while (i < n && (p[i] === p[i-1] - 1 || p[i-1] === 1 && p[i] === n)) i++;
    if (i === n) return 'OK';
    return 'NO';
}

const q = parseInt(readline());
for (let i = 0; i < q; i++) {
    write(roundelay(parseInt(readline()), readline().split(' ').map(Number)) + '\n');
}


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

function alph() {
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return f;
}
function max(x,y) {
  return x >=y ? x : y;
}
function min(x,y) {
  return x <=y ? x : y;
}
function abs(x) {
  return x < 0 ? x*(-1) : x;
}
// console.log(input)
var T = readline();
// var inf = 1000000000000;
for(var tc=1;tc<=T;tc++) {
  // var nul = readline();
  var n = readline()//.split(' ').map((x) => parseInt(x));
  // var a = readline().split(' ').map((x) => parseInt(x));
  var p = readline();
  var c = []
  var f = alph();
  var mp = new Map();
  for(var i=0;i<f.length;i++) mp.set(f[i], i+1)
  for(var i=0;i<n.length;i++) {
    c.push([i, mp.get(n[i])])
  }
  c.sort(function(a, b) { return a[1] - b[1] });
  // if(tc == 1) console.log(c)
  var ans = "";
  var g = 0;
  for(var i=0;i<c.length;i++) {
    var val = c[i][1];
    if(g + val > p) {
      // if(tc == 1) console.log("p", i)
      break;
    }
    g += val;
    // ans += n[c[i][0]]
  }
  var ca = c.slice(0, i)
  ca.sort(function(a,b) { return a[0] - b[0] })
  for(var i=0;i<ca.length;i++) ans += n[ca[i][0]]
  console.log(ans)
}

const main = () => {

	var t = readInt();
	var allans = [];
	for (var zz = 0; zz < t; zz++) {
		var s = readString();
		var n = s.length;
		var p = readInt();

		var idxs = [];
		for (var i = 0; i < 27; i++)
			idxs.push([]);
		for (var i = 0; i < n; i++)
			idxs[s.charCodeAt(i) - 96].push(i);

		var total = 0;
		var takeIdx = [0];
		for (var i = 0; i < n; i++)
			takeIdx.push(0);
		for (var i = 1; i < 27; i++) {
			while (total + i <= p && idxs[i].length > 0) {
				total += i;
				takeIdx[idxs[i][idxs[i].length - 1]] = 1;
				idxs[i].pop();
			}
		}
		var ansarr = [];
		for (var i = 0; i < n; i++)
			if (takeIdx[i] === 1)
				ansarr.push(s[i]);
		var ans = ansarr.join('');
		allans.push(ans);
	}
	multiLineArrayPrint(allans);

	return;
}

const readInt = () => parseInt(readline());
const readString = () => readline();
const readIntArr = () => readline().split(" ").map(zzzz => parseInt(zzzz));
const parseLong = (string) => { // javascript's largest long is < (1<<62)
	var n = string.length;
	var res = 0;
	for (var i = 0; i < n; i++) {
		res *= 10;
		res += parseInt(string[i]);
	}
	return res;
}
const readLong = () => parseLong(readLong());
const readLongArr = () => readline().split(" ").map(zzzz => parseLong(zzzz));
const oneLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join(' '));
const multiLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join('\n'));
const multiLineArrayOfArraysPrint = (arr) => print(arr.map(yyyy => yyyy.map(zzzz => zzzz.toString()).join(' ')).join('\n'));
const makeArr = (defaultVal, dimensionsArr) => {
	var n = dimensionsArr.length;
	if (n === 1) return Array(dimensionsArr[0]).fill(defaultVal);
	else {
		var temp = [];
		for (var i = 0; i < dimensionsArr[0]; i++)
			temp.push(makeArr(defaultVal, dimensionsArr.slice(1)));
		return temp;
	}
}

for (_ = 0; _ < 1; _++) {
	main();
}

// newline for testing
 //newline for testing
// codeforces js cannot use "let" keyword. use "var" instead
// codeforces js cannot destructure arrays

T = readline()

abc = 'abcdefghijklmnopqrstuvwxyz'.split('')
obj = {}
for(i=0; i< abc.length; i++){
      obj[abc[i]] = i +1
}

while(T--){
      str = readline().split('').map(el => obj[el])
      p = readline()

      sum = str.reduce(function(acc, cur){
            return acc + cur
      }, 0)

      clone = str.slice()
      clone.sort((a, b) =>  a - b)

      while(sum > p){
            sum = sum - clone[clone.length-1]
            clone.pop()
      }

      objAns = {}
      for(i = 0; i < clone.length; i++){
            if(objAns[clone[i]] === undefined)
                  objAns[clone[i]] = 1
            else
                  objAns[clone[i]]++
      }

      strAns = []

      for(i = 0; i< str.length; i++){
            if(objAns[str[i]]){
                  objAns[str[i]]--
                  strAns.push(str[i])
            }
      }

      resultObj = {}

      Object.keys(obj).forEach(key => {
            value = obj[key]
            resultObj[value] = key
      })

      res = strAns.map(el => resultObj[el])

      print(res.join(''))
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let arr = readline().trim().split("");
    let n = arr.length;
    let k = parseInt(readline());
    let obj = {
      a: 1,
      b: 2,
      c: 3,
      d: 4,
      e: 5,
      f: 6,
      g: 7,
      h: 8,
      i: 9,
      j: 10,
      k: 11,
      l: 12,
      m: 13,
      n: 14,
      o: 15,
      p: 16,
      q: 17,
      r: 18,
      s: 19,
      t: 20,
      u: 21,
      v: 22,
      w: 23,
      x: 24,
      y: 25,
      z: 26,
    };
    let narr = [];
    for (let i = 0; i < n; i++) {
      let o = { val: obj[arr[i]], ind: i };
      narr.push(o);
    }
    narr.sort((a, b) => a.val - b.val);
    let sum = 0;
    for (let i = 0; i < n; i++) sum += narr[i].val;
    let c = {},
      i = n - 1;
    while (sum > k && i >= 0) {
      sum -= narr[i].val;
      c[narr[i].ind] = 1;
      i--;
    }
    let res = "";
    for (let i = 0; i < n; i++) {
      if (c[i]) continue;
      else res += arr[i];
    }
    console.log(res);
  }
};
solve();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let alph = [...Array(26)].map((_, i) => String.fromCharCode(i + 97));
    let price = {};
    alph.forEach((letter, i) => price[letter] = i + 1);
    let N = readline();

    for (let test = 0; test < N; test++) {
        let str = readline();
        let target = Number(readline());

        if (str === '' || target === 0) {
            output('');
            continue;
        }

        let totalCost = 0;
        let costs = str.split('').map((letter, index) => {
            totalCost += price[letter];
            return {
                originalIndex: index,
                letter: letter,
                cost: price[letter]
            };
        });
        costs.sort((a, b) => a.cost - b.cost);

        while (totalCost > target) {
            let next = costs.pop();
            totalCost -= next.cost;
        }

        costs.sort((a, b) => a.originalIndex - b.originalIndex);

        let result = costs.map(c => c.letter).join('');

        output(result);
    }
}

'use strict';

function solve(n, s) {
  const m = s.length;
  const a = new Array(m);
  for (let i = 0; i < m; i++) a[i] = s.charCodeAt(i) - 96;
  let sum = a.reduce((a, b) => a + b, 0);
  if (sum <= n) return s;
  const map = Array.from({
    length: 27
  }, () => []);
  let res = new Array(m).fill(1);
  for (let [i, num] of a.entries()) map[num].push(i);
  let i = 26;
  while (sum > n) {
    while (i >= 0 && map[i].length === 0) {
      i--;
    }
    if (map[i].length === 0) return '';
    const j = map[i].pop();
    res[j] = 0;
    sum -= i;
  }
  let ans = '';
  for (let i = 0; i < m; i++) {
    if (res[i]) ans += s[i];
  }
  return ans;
}

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

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

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	var alpha = "abcdefghijklmnopqrstuvwxyz";
	var costmap = {};
	for(var i = 0; i < alpha.length; i++){
		costmap[alpha[i]] = i + 1;
	}
	while(hasNext()){
		var S = nextCharArray();
		var N = S.length;
		var P = nextInt();
		var cost = 0;
		var map = {};
		for(var i = 0; i < N; i++){
			cost += costmap[S[i]];
			if(map[S[i]] == null){
				map[S[i]] = [];
			}
			map[S[i]].push(i);
		}
		for(var i = alpha.length - 1; i >= 0; i--){
			if(cost <= P){
				break;
			}
			if(map[alpha[i]] == null){
				continue;
			}
			var nx = map[alpha[i]];
			for(var j = 0; j < nx.length; j++){
				S[nx[j]] = "";
				cost -= costmap[alpha[i]];
				if(cost <= P){
					break;
				}
			}
		}
		myout(myconv(S, 0));
	}
}

const readline = require('readline')

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

function solve(str, p) {
    const arr = []
    for (let i = 0; i < str.length; i++) {
        const x = str.charCodeAt(i) - 'a'.charCodeAt(0) + 1
        arr.push([x, i])
    }
    arr.sort((a, b) => a[0] - b[0])
    //
    let now = 0
    const skip = {}
    for (let i = 0; i < arr.length; i++) {
        const [x, j] = arr[i]
        if (now + x > p) {
            // delete
            skip[j] = 1
        } else {
            now += x
        }
    }
    const ans = []
    for (let i = 0; i < str.length; i++) {
        if (!skip[i]) ans.push(str[i])
    }
    return ans.join('')
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let arr = readline().trim().split("");
    let n = arr.length;
    let k = parseInt(readline());
    let obj = {
      a: 1,
      b: 2,
      c: 3,
      d: 4,
      e: 5,
      f: 6,
      g: 7,
      h: 8,
      i: 9,
      j: 10,
      k: 11,
      l: 12,
      m: 13,
      n: 14,
      o: 15,
      p: 16,
      q: 17,
      r: 18,
      s: 19,
      t: 20,
      u: 21,
      v: 22,
      w: 23,
      x: 24,
      y: 25,
      z: 26,
    };
    let narr = [];
    for (let i = 0; i < n; i++) {
      let o = { val: obj[arr[i]], ind: i };
      narr.push(o);
    }
    narr.sort((a, b) => a.val - b.val);
    let sum = 0;
    for (let i = 0; i < n; i++) sum += narr[i].val;
    let c = {},
      i = n - 1;
    if (sum === k) {
      console.log("");
      continue;
    }
    while (sum > k && i >= 0) {
      sum -= narr[i].val;
      c[narr[i].ind] = 1;
      i--;
    }
    let res = "";
    for (let i = 0; i < n; i++) {
      if (c[i]) continue;
      else res += arr[i];
    }
    console.log(res);
  }
};
solve();


ln=readline().split(" ").map(x=>x*1);
n=ln[0];
a=ln[1];
b=ln[2];
seals = [];
for(i=0; i<n; i++){
    seals.push(readline().split(" ").map(x=>x*1));
}

function canFit(x1,y1,x2,y2){
    if(x1>a||x2>a||y1>b||y2>b) return false;
    ox = x1+x2>a?false:true;
    oy = y1+y2>b?false:true;
    return ox||oy;
}

ans = 0;
for(i=0; i<n-1; i++){
    for(j=i+1; j<n; j++){
        ix = seals[i][0];
        iy = seals[i][1];
        jx = seals[j][0];
        jy = seals[j][1];
        a1 = ix*iy;
        a2 = jx*jy;
        if(canFit(ix,iy, jx,jy)||canFit(iy,ix, jx,jy)||canFit(ix,iy, jy,jx)||canFit(iy,ix, jy,jx)){
            ans = ans<a1+a2?a1+a2:ans;
        }
    }
}
print(ans);

ln=readline().split(" ").map(x=>x*1);
n=ln[0];
a=ln[1];
b=ln[2];
seals = [];
for(i=0; i<n; i++){
    seals.push(readline().split(" ").map(x=>x*1));
}

function canFit(x1,y1,x2,y2){
    if(x1>a||x2>a||y1>b||y2>b) return false;
    ox = x1+x2>a?true:false;
    oy = y1+y2>b?true:false;
    return ox||oy;
}

ans = 0;
for(i=0; i<n-1; i++){
    for(j=i+1; j<n; j++){
        ix = seals[i][0];
        iy = seals[i][1];
        jx = seals[j][0];
        jy = seals[j][1];
        a1 = ix*iy;
        a2 = jx*jy;
        if(canFit(ix,iy, jx,jy)||canFit(iy,ix, jx,jy)||canFit(ix,iy, jy,jx)||canFit(iy,ix, jy,jx)){
            ans = ans<a1+a2?a1+a2:ans;
        }
    }
}
print(ans);

var rline = readline().split(" ");var xy = [rline[1],rline[2]];

var temp = [];for(var o=0;o<rline[0];o++)temp.push(readline().split(" "))
var ayinput = [];

for(var i = 0;i<temp.length;i++){
 ayinput.push((+xy[0]-(+temp[i][0]))*xy[1] + " " + (+xy[1]-(+temp[i][1]))*xy[0]);
}

var lastspace = 9005;var round = 0;var z = 0;var e = 9999;
for(var r = 0;r<ayinput.length;r++){
 var firstitem = ayinput[r].split(" ");for(var m = r+1;m<ayinput.length;m++){

var seconditem = ayinput[m].split(" ");
var fps0 = (+firstitem[z])+(+seconditem[0]);var fps1 = (+firstitem[z])+(+seconditem[1]);

if(fps0>=xy[0]*xy[1]){if((fps0<=lastspace)&&(seconditem[1]<=e) ){
    e = seconditem[1];lastspace= fps0;round =((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}

if(fps1>=xy[0]*xy[1]){if((fps1<=lastspace)&&(seconditem[0]<=e)){
    e = seconditem[0];lastspace=fps1;round = ((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}

}if(z===0){z+=1;r-=1}
}
 print(round);

    var rline = readline().split(" ");var xy = [rline[1],rline[2]];

    var temp = [];for(var o=0;o<rline[0];o++)temp.push(readline().split(" "))
    var ayinput = [];

    for(var i = 0;i<temp.length;i++){
    ayinput.push((+xy[0]-(+temp[i][0]))*xy[1] + " " + (+xy[1]-(+temp[i][1]))*xy[0]);
    }

    var lastspace = 9999999;var round = 0;var z = 0;var e = 9999999;
    for(var r = 0;r<ayinput.length;r++){
    var firstitem = ayinput[r].split(" ");for(var m = r+1;m<ayinput.length;m++){

    var seconditem = ayinput[m].split(" ");
    var fps0 = (+firstitem[z])+(+seconditem[0]);var fps1 = (+firstitem[z])+(+seconditem[1]);

    if((fps0>=xy[0]*xy[1])&&(fps0<=lastspace)){

       var s = true ;if((fps0==lastspace)&&(seconditem[1]>e)){s=false}
        if(s==true){
        e = seconditem[1];lastspace= fps0;round =((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}

    if((fps1>=xy[0]*xy[1])&&(fps1<=lastspace)){
         s = true ;if((fps1==lastspace)&&(seconditem[0]>e)){s=false}
         if(s==true){
        e = seconditem[0];lastspace=fps1;round = ((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}

    }if(z===0){z+=1;r-=1}
    }
    print(round);

var rline = readline().split(" ");var xy = [+rline[1],+rline[2]];
var round = [0];
var ayinput = [];for(var o=0;o<rline[0];o++)ayinput.push(readline().split(" "))

for(var i =0;i<ayinput.length;i++){
for(var r=i+1;r<ayinput.length;r++){kk(ayinput[i],ayinput[r])}
}

function kk(a,b){

var s1 = [xy[0] - (+a[0]) , xy[1]];var s2 = [xy[1] - (+a[1]) , xy[0]];
var s3 = [xy[0] - (+a[1]) , xy[1]];var s4 = [xy[1] - (+a[0]) , xy[0]];
var toot = [s1,s2,s3,s4];for(var x = 0;x<toot.length;x++){

if(toot[x][0]>0){

  if ((toot[x][0] >= b[0]) && (toot[x][1]>=b[0])){
    round.push((+(ayinput[i][0]*ayinput[i][1]))  +  (+(ayinput[r][0]*ayinput[r][1])))
    if(round[round.length - 1]>xy[0]*xy[1])round[round.length - 1] = 0;
          }

  if ((toot[x][1] >= b[0]) && (toot[x][0]>=b[1])){
    round.push((+(ayinput[i][0]*ayinput[i][1]))  +  (+(ayinput[r][0]*ayinput[r][1])))
    if(round[round.length - 1]>xy[0]*xy[1])round[round.length - 1] = 0;
  }
  }

}
}

print(Math.max(...round))

var rline = readline().split(" ");var xy = [+rline[1],+rline[2]];
var round = [0];
var ayinput = [];for(var o=0;o<rline[0];o++)ayinput.push(readline().split(" "))

for(var i =0;i<ayinput.length;i++){
for(var r=i+1;r<ayinput.length;r++){kk(ayinput[i],ayinput[r])}
}

function kk(a,b){

var s1 = [xy[0] - (+a[0]) , xy[1]];var s2 = [xy[1] - (+a[1]) , xy[0]];
var s3 = [xy[0] - (+a[1]) , xy[1]];var s4 = [xy[1] - (+a[0]) , xy[0]];
var toot = [s1,s2,s3,s4];for(var x = 0;x<toot.length;x++){

if(toot[x][0]>0){

  if ((toot[x][0] >= b[0]) && (toot[x][1]>=b[1])){
    round.push((+(ayinput[i][0]*ayinput[i][1]))  +  (+(ayinput[r][0]*ayinput[r][1])))
    if(round[round.length - 1]>xy[0]*xy[1])round[round.length - 1] = 0;
          }

  if ((toot[x][1] >= b[0]) && (toot[x][0]>=b[1])){
    round.push((+(ayinput[i][0]*ayinput[i][1]))  +  (+(ayinput[r][0]*ayinput[r][1])))
    if(round[round.length - 1]>xy[0]*xy[1])round[round.length - 1] = 0;
  }
  }

}
}

print(Math.max(...round))

    var rline = readline().split(" ");var xy = [rline[1],rline[2]];

    var temp = [];for(var o=0;o<rline[0];o++)temp.push(readline().split(" "))
    var ayinput = [];

    for(var i = 0;i<temp.length;i++){
    ayinput.push((+xy[0]-(+temp[i][0]))*xy[1] + " " + (+xy[1]-(+temp[i][1]))*xy[0]);
    }

    var lastspace = 9999999;var round = 0;var z = 0;var e = 9999999;
    for(var r = 0;r<ayinput.length;r++){
    var firstitem = ayinput[r].split(" ");for(var m = r+1;m<ayinput.length;m++){

    var seconditem = ayinput[m].split(" ");
    var fps0 = (+firstitem[z])+(+seconditem[0]);var fps1 = (+firstitem[z])+(+seconditem[1]);

    if(fps0>=xy[0]*xy[1]){if((fps0<=lastspace)&&(seconditem[1]<=e) ){

        e = seconditem[1];lastspace= fps0;round =((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}

    if(fps1>=xy[0]*xy[1]){if((fps1<=lastspace)&&(seconditem[0]<=e)){

        e = seconditem[0];lastspace=fps1;round = ((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}

    }if(z===0){z+=1;r-=1}
    }
    print(round);


//↓見なくていいよ！ここから--------------------------------------------------
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);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
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){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray();
		var count = 0;
		list.sort(function(a,b){
			return a - b;
		});
		for(var j = 0; j < N; j++){
			if(list[j] <= j + 1){
				count = j + 1;
			}
		}
		output[i] = count + 1;
	}
	myout(myconv(output,9));
}

const processData = (lines) => {
  const n = +lines[0]
  for (let i=0; i<n; i++) {
    const arr = lines[i*2+2].split(' ').map(x => +x)
    arr.sort((a, b) => a-b)
    let acc = 1
    let buffer = 0
    for (let i=0; i<arr.length; i++) {

      if (arr[i] <= acc + buffer) {
        acc += buffer + 1
        buffer = 0
      } else {
        buffer++
      }
    }
    console.log(acc)
  }
}

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

function ladies (n, arr) {
    arr.sort((a, b) => a > b ? 1 : -1);
    let present = 1;
    let itr = 0;
    let j = n - 1;

    while (j >= 0 && itr < n) {
        let now = ((j - itr) + 1);
        if (arr[j] <= (now + present - 1)) {
            present += now;
            itr = j + 1;
            j = n - 1;
        }
        else {
            if ((itr === j) || (itr === n-1) || (itr > j)) return present;
            j -= 1;
        }
    }
    return present;
}

function processData(input) {
    let inpArr = input.split("\n");
    let n = parseInt(inpArr[0]);

    for (let i = 1; i < inpArr.length - 1; i += 2) {
        console.log(ladies(parseInt(inpArr[i]), inpArr[i+1].split(' ').map(val => parseInt(val))));
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

'use strict';

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

let inputString = [];
let currentLine = 0;

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

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

    //withTiming(main);
    main();
});

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

const withTiming = callback => {
    const start = new Date();
    callback();
    console.log(`Took ${new Date() - start} ms`);
}

function main() {
    const n = Math.floor(readline());
    const inputs = [];

    for (let i = 0; i < n; i++) {
        const m = parseInt(readline());
        const grannies = readline().split(' ').map(granny => parseInt(granny));
        let possibleGrannies = m + 1, i = 0;
        grannies.sort((a, b) => b - a);

        while (grannies[i] >= possibleGrannies) {
            i++;
            possibleGrannies--;
        }

        console.log(possibleGrannies);
    }
}

//1 1 4 5 4 9

'use strict';

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

let inputString = [];
let currentLine = 0;

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

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

    //withTiming(main);
    main();
});

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

const withTiming = callback => {
    const start = new Date();
    callback();
    console.log(`Took ${new Date() - start} ms`);
}

function main() {
    const n = Math.floor(readline());
    const inputs = [];

    for (let i = 0; i < n; i++) {
        const m = parseInt(readline());
        const grannies = readline().split(' ').map(granny => parseInt(granny));
        let currentGrannies = 1, k = 0;
        grannies.sort();

        while(k < grannies.length) {
            if (grannies[k] <= currentGrannies) {
                currentGrannies++;
                k++;
            } else {
                let j = grannies[k];

                if (grannies[j] <= j + 1) {
                    currentGrannies = j + 2;
                    k = j + 1;
                } else {
                    k = grannies.length;
                }
            }
        }
        console.log(currentGrannies);
    }
}

//1 1 4 5 5 9

'use strict';

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

let inputString = [];
let currentLine = 0;

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

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

    //withTiming(main);
    main();
});

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

const withTiming = callback => {
    const start = new Date();
    callback();
    console.log(`Took ${new Date() - start} ms`);
}

function main() {
    const n = Math.floor(readline());
    const inputs = [];

    for (let i = 0; i < n; i++) {
        const m = parseInt(readline());
        const grannies = readline().split(' ').map(granny => parseInt(granny));
        let k = 0, result = grannies.length + 1;
        grannies.sort();

        while(k < grannies.length) {
            if (grannies[k] <= k + 1) {
                k++;
            } else {
                let j = grannies[k];

                if (grannies[j] <= j + 1) {
                    k = j + 1;
                } else {
                    result = k + 1;
                    k = grannies.length;
                }
            }
        }

        console.log(result);
    }
}

//1 1 4 5 4 9


var wires = parseInt(readline());
var arr = readline().split(" ").map(Number);
var shoots = parseInt(readline());

for (var i = 0; i < shoots; i++) {
    var current = readline().split(" ").map(Number);
    var k = current[0];
    var n = current[1];

    if (k !== 1) {
        arr[k - 2] += n - 1; // arr[k - 2] is nothing but arr[(k - 1) - 1]
    }

    if (k !== arr.length) {
        arr[k] += arr[k - 1] - n; // arr[k] is nothing but arr[(k - 1) + 1]
    }

    arr[k - 1] = 0;
}

print(arr.join(" "));

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function readint() {
    let line = readline().split(' ').map(function(num) {
        return parseInt(num);
    });
    return line;
}

function readfloat() {
    let line = readline().split(' ').map(function(num) {
        return parseFloat(num);
    });
    return line;
}

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

function write(x) {
    process.stdout.write(x);
}
function main() {
    let n = parseInt(readline());
    let a = readint();
    let m = parseInt(readline());
    let xy = [];
    for (let i = 0; i < m; i++) {
        let xly = readint();
        xy.push(xly);
    }
    for (let i = 0; i < m; i++) {

        let x = xy[i][0];
        let y = xy[i][1];
        x--;
        y--;
        if(x != 0) {
            a[x - 1] += y;
        }
        if(x != n - 1) {
            a[x + 1] += a[x] - y - 1;
        }
        a[x] = 0;
    }
    for (let i = 0; i < a.length; i++) {
        write(a[i] + "\n");
    }
}

var n = +readline();
var a = ('0 ' + readline() + ' 0').split(' ').map(Number);
var m = +readline();
while( m-- ){
	+function(x, y){
		a[x-1] += y-1;
		a[x+1] += a[x]-y;
		a[x] = 0;
	}.apply(0, readline().split(' ').map(Number));
}
a.shift();
a.pop();
print(a.join('\n'));

ip = readline().split(" ");
n = parseInt(ip[0]);
A = readline().split(" ");
ip = readline().split(" ");
m = parseInt(ip[0]);
var B = new Array();
for (var i = 0; i < m; i++){
	B[i] = readline().split(" ");
	if (B[i][0]-1 > 0) A[B[i][0]-2] = parseInt(A[B[i][0]-2]) + parseInt(B[i][1]-1);
	if (B[i][0]-1 < n-1) A[B[i][0]] =  parseInt(A[B[i][0]])  + parseInt(A[B[i][0]-1]) - parseInt(B[i][1]);
	A[B[i][0]-1] = 0;
}
for (var i = 0; i < n; i++){
	write(A[i] + "\n");
}

var numberOfLines = readline()
  var lines = readline().split(' ').map(Number)
  var numberOfShoots = readline()

  for (var i = 0; i < numberOfShoots; i++) {
    var shootPositions = readline().split(' ').map(Number)
    var lineIndex = shootPositions[0] - 1
    var index = shootPositions[1]

    var currentNumberOfBirds = lines[lineIndex]

    if (lineIndex - 1 >= 0) lines[lineIndex - 1] += (index - 1)
    if (lineIndex + 1 < lines.length) lines[lineIndex + 1] += currentNumberOfBirds - index
    lines[lineIndex] = 0
  }

  for (var i = 0; i < lines.length; i++) {
    print(lines[i])
  }

;(function () {

	var n = +readline();
	var a = readline().split(' ').map(Number);
	var m = +readline();
	var x = [];
	for (var i = 0; i < m; i++) x.push( readline().split(' ').map(Number) );

	for (var i = 0; i < m; i++) {
		if (x[i][0] != 1) a[x[i][0] - 2] += x[i][1] - 1;
		if (x[i][0] != n) a[x[i][0]] += a[x[i][0] - 1] - x[i][1];
		a[x[i][0] - 1] = 0; // poor bird
	}

	print( a.join('\n') );

}).call(this);

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]);
	};
	return tokens;
}

function main() {
	var wireNum = parseInt(readline());
	var wires = tokenizeIntegers(readline());
	wires.unshift(null);

	var jumpNum = parseInt(readline());
	for (var i = 0; i < jumpNum; i += 1) {
		var integers = tokenizeIntegers(readline());
		var r = integers[0], c = integers[1];
		if (r > 1) {
			wires[r-1] += c-1;
		}
		if (r < wireNum) {
			wires[r+1] += wires[r]-c;
		}
		wires[r] = 0;
	}

	print(wires.slice(1).join('\n'));
}

main();

var n = readline(),
	a = readline().split(" ").map(Number),
	m = readline(), x = [];
for (var i = 0; i < m; i++) {
	x[i] = readline().split(" ").map(Number);
	var v = x[i][0] - 1;
	a[v + 1] += a[v] - x[i][1];
	a[v] = 0;
	a[v - 1] += x[i][1] - 1;
}
for (var i = 0; i < n; i++) {
	print(a[i]);
}

const readline = require('readline');

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

let lineCounter = 1;
let birdsPerLine = [];
let shotsArr = [];
let numOfShots;

rl.on('line', (input) => {
    if (lineCounter === 1) {
        lineCounter++;
        return;
    }
    if (lineCounter === 2) {
        let line = input.split(' ');
        line.forEach(ele => {
            birdsPerLine.push(parseInt(ele));
        })
    } else if (lineCounter === 3) {
        numOfShots = parseInt(input);
        if (numOfShots === 0) {
            rl.close();
            solve(birdsPerLine, shotsArr);
            birdsPerLine.forEach(ele => {
                console.log(ele);
            })
        }
    } else if (lineCounter <= 3 + numOfShots) {
        let line = input.split(' ');
        shotsArr.push([parseInt(line[0]), parseInt(line[1])]);
        if (lineCounter === 3 + numOfShots) {
            rl.close();
            solve(birdsPerLine, shotsArr);
            birdsPerLine.forEach(ele => {
                console.log(ele);
            })
        }
    }
    lineCounter++;
});

const solve = (birdsPerLine, shotsArr) => {
    shotsArr.forEach(shot => {
        let line = shot[0];
        let shootedBird = shot[1];
        let currentBirds = birdsPerLine[line - 1];
        let leftBird = shootedBird - 1;
        let rightBirds = currentBirds - shootedBird;
        birdsPerLine[line - 1] = 0;
        if (birdsPerLine[line - 2] || birdsPerLine[line - 2] === 0) birdsPerLine[line - 2] += leftBird;
        if (birdsPerLine[line] || birdsPerLine[line] === 0) birdsPerLine[line] += rightBirds;
    });

}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

function print(s) {
  process.stdout.write(`${s}`);
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  // input
  const n = +readline();
  const a = readline().split(' ').map(x => parseInt(x));
  const m = +readline();
  for (let i = 0; i < m; i++) {
    const [x, y] = readline().split(' ').map(x => parseInt(x));
    if (x !== 1) {
      a[x-1-1] += y - 1;
    }
    if (x !== n) {
      a[x+1-1] += a[x-1] - y;
    }
    a[x-1] = 0;
  }
 // output
  a.forEach(x => print(`${x}\n`));
}

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

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

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

  if (c == 2) {
    c++;
    return;
  }

  const [x, y] = d.split(' ').map(Number);
  let curr = x - 1;
  let up = curr - 1;
  let down = curr + 1;

  let birds = wires[curr];
  let upBirds = y - 1;
  let downBirds = birds - y;
  wires[curr] = 0;

  if (wires[up] !== undefined) {
    wires[up] = wires[up] + upBirds;
  }

  if (wires[down] !== undefined) {
    wires[down] = wires[down] + downBirds;
  }
  c++;
});

rl.on('close', () => {
  for (let i = 0; i < wires.length; i++) {
    console.log(wires[i]);
  }
});

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
const mapFunc = (arr) => {
  return arr.map((b) => parseInt(b));
}
let input = [];
readline.on('line', line => {
  input.push(line);
});
process.stdin.on('end', () => {
const n = parseInt(input[0], 10);
let a = input[1].split(' ');
a = a.map((b) => parseInt(b));
const m = parseInt(input[2], 10);
for (let i=3; i < m+3; i++) {
  let xy = input[i].split(' ');
  xy = mapFunc(xy);
  xy[0] -= 1;
  const wentUp = xy[1] - 1;
  const wentDown = parseInt(a[xy[0]], 10) - wentUp - 1;
  if (xy[0] > 0) {
    a[xy[0] - 1] = a[xy[0] - 1] + wentUp;
  }
  if (xy[0] < n-1) {
    a[xy[0] + 1] = a[xy[0] + 1] + wentDown;
  }
  a[xy[0]] = 0;
}
for (const e of a) {
  console.log(e);
}
});

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

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

  if (c === 1) {
    c++;
    wires = [0, ...d.split(' ').map(Number), 0];
    return;
  }

  if (c == 2) {
    c++;
    return;
  }

  const [x, y] = d.split(' ').map(Number);

  wires[x - 1] +=  y - 1;
  wires[x + 1] += wires[x] - y;
  wires[x] = 0;

  c++;
});

rl.on('close', () => {
  for (let i = 1; i < wires.length - 1; i++) {
    console.log(wires[i]);
  }
});

var wires = parseInt(readline());
var arr = readline().split(" ").map(Number);
var shoots = parseInt(readline());

for (var i = 0; i < shoots; i++) {
    var current = readline().split(" ").map(Number);
    var k = current[0];
    var n = current[1];

    if (arr[(k -1) -1]) {
        arr[(k -1) -1] += n - 1;
    }

    if (arr[(k - 1) + 1]) {
        arr[(k - 1) + 1] += arr[k - 1] - n;
    }

    arr[k - 1] = 0;
}

print(arr.join(" "));

const readline = require('readline');

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

let lineCounter = 1;
let birdsPerLine = [];
let shotsArr = [];
let numOfShots;

rl.on('line', (input) => {
    if (lineCounter === 1) {
        lineCounter++;
        return;
    }
    if (lineCounter === 2) {
        let line = input.split(' ');
        line.forEach(ele => {
            birdsPerLine.push(parseInt(ele));
        })
    } else if (lineCounter === 3) {
        numOfShots = parseInt(input);
    } else if (lineCounter <= 3 + numOfShots) {
        let line = input.split(' ');
        shotsArr.push([parseInt(line[0]), parseInt(line[1])]);
        if (lineCounter === 3 + numOfShots) {
            rl.close();
            solve(birdsPerLine, shotsArr);
            birdsPerLine.forEach(ele => {
                console.log(ele);
            })
        }
    }
    lineCounter++;
});

const solve = (birdsPerLine, shotsArr) => {
    shotsArr.forEach(shot => {
        let line = shot[0];
        let shootedBird = shot[1];
        let currentBirds = birdsPerLine[line - 1];
        let leftBird = shootedBird - 1;
        let rightBirds = currentBirds - shootedBird;
        birdsPerLine[line - 1] = 0;
        if (birdsPerLine[line - 2] || birdsPerLine[line - 2] === 0) birdsPerLine[line - 2] += leftBird;
        if (birdsPerLine[line] || birdsPerLine[line] === 0) birdsPerLine[line] += rightBirds;
    });

}


var inp = readline().split(' ');
var n = parseInt(inp[0], 10);
var d = parseInt(inp[1], 10);
var friends = [];

for (var i = 0; i < n; i++) {
	inp = readline().split(' ');
	friends.push({
		m: parseInt(inp[0], 10),
		s: parseInt(inp[1], 10)
	});
}

friends = friends.sort(function (a, b) {
	return a.m - b.m;
});

var result = count(friends, d);

write(result);

function count(friends, d) {
	var maxF = 0;
	var m = 0;
	var s = 0;
	var f = friends[s].s;

	while (s < friends.length - 1) {
		s++;
		f += friends[s].s;
		if (friends[s].m - friends[m].m >= d) {
			maxF = Math.max(maxF, f - friends[s].s);
			while (friends[s].m - friends[m].m >= d) {
				f -= friends[m].s;
				m++;
			}
		}
	}
	maxF = Math.max(maxF, f);
	return maxF;
}

function main() {
    var line = readline().split(' ').map(Number);
    var n = line[0];
    var d = line[1];
    var friends = [];
    for(var i=0;i<n;i++){
        line = readline().split(' ').map(Number);
        friends.push(line);
    }
    friends.sort((a,b)=>a[0]-b[0]);
    var startIndex = 0;
    var max = 0;
    var sum = 0;
    for(var i=0;i<n;i++){
        while(friends[i][0] - friends[startIndex][0] >= d){
            sum -= friends[startIndex][1];
            startIndex++;

        }
        sum += friends[i][1];
        if(sum > max){
            max = sum;
        }
    }
    print(max)
}

main()

var parsedLine = readline().split(" ");
var n = parseInt(parsedLine[0]);
var d = parseInt(parsedLine[1]);

var friends = [];
for (var i = 0; i < n; i++) {
  parsedLine = readline().split(" ");
  friends.push({
    m: parseInt(parsedLine[0]),
    s: parseInt(parsedLine[1])
  });
}
friends.sort(function(f1, f2) { return f1.m - f2.m; });

var sums = [0];
friends.forEach(function(f, i) { sums.push(f.s + sums[i]); });

var max = 0;
friends.forEach(function(f, i, arr) {
  var j = binarySearch(i, arr.length, function(k) {
    return arr[k].m >= arr[i].m + d;
  });
  var sum = sums[j] - sums[i];
  max = sum > max ? sum : max;
});

print(max);

function binarySearch(start, end, callback) {
  while(end > start + 1) {
    var mid = start + parseInt((end-start)/2);
    if (callback(mid)) {
      end = mid;
    } else {
      start = mid;
    }
  }
  return end;
}

var input = readline().split(" ").map(Number), n = input[0], d = input[1], arr = [];
for(var i = 0; i < n; i++){
    arr.push(readline().split(" ").map(Number));
}
var ans = 0;

arr.sort(function(a,b){return a[0]-b[0]});

var a = 0;
for(var i = 0; i < n; i++){
    arr[i][1] += a;
    a = arr[i][1];
}
delete a;

for(var i = 0; i < n; i++){
    var l = i;
    var r = n-1;

    while(r-l > 2){
        var m = Math.floor((r+l)/2);

        if(arr[m][0] < arr[i][0] + d){
            l = m;
        }
        else{
            r = m;
        }
    }

    while(l < r){
        if(arr[l][0] < arr[i][0] + d){
            l++;
        }
        else{
            r = l;
        }
    }

    if(arr[l][0] >= arr[i][0] + d){
        l--;
    }

    var numb;

    if(i == 0){
        numb = arr[l][1];
    }
    else{
        numb = arr[l][1] - arr[i-1][1]
    }

    var ans = Math.max(ans, numb);
}

write(ans);

var input = readline().split(" ").map(Number), n = input[0], d = input[1], arr = [];
for(var i = 0; i < n; i++){
    arr.push(readline().split(" ").map(Number));
}
var ans = 0;

arr.sort(function(a,b){return a[0]-b[0]});

var a = 0;
for(var i = 0; i < n; i++){
    arr[i][1] += a;
    a = arr[i][1];
}
delete a;

for(var i = 0; i < n; i++){
    var l = i;
    var r = n-1;

    while(r-l > 2){
        var m = Math.floor((r+l)/2);

        if(arr[m][0] < arr[m][0] + d){
            l = m;
        }
        else{
            r = m;
        }
    }

    while(l < r){
        if(arr[l][0] < arr[i][0] + d){
            l++;
        }
        else{
            r = l;
        }
    }

    if(arr[l][0] >= arr[i][0] + d){
        l--;
    }

    var numb;

    if(i == 0){
        numb = arr[l][1];
    }
    else{
        numb = arr[l][1] - arr[i-1][1]
    }

    var ans = Math.max(ans, numb);
}

write(ans);

var inp = readline().split(' ');
var n = parseInt(inp[0], 10);
var d = parseInt(inp[1], 10);
var friends = [];

for (var i = 0; i < n; i++) {
	inp = readline().split(' ');
	friends.push({
		m: parseInt(inp[0], 10),
		s: parseInt(inp[1], 10)
	});
}

friends = friends.sort(function (a, b) {
	return a.m > b.m;
});

var result = count(friends, d);

write(result);

function count(friends, d) {
	var maxF = 0;
	var m = 0;
	var s = 0;
	var f = friends[s].s;

	while (s < friends.length - 1) {
		s++;
		f += friends[s].s;
		if (friends[s].m - friends[m].m >= d) {
			maxF = Math.max(maxF, f - friends[s].s);
			while (friends[s].m - friends[m].m >= d) {
				f -= friends[m].s;
				m++;
			}
		}
	}
	maxF = Math.max(maxF, f);
	return maxF;
}


'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

// Make a Snippet for the code above this and then write your logic in main();
var mod = 1000000000n + 7n
var maxN = 1002

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

  Array(parseInt(x)).fill(1).map((t, iii) => {
    var n = parseInt(readline())

    var x = []
    var y = []
    for (let i = 0; i < n; i++) {
      var [xx, yy] = readline().split(' ').map((x, iii) => {
        return parseInt(x)
      })

      y.push(yy)
      x.push(xx)
    }
    var a = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })

    var ans = 0
    var ans1 = 0
    for (let i = 0; i < n; i++) {
      if (i === 0) {
        ans += x[i] - 0 + a[i]
      } else {
        ans += x[i] - y[i - 1] + a[i]
      }
      ans1 = ans
      ans += Math.ceil((y[i] - x[i]) / 2)

      ans = Math.max(y[i], ans)
    }

    // if(n>=1) ans-=a[n-1]

    console.log(ans1)

  })
}

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

  return gcd(b, a % b);
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = new Array(N + 1);
		list[0] = {
			a : 0,
			b : 0,
			v : 0
		};
		for(var j = 1; j <= N; j++){
			list[j] = {
				a : nextInt(),
				b : nextInt(),
				v : 0
			};
		}
		for(var j = 1; j <= N; j++){
			list[j].v = nextInt();
		}
		var now = 0;
		for(var j = 1; j <= N; j++){
			now += list[j].a - list[j - 1].b + list[j].v;
			if(j == N){
				break;
			}
			now += Math.ceil((list[j].b - list[j].a) / 2);
			if(list[j].b > now){
				now = list[j].b;
			}
		}
		myout(now);
	}
}

function getInt(num){
        return parseInt(num, 10);
    }
var t = parseInt(readline(), 10);
for(var it = 0; it<t; it++){
    var n = parseInt(readline(), 10);
    var lines = [[0,0]];

    for(var i = 0; i< n; i++){
        lines.push(readline().split(' ').map(getInt));
    }
    var times = readline().split(' ').map(getInt);

    if(n == 1){
        print(times[0] + lines[1][0]);
        continue;
    }

    var r = 0;
    for(var i = 0; i< times.length - 1; i++){
        var a1 = r + (lines[i+1][0] - lines[i][1] + times[i]) + Math.ceil((lines[i+1][1]-lines[i+1][0])/2);
        var a2 = lines[i+1][1];
        r = Math.max(a1, a2);
    }
    r = r + times[times.length - 1] + lines[times.length][0] - lines[times.length - 1][1]
    print(r)
}

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function solve() {
   var n = Number(read());
   var a = [];
   var b = [];
   for (var i = 0; i < n; i++) {
      var ab = readArray(Number);
      a[i] = ab[0];
      b[i] = ab[1];
   }
   var tm = readArray(Number);
   var time = 0;
   for (var i = 0; i < n; i++) {
      time += tm[i] + a[i] - (b[i - 1] || 0);
      if (i < n - 1) {
         time += (b[i] - a[i] + 1) >> 1;
         if (time < b[i]) {
            time = b[i];
         }
      }
   }
   write(time);
}

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

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

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function solve() {
   var n = Number(read());
   var a = [];
   var b = [];
   for (var i = 0; i < n; i++) {
      var ab = readArray(Number);
      a[i] = ab[0];
      b[i] = ab[1];
   }
   var tm = readArray(Number);
   var total = a[0] + tm[0] + n;
   for (var i = 1; i < n; i++) {
      total += a[i] + tm[i] - b[i - 1];
   }
   write(total);
}

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

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

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function solve() {
   var n = Number(read());
   var a = [];
   var b = [];
   for (var i = 0; i < n; i++) {
      var ab = readArray(Number);
      a[i] = ab[0];
      b[i] = ab[1];
   }
   var tm = readArray(Number);
   var total = a[0] + tm[0] + n;
   for (var i = 1; i < n; i++) {
      write(total);
      total += a[i] + tm[i] - b[i - 1];
   }
   write(total + '\n'   );
}

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

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