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

let input = [];
rl.on("line", function (line) {
  input.push(line);
}).on("close", function () {
  solution(input);
  process.exit();
});

function solution(_input) {
  const input = _input[Symbol.iterator]();
  const T = Number(input.next().value);

  const results = [];
  tc: for (let t = 0; t < T; t++) {
    const N = Number(input.next().value);
    const A = input.next().value.split(" ").map(Number);
    const B = input.next().value.split(" ").map(Number);

    const AB = [];
    for (let i = 0; i < N; i++) {
      AB.push([A[i], B[i]]);
    }
    AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));
    for (let i = 1; i < N; i++) {
      if (AB[i - 1][0] > AB[i][0] || AB[i - 1][1] > AB[i][1]) {
        results.push("-1");
        continue tc;
      }
    }

    ops = [];
    for (let i = 0; i < N; i++) {
      for (let j = i + 1; j < N; j++) {
        if (A[i] > A[j] || B[i] > B[j]) {
          [A[i], A[j]] = [A[j], A[i]];
          [B[i], B[j]] = [B[j], B[i]];
          ops.push([j + 1, i + 1].join(" "));
        }
      }
    }
    results.push(ops.length);
    for (let i = 0; i < ops.length; i++) {
      results.push(ops[i]);
    }
  }
  console.log(results.join("\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;
}
var T = readline();
for(var qe=1;qe<=T;qe++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map((x) => parseInt(x));
  var b = readline().split(' ').map((x) => parseInt(x));
  var as = [...a]
  var bs = [...b]
  as.sort(function(x,y) { return x-y })
  bs.sort(function(x,y) { return x-y })
  // var rev_a = reverse(as);
  // var rev_b = reverse(bs);
  // function reverse(arr) {
  //   var v = [];
  //   for(var j=arr.length-1;j>=0;j--) v.push(arr[j]);
  //   return v;
  // }
  //console.log(a, as, rev_a);
  var ans = [];
  var flag = true;
  for(var i=0;i<n;i++) {
    var ok = false;
    for(var j=i;j<n;j++) {
      if(a[j] == as[i] && b[j] == bs[i]) {
        if(i != j) ans.push([i+1, j+1]);
        ok = true;
        a[j] = a[i];
        b[j] = b[i];
        break;
      }
    }
    if(!ok) flag = false;
  }
  if(!flag) console.log(-1);
  else {
      console.log(ans.length);
      for(var i=0;i<ans.length;i++) {
        console.log(ans[i].join(' '));
      }
  }

  //console.log(ans);
  //fs.appendFileSync('output.txt', ans+'\r\n');

}
//

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 sa = lines[l++].trim().split(' ').map(Number)
        const sb = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(sa, sb)
    }
    console.log(output.join('\n'))
// })()
})

function solve(sa, sb) {
    const moves = []
    const sorted = sa.map((x, i) => ({ x, i }))
        // .sort((a, b) => a.x - b.x)
    sort(sorted, 0, sorted.length - 1, sa, moves)
// console.log(sorted)
    //
    let p = {}, pi = -1
    sorted.forEach((x, i) => {
        if (x.x === p.x) {
            //
        } else {
            // [pi, i - 1]
            if (pi >= 0) {
                // console.log(pi, i - 1)
                sort(sorted, pi, i - 1, sb, moves)
            }
            p = x
            pi = i
        }
    })
// console.log(pi, sa.length - 1)
    sort(sorted, pi, sa.length - 1, sb, moves)
    const after = sorted.map(o => sb[o.i])
// console.log(after)
    for (let i = 1; i < after.length; i++) {
        if (after[i - 1] > after[i]) return -1
    }
    if (!moves.length) return 0
    return moves.length + '\n' + moves.join('\n')
}
function sort(arr, first, last, old, moves) {
    let swap
    for (let i = first; i <= last; i++) {
        swap = 0
        for (let j = first + 1; j <= last; j++) {
            if (old[arr[j - 1].i] > old[arr[j].i]) {
                [arr[j - 1], arr[j]] = [arr[j], arr[j - 1]]
                moves.push([j - 1 + 1, j + 1].join(' '))
                swap = 1
            }
        }
        if (!swap) break
    }
}

'use strict';

function solve(n, a, b) {
  let nums = new Array(n);
  for (let i = 0; i < n; i++) {
    nums[i] = [a[i], b[i], i];
  }
  let flag = true;
  nums.sort((a, b) => {
    if (a[0] === b[0]) {
      return a[1] - b[1];
    } else if (a[1] === b[1]) {
      return a[0] - b[0];
    } else {
      const x = a[0] - b[0],
            y = a[1] - b[1];
      if (x * y < 0) {
        flag = false;
      }
      return a[0] - b[0];
    }
  });
  if (!flag) return -1;
  const h = new Array(n).fill(-1),
        e = [],
        ne = [];
  let idx = 0;
  const add = (i, j) => {
    e[idx] = j, ne[idx] = h[i], h[i] = idx++;
  };
  for (let i = 0; i < n; i++) {
    if (nums[i][2] !== i) {
      add(i, nums[i][2]);
    }
  }
  let res = [],
      st = new Array(n);
  for (let i = 0; i < n; i++) {
    if (st[i]) continue;
    if (h[i] !== -1) {
      const queue = [i];
      for (let u of queue) {
        st[u] = 1;
        for (let k = h[u]; k !== -1; k = ne[k]) {
          const v = e[k];
          if (st[v]) continue;
          queue.push(v);
        }
      }
      let cur = i;
      for (let j = 1; j < queue.length; j++) {
        res.push([cur, queue[j]]);
        cur = queue[j];
      }
    }
  }
  if (res.length === 0) return '0';
  return `${res.length}\n${res.map(arr => arr.map(num => num + 1).join(' ')).join('\n')}`;
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      const b = (await read()).split(' ').map(Number);
      res.push(solve(n, 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";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr1 = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr2 = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let res = [];
    const sort = (arr, arr1) => {
      for (let i = 0; i < n; i++) {
        let min = i;
        for (let j = i + 1; j < n; j++) {
          if (arr[min] > arr[j]) min = j;
        }
        if (min === i) continue;
        res.push(`${min + 1} ${i + 1}`);
        [arr[i], arr[min]] = [arr[min], arr[i]];
        [arr1[i], arr1[min]] = [arr1[min], arr1[i]];
      }
      for (let i = 1; i < n; i++) {
        if (arr1[i - 1] > arr1[i]) return false;
      }
      return true;
    };
    const print = () => {
      console.log(res.length);
      if (res.length === 0) return;
      for (let i = 0; i < res.length; i++) console.log(res[i]);
    };
    if (sort(arr1, arr2)) {
      print();
      continue;
    }
    if (sort(arr2, arr1)) {
      print();
      continue;
    }
    console.log(-1);
  }
};
solve();

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`\nTest #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

tests = [
``, // Test #1
``, // Test #2
``, // Test #3
``, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const calc = (testN)=>{
  // READING:
  let [n] = ra();
  let A = ra();
  let B = ra();
  LT({n, A, B});
  // PROCESSING:
  let P = [];
  for (let i=0; i<n; i++)
    P.push(i);
  let swaps = [];
  let swap = (i, j)=>{
    swaps.push((i+1)+' '+(j+1));
    let tmp = A[i];
    A[i] = A[j];
    A[j] = tmp;
    tmp = B[i];
    B[i] = B[j];
    B[j] = tmp;
  };
  for (let i=0; i<n; i++){
    for (let j=0; j<n-1; j++){
      if (A[j]==A[j+1]){
        if (B[j]>B[j+1]){
          swap(j, j+1);
        }
      } else {
        if (A[j]<A[j+1]){
          if (B[j]>B[j+1])
            return void print(-1);
        } else {
          if (B[j]<B[j+1])
            return void print(-1);
          swap(j, j+1);
        }
      }
    }
  }
  print(swaps.length);
  if (swaps.length)
    print(swaps.join('\n'))
};

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

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

/*---------------------------------------------------*/

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

const calc = (t)=>{
    /* read */
    let n = +readline();
    let a = ra();
    let b = ra();

    let moves = [];

    for (let i = 0; i < n; i++) {
        let minidx = i;
        let j = i + 1;
        for (; j < n; j++) {
            if (a[j] < a[minidx]) {
                minidx = j;
            }
        }
        if (minidx === i) continue;
        j = minidx;
        moves.push(`${i + 1} ${j + 1}`);

        let tmpa = a[i];
        a[i] = a[j];
        a[j] = tmpa;

        let tmpb = b[i];
        b[i] = b[j];
        b[j] = tmpb;
    }

    for (let l = 0; l < n - 1; l++) {
        let r = l + 1;
        while (r < n && a[l] === a[r]) {
            r++;
        }

        for (let i = l; i < r; i++) {
            let minidx = i;
            let j = i + 1
            for (; j < r; j++) {
                if (b[j] < b[minidx]) {
                    minidx = j;
                }
            }
            if (minidx === i) continue;
            j = minidx;
            moves.push(`${i + 1} ${j + 1}`);

            let tmpb = b[i];
            b[i] = b[j];
            b[j] = tmpb;
        }

    }

    if (moves.length > 10000) return '-1';

    for (let i = 1; i < n; i++) {
        if (b[i] < b[i - 1]) return '-1';
    }

    let result = `${moves.length}`;
    if (moves.length > 0) {
        result += '\n';
        result += moves.join('\n');
    }
    return result;
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc(t));
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

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

let input = [];
rl.on("line", function (line) {
  input.push(line);
}).on("close", function () {
  solution(input);
  process.exit();
});

function solution(_input) {
  const input = _input[Symbol.iterator]();
  const T = Number(input.next().value);

  const results = [];
  tcloop: for (let t = 0; t < T; t++) {
    const N = Number(input.next().value);
    const A = input.next().value.split(" ").map(Number);
    const B = input.next().value.split(" ").map(Number);

    const AB = [];
    for (let i = 0; i < N; i++) {
      AB.push([A[i], B[i]]);
    }
    AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));
    for (let i = 1; i < N; i++) {
      if (AB[0][i - 1] > AB[0][i] || AB[1][i - 1] > AB[1][i]) {
        results.push("-1");
        continue tcloop;
      }
    }

    ops = [];
    // for (let i = 0; i < N; i++) {
    //   for (let j = i + 1; j < N; j++) {
    //     if (A[i] > A[j] || B[i] > B[j]) {
    //       [A[i], A[j]] = [A[j], A[i]];
    //       [B[i], B[j]] = [B[j], B[i]];
    //       ops.push([j + 1, i + 1].join(" "));
    //     }
    //   }
    // }
    for (let i = 1; i < N; i++) {
      for (let j = 1; j < N; j++) {
        if (A[j - 1] > A[j] || B[j - 1] > B[j]) {
          [A[j - 1], A[j]] = [A[j], A[j - 1]];
          [B[j - 1], B[j]] = [B[j], B[j - 1]];
          ops.push([j, j + 1].join(" "));
        }
      }
    }

    results.push(ops.length);
    for (let i = 0; i < ops.length; i++) {
      results.push(ops[i]);
    }
  }
  console.log(results.join("\n"));
}

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

let input = [];
rl.on("line", function (line) {
  input.push(line);
}).on("close", function () {
  solution(input);
  process.exit();
});

function solution(_input) {
  const input = _input[Symbol.iterator]();
  const T = Number(input.next().value);

  const results = [];
  tcloop: for (let t = 0; t < T; t++) {
    const N = Number(input.next().value);
    const A = input.next().value.split(" ").map(Number);
    const B = input.next().value.split(" ").map(Number);

    const AB = [];
    for (let i = 0; i < N; i++) {
      AB.push([A[i], B[i]]);
    }
    AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));
    for (let i = 1; i < N; i++) {
      if (AB[0][i - 1] > AB[0][i] || AB[1][i - 1] > AB[1][i]) {
        results.push("-1");
        continue tcloop;
      }
    }

    ops = [];
    for (let i = 0; i < N; i++) {
      for (let j = i + 1; j < N; j++) {
        if (A[i] > A[j] || B[i] > B[j]) {
          [A[i], A[j]] = [A[j], A[i]];
          [B[i], B[j]] = [B[j], B[i]];
          ops.push([j + 1, i + 1].join(" "));
        }
      }
    }

    results.push(ops.length);
    for (let i = 0; i < ops.length; i++) {
      results.push(ops[i]);
    }
  }
  console.log(results.join("\n"));
}

const { Console } = require("console");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);
}).on("close", function () {
  solution(input);
  process.exit();
});

function solution(_input) {
  const input = _input[Symbol.iterator]();
  const T = Number(input.next().value);

  const results = [];
  tcloop: for (let t = 0; t < T; t++) {
    const N = Number(input.next().value);
    const A = input.next().value.split(" ").map(Number);
    const B = input.next().value.split(" ").map(Number);

    const AB = [];
    for (let i = 0; i < N; i++) {
      AB.push([A[i], B[i]]);
    }
    AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));
    for (let i = 1; i < N; i++) {
      if (AB[0][i - 1] > AB[0][i] || AB[1][i - 1] > AB[1][i]) {
        results.push("-1");
        continue tcloop;
      }
    }

    ops = [];
    for (let i = 0; i < N; i++) {
      for (let j = i + 1; j < N; j++) {
        if (A[i] > A[j] || B[i] > B[j]) {
          [A[i], A[j]] = [A[j], A[i]];
          [B[i], B[j]] = [B[j], B[i]];
          ops.push([j + 1, i + 1].join(" "));
        }
      }
    }

    for (let i = 0; i < N; i++) {
      for (let j = i + 1; j < N; j++) {
        if (A[i] > A[j] || B[i] > B[j]) {
          [A[i], A[j]] = [A[j], A[i]];
          [B[i], B[j]] = [B[j], B[i]];
          ops.push([j + 1, i + 1].join(" "));
        }
      }
    }

    results.push(ops.length);
    for (let i = 0; i < ops.length; i++) {
      results.push(ops[i]);
    }
  }
  console.log(results.join("\n"));
}

const { Console } = require("console");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);
}).on("close", function () {
  solution(input);
  process.exit();
});

function solution(_input) {
  const input = _input[Symbol.iterator]();
  const T = Number(input.next().value);

  const results = [];
  tcloop: for (let t = 0; t < T; t++) {
    const N = Number(input.next().value);
    const A = input.next().value.split(" ").map(Number);
    const B = input.next().value.split(" ").map(Number);

    const AB = [];
    for (let i = 0; i < N; i++) {
      AB.push([A[i], B[i]]);
    }
    AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));
    for (let i = 1; i < N; i++) {
      if (AB[0][i - 1] > AB[0][i] || AB[1][i - 1] > AB[1][i]) {
        results.push("-1");
        continue tcloop;
      }
    }

    ops = [];
    for (let i = 0; i < N - 1; i++) {
      for (let j = i + 1; j < N; j++) {
        if (A[i] > A[j] || B[i] > B[j]) {
          [A[i], A[j]] = [A[j], A[i]];
          [B[i], B[j]] = [B[j], B[i]];
          ops.push([j + 1, i + 1].join(" "));
        }
      }
    }

    results.push(ops.length);
    for (let i = 0; i < ops.length; i++) {
      results.push(ops[i]);
    }
  }
  console.log(results.join("\n"));
}

const { Console } = require("console");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);
}).on("close", function () {
  solution(input);
  process.exit();
});

function solution(_input) {
  const input = _input[Symbol.iterator]();
  const T = Number(input.next().value);

  const results = [];
  tcloop: for (let t = 0; t < T; t++) {
    const N = Number(input.next().value);
    const A = input.next().value.split(" ").map(Number);
    const B = input.next().value.split(" ").map(Number);

    const AB = [];
    for (let i = 0; i < N; i++) {
      AB.push([A[i], B[i]]);
    }
    AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));
    for (let i = 1; i < N; i++) {
      if (AB[0][i - 1] > AB[0][i] || AB[1][i - 1] > AB[1][i]) {
        results.push(-1);
        continue tcloop;
      }
    }

    ops = [];
    for (let i = 0; i < N; i++) {
      for (let j = i + 1; j < N; j++) {
        if (A[i] > A[j] || B[i] > B[j]) {
          [A[i], A[j]] = [A[j], A[i]];
          [B[i], B[j]] = [B[j], B[i]];
          ops.push([j + 1, i + 1].join(" "));
        }
      }
    }

    results.push(ops.length);
    for (let i = 0; i < ops.length; i++) {
      results.push(ops[i]);
    }
  }
  console.log(results.join("\n"));
}

const { Console } = require("console");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);
}).on("close", function () {
  solution(input);
  process.exit();
});

function solution(_input) {
  const input = _input[Symbol.iterator]();
  const T = Number(input.next().value);

  const results = [];
  tcloop: for (let t = 0; t < T; t++) {
    const N = Number(input.next().value);
    const A = input.next().value.split(" ").map(Number);
    const B = input.next().value.split(" ").map(Number);

    const AB = [];
    for (let i = 0; i < N; i++) {
      AB.push([A[i], B[i]]);
    }
    AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));
    for (let i = 1; i < N; i++) {
      if (AB[1][i - 1] > AB[1][i]) {
        results.push(-1);
        continue tcloop;
      }
    }

    ops = [];
    for (let i = 0; i < N; i++) {
      for (let j = i + 1; j < N; j++) {
        if (A[i] > A[j] || B[i] > B[j]) {
          [A[i], A[j]] = [A[j], A[i]];
          [B[i], B[j]] = [B[j], B[i]];
          ops.push([j + 1, i + 1].join(" "));
        }
      }
    }

    results.push(ops.length);
    for (let i = 0; i < ops.length; i++) {
      results.push(ops[i]);
    }
  }
  console.log(results.join("\n"));
}

const { Console } = require("console");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);
}).on("close", function () {
  solution(input);
  process.exit();
});

function solution(_input) {
  const input = _input[Symbol.iterator]();
  const T = Number(input.next().value);

  const results = [];
  tcloop: for (let t = 0; t < T; t++) {
    const N = Number(input.next().value);
    const A = input.next().value.split(" ").map(Number);
    const B = input.next().value.split(" ").map(Number);

    const AB = [];
    for (let i = 0; i < N; i++) {
      AB.push([A[i], B[i]]);
    }
    AB.sort(([a1, b1], [a2, b2]) => (a1 < a2 ? -1 : b1 < b2 ? -1 : 0));
    for (let i = 1; i < N; i++) {
      if (AB[1][i - 1] > AB[1][i]) {
        results.push(-1);
        continue tcloop;
      }
    }

    ops = [];
    for (let i = 0; i < N; i++) {
      for (let j = i + 1; j < N; j++) {
        if (A[i] > A[j] || B[i] > B[j]) {
          [A[i], A[j]] = [A[j], A[i]];
          [B[i], B[j]] = [B[j], B[i]];
          ops.push([i + 1, j + 1].join(" "));
        }
      }
    }

    results.push(ops.length);
    for (let i = 0; i < ops.length; i++) {
      results.push(ops[i]);
    }
  }
  console.log(results.join("\n"));
}

const { Console } = require("console");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);
}).on("close", function () {
  solution(input);
  process.exit();
});

function solution(_input) {
  const input = _input[Symbol.iterator]();
  const T = Number(input.next().value);

  const results = [];
  for (let t = 0; t < T; t++) {
    const N = Number(input.next().value);
    const A = input.next().value.split(" ").map(Number);
    const B = input.next().value.split(" ").map(Number);
    const history = [];
    for (let i = 0; i < N; i++) {
      let minA = A[i];
      let minB = B[i];
      let idxA = null;
      let idxB = null;
      for (let j = i + 1; j < N; j++) {
        if (minA > A[j]) {
          minA = A[j];
          idxA = j;
        }
        if (minB > B[j]) {
          minB = B[j];
          idxB = j;
        }
      }
      const idx = idxA || idxB;
      if (idx !== null) {
        let tmp = A[i];
        A[i] = A[idx];
        A[idx] = tmp;
        tmp = B[i];
        B[i] = B[idx];
        B[idx] = tmp;
        history.push([i + 1, idx + 1]);
      }
    }
    if (
      JSON.stringify(A.slice().sort()) === JSON.stringify(A) &&
      JSON.stringify(B.slice().sort()) === JSON.stringify(B)
    ) {
      results.push(history.length);
      history.forEach((v) => results.push(v.join(" ")));
    } else {
      results.push(-1);
    }

    // console.log(history);
  }
  console.log(results.join("\n"));
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr1 = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr2 = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let res = [];
    const sort = (arr, arr1) => {
      for (let i = 0; i < n; i++) {
        let min = i;
        for (let j = i + 1; j < n; j++) {
          if (arr[min] > arr[j]) min = j;
        }
        if (min === i) continue;
        res.push(`${min + 1} ${i + 1}`);
        [arr[i], arr[min]] = [arr[min], arr[i]];
        [arr1[i], arr1[min]] = [arr1[min], arr1[i]];
      }
      for (let i = 1; i < n; i++) {
        if (arr1[i - 1] > arr1[i]) return false;
      }
      return true;
    };
    const print = () => {
      console.log(res.length);
      if (res.length === 0) return;
      for (let i = 0; i < res.length; i++) console.log(res[i]);
    };
    if (sort(arr1, arr2)) {
      print();
      continue;
    }
    res = [];
    if (sort(arr2, arr1)) {
      print();
      continue;
    }
    console.log(-1);
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr1 = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr2 = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let res = [];
    const sort = (arr, arr1) => {
      for (let i = 0; i < n; i++) {
        let min = i;
        for (let j = i + 1; j < n; j++) {
          if (arr[min] > arr[j]) min = j;
        }
        if (min === i) continue;
        res.push(`${min + 1} ${i + 1}`);
        [arr[i], arr[min]] = [arr[min], arr[i]];
        [arr1[i], arr1[min]] = [arr1[min], arr1[i]];
      }
      for (let i = 1; i < n; i++) {
        if (arr1[i - 1] > arr1[i]) return false;
      }
      return true;
    };
    const print = () => {
      console.log(res.length);
      if (res.length === 0) return;
      for (let i = 0; i < res.length; i++) console.log(res[i]);
    };
    if (sort([...arr1], [...arr2])) {
      print();
      continue;
    }
    res = [];
    if (sort([...arr2], [...arr1])) {
      print();
      continue;
    }
    console.log(-1);
  }
};
solve();

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`\nTest #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

tests = [
``, // Test #1
``, // Test #2
``, // Test #3
``, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const calc = (testN)=>{
  // READING:
  let [n] = ra();
  let A = ra();
  let B = ra();
  LT({n, A, B});
  // PROCESSING:
  let P = [];
  for (let i=0; i<n; i++)
    P.push(i);
  let swaps = [];
  let swap = (i, j)=>{
    swaps.push((i+1)+' '+(j+1));
    let tmp = A[i];
    A[i] = A[j];
    A[j] = tmp;
    tmp = B[i];
    B[i] = B[j];
    B[j] = tmp;
  };
  for (let i=0; i<n; i++){
    for (let j=0; j<n-1; j++){
      if (A[j]==A[j+1]){
        if (B[j]>B[j+1]){
          swap(j, j+1);
        }
      } else {
        if (A[j]<A[j+1]){
          if (B[j]>B[j+1])
            print(-1);
        } else {
          if (B[j]<B[j+1])
            print(-1);
          swap(j, j+1);
        }
      }
    }
  }
  print(swaps.length);
  if (swaps.length)
    print(swaps.join('\n'))
};

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`\nTest #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

tests = [
``, // Test #1
``, // Test #2
``, // Test #3
``, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const calc = (testN)=>{
  // READING:
  let [n] = ra();
  let A = ra();
  let B = ra();
  LT({n, A, B});
  // PROCESSING:
  let P = [];
  for (let i=0; i<n; i++)
    P.push(i);
  let swaps = [];
  let swap = (i, j)=>{
    swaps.push((i+1)+' '+(j+1));
    let tmp = A[i];
    A[i] = A[j];
    A[j] = tmp;
    tmp = B[i];
    B[i] = B[j];
    B[j] = tmp;
  };
  for (let i=0; i<n; i++){
    for (let j=0; j<n-1; j++){
      if (A[j]==A[j+1]){
        if (B[j]>B[j+1]){
          swap(j, j+1);
        }
      } else {
        if (A[j]<A[j+1]){
          if (B[j]>B[j+1])
            return -1;
        } else {
          if (B[j]<B[j+1])
            return -1;
          swap(j, j+1);
        }
      }
    }
  }
  print(swaps.length);
  print(swaps.join('\n'))
};

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

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

/*---------------------------------------------------*/

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

const calc = (t)=>{
    /* read */
    let n = +readline();
    let a = ra();
    let b = ra();

    let moves = [];

    for (let i = 0; i < n; i++) {
        let minidx = i;
        let j = i + 1;
        for (; j < n; j++) {
            if (a[j] < a[minidx]) {
                minidx = j;
            }
        }
        if (minidx === i) continue;
        j = minidx;
        moves.push(`${i} ${j}`);

        let tmpa = a[i];
        a[i] = a[j];
        a[j] = tmpa;

        let tmpb = b[i];
        b[i] = b[j];
        b[j] = tmpb;
    }

    for (let l = 0; l < n - 1; l++) {
        let r = l + 1;
        while (r < n && a[l] === a[r]) {
            r++;
        }

        for (let i = l; i < r; i++) {
            let minidx = i;
            let j = i + 1
            for (; j < r; j++) {
                if (b[j] < b[minidx]) {
                    minidx = j;
                }
            }
            if (minidx === i) continue;
            j = minidx;
            moves.push(`${i} ${j}`);

            let tmpb = b[i];
            b[i] = b[j];
            b[j] = tmpb;
        }

    }

    if (moves.length > 10000) return '-1';

    for (let i = 1; i < n; i++) {
        if (b[i] < b[i - 1]) return '-1';
    }

    let result = `${moves.length}`;
    if (moves.length > 0) {
        result += '\n';
        result += moves.join('\n');
    }
    return result;
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc(t));
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\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;
}
var T = readline();
for(var qe=1;qe<=T;qe++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map((x) => parseInt(x));
  var b = readline().split(' ').map((x) => parseInt(x));
  var as = [...a]
  var bs = [...b]
  as.sort(function(x,y) { return x-y })
  bs.sort(function(x,y) { return x-y })
  // var rev_a = reverse(as);
  // var rev_b = reverse(bs);
  // function reverse(arr) {
  //   var v = [];
  //   for(var j=arr.length-1;j>=0;j--) v.push(arr[j]);
  //   return v;
  // }
  //console.log(a, as, rev_a);
  var ans = [];
  var flag = true;
  for(var i=0;i<n;i++) {
    var ok = false;
    for(var j=i;j<n;j++) {
      if(a[j] == as[i] && b[j] == bs[i]) {
        if(i != j) ans.push([i+1, j+1]);
        ok = true;
        a[j] = a[i];
        b[j] = b[i];
        break;
      }
    }
    if(!ok) flag = false;
  }
  if(!flag) console.log(-1);
  else {
    if(ans.length===0) console.log(0);
    else {
      for(var i=0;i<ans.length;i++) {
        console.log(ans[i].join(' '));
      }
    }
  }

  //console.log(ans);
  //fs.appendFileSync('output.txt', ans+'\r\n');

}
//


'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

    for(let i = 0; i<testNumbers; i++){
        solve(readline().split(" ").map(x=>parseInt(x)));
    }
}

function solve(input){
    let max = 0;
    let min = 21;
    for(let i = 0; i<3; i++){
        max = input[i] > max ? input[i] : max;
        min = input[i] < min ? input[i] : min;
    }
    console.log(
        input.filter(x=>x != max && x != min)[0]
    )
}

let buf='';

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

process.stdin.on('end', function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    for(let _=1;_<=t;_++)
    {
        let [a,b,c]=line[_].split(' ').map(x=>{return parseInt(x)});
        if(a>b) [a,b]=[b,a];
        if(a>c) [a,c]=[c,a];
        if(b>c) [b,c]=[c,b];
        console.log(b);
    }
})

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

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

    return gcd( b , a%b )
}

function main() {

    let t = parseInt(readLine());

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

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

        //console.log("a_b_c " + a_b_c)
        let min = Math.min(...a_b_c);
        let max = Math.max(...a_b_c);

        /*console.log("min " + min)
        console.log("max " + max)*/

        let medium = a_b_c.filter(x=>(x!=min)&&(x!=max))[0]

        //console.log("medium " + medium)

        console.log(medium)
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const testCases = Number(readline());
    for (let i = 0; i < testCases; i++) {
        let arr = readline().split(" ").map(elem => Number(elem));
        console.log(findMedium(arr))
    }
}

function findMedium(arr) {
    arr.sort((a, b) => a - b)
    return arr[1]
}

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 arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(arr) {
    arr.sort((a, b) => a - b)
    return arr[1]
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var list = nextIntArray(3);
		list.sort(function(a,b){
			return a - b;
		});
		myout(list[1]);
	}
}

t = +readline()

while(t--) {
    abc = readline().split(' ').map(value => +value).sort((a, b) => a - b)
    print(abc[1])
}

var t = +readline();

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

      var nums = [];
    var arr = readline().split(' ')

    print(ThreeNum(arr[0],arr[1],arr[2]))

}

function ThreeNum(a,b,c){
        a = +a
        b = +b
        c = +c

    return [a,b,c].sort((a,b) => a-b)[1]
}

var t = readline();

for(tt=0;tt<t;tt++){
    var arr = readline().split(' ');
    arr[0] = parseInt(arr[0])
    arr[1] = parseInt(arr[1])
    arr[2] = parseInt(arr[2])
    var x = arr[0] + arr[1] + arr[2];
    print(x - Math.min(arr[0],arr[1],arr[2]) - Math.max(arr[0],arr[1],arr[2]));
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main(){
    const testNumbers = readline()

    for(let i = 0; i<testNumbers; i++){
        solve(readline().split(" ").map(x=>parseInt(x)))
    }
}

function solve(input){
    let max = 0;
    let min = 21;
    for(let i = 0; i<3; i++){
        max = input[1] > max ? input[i] : max;
        min = input[i] < min ? input[i] : min;
    }
    console.log(
        input.filter(x=>x != max && x != min)[0]
    )
}

t = +readline()

while(t--) {
    abc = readline().split(' ').map(value => +value).sort()
    print(abc[1])
}


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

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

const INF = 1e9;

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();
		const a = rna();
		a.unshift(0);

		let ans = -INF;
		for (let i = n; i > Math.max(0, n-2*k); i--) {
			for (let j = i-1; j > Math.max(0, n-2*k); j--) {
				const cur = i*j - k*(a[i]|a[j]);
				ans = Math.max(ans, cur);
			}
		}

		console.log(ans);
	}
}

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++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        const args = lines[l++].trim().split(' ').map(Number)
        console.log(solve(n, k, args))
    }
// })()
})

function solve(n, k, arr) {
    let max = -Infinity
    const limit = 2 * k + 1
    for (let i = 0; i < limit; i++) {
        for (let j = 0; j < limit; j++) {
            if (i === j) continue

            const a = n - 1 - i
            const b = n - 1 - j
            if (a < 0 || b < 0) continue
            const v = (a + 1) * (b + 1) - k * (arr[a] | arr[b])
            // console.log(i, j, v)
            max = Math.max(max, v)
        }
    }
    return max
}

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

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

const INF = 1e9;

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();
		const a = rna();
		a.unshift(0);

		let ans = -INF;
		for (let i = n; i >= Math.max(1, n-k-5); i--) {
			for (let j = i-1; j >= Math.max(1, n-k-5); j--) {
				const cur = i*j - k*(a[i]|a[j]);
				ans = Math.max(ans, cur);
			}
		}

		console.log(ans);
	}
}

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

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

const INF = 1e9;

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();
		const a = rna();
		a.unshift(0);

		let ans = -INF;
		for (let i = n; i >= Math.max(1, n-k); i--) {
			for (let j = i-1; j >= Math.max(1, n-k); j--) {
				const cur = i*j - k*(a[i]|a[j]);
				ans = Math.max(ans, cur);
			}
		}

		console.log(ans);
	}
}

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

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

const INF = 1e9;

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();
		const a = rna();
		a.unshift(0);

		let ans = -INF;
		for (let i = n; i >= Math.max(1, n-k-5); i--) {
			for (let j = i-1; j >- Math.max(1, n-k-5); j--) {
				const cur = i*j - k*(a[i]|a[j]);
				ans = Math.max(ans, cur);
			}
		}

		console.log(ans);
	}
}

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

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

const INF = 1e9;

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();
		const a = rna();
		a.unshift(0);

		let ans = -INF;
		for (let i = n; i > n-k; i--) {
			for (let j = i-1; j > n-k; j--) {
				const cur = i*j - k*(a[i]|a[j]);
				ans = Math.max(ans, cur);
			}
		}

		console.log(ans);
	}
}


main.apply(0, readNums());
function main(n, m) {
    var max = 0;
    for (var i = 0; i < n; i++) {
        var v = min(readNums());
        if (v > max)
            max = v;
    }
    print(max);
}
function readNums() {
    return readline().split(' ').map(function(v) {
        return v - 0;
    })
}
function min(arr) {
    var v = arr[0];
    for (var i = 1; i < arr.length; i++) {
        if (v > arr[i])
            v = arr[i];
    }
    return v;
}

function cmp(a,b){return a-b;}

s=readline().split(' ')
n=+s[0]
m=+s[1]
res=0
while(n--)
{
    a=readline().split(' ')
    a.sort(cmp)
    if (+a[0]>res)
    {
        res=+a[0]
    }
}
print(res)


(function main(){

    var t = readline();
    while(t--){
        var num = readline();
        var word = [];
        var obj = {

        }
        for(var i=0;i<3;i++){
            word[i] = readline().split(' ');
            for(var j=0;j<num;j++){
                if(typeof obj[word[i][j]] === 'undefined'){
                    obj[word[i][j]] = 1;
                }else{
                    obj[word[i][j]]++;
                }
            }
        }
        var result = "";

        for(var i=0;i<3;i++){
            var sum = 0;
            for(var j=0;j<num;j++){
                if(obj[word[i][j]]==1){
                    sum+=3;
                }else if(obj[word[i][j]]==2){
                    sum+=1;
                }
            }
            if(i){
                result=result+" "+sum;
            }else{
                result=result+sum;
            }
        }
        print(result);

    }

})();

var t = parseInt(readline());

var calc = (ob1, ob2, ob3) => {
    var res = 0;
    for(var k in ob1){
        if(!ob2[k] && !ob3[k]) res += 3;
        else if (!ob2[k] || !ob3[k] ) res += 1;
    }

    return res;
};

var toObj = (r) => {
    var obj = {}
    for(var i = 0; i < r.length; i++){
        obj[r[i]] = true
    }
    return obj
}

while(t--){
    var n = parseInt(readline());
    var r1 = readline().split(" ");
    var r2 = readline().split(" ");
    var r3 = readline().split(" ");

    var ob1 = toObj(r1);
    var ob2 = toObj(r2);
    var ob3 = toObj(r3);

    var res1 = calc(ob1, ob2, ob3);
    var res2 = calc(ob2, ob1, ob3);
    var res3 = calc(ob3, ob2, ob1);

    print(res1 + " " + res2 + " " + res3);

}

var limit = parseInt(readline());
    for (var i = 0; i < limit; i++) {
        var caseLength = parseInt(readline());
        var firstArray = readline().split(" ");
        var secondArray = readline().split(" ");
        var thirdArray = readline().split(" ");
        var firstMap = new Map();
        var secondMap = new Map();
        var thirdMap = new Map();
        for (var j = 0; j < caseLength; j++) {
            firstMap.set(firstArray[j], 1);
            secondMap.set(secondArray[j], 1);
            thirdMap.set(thirdArray[j], 1);
        }
        var firstTotal = 0;
        var secondTotal = 0;
        var thridTotal = 0;
        for (var j = 0; j < caseLength; j++) {
            if (!secondMap.has(firstArray[j]) && !thirdMap.has(firstArray[j])) {
                firstTotal += 3;
            }
            else if ((!secondMap.has(firstArray[j]) && thirdMap.has(firstArray[j])) ||
                (secondMap.has(firstArray[j]) && !thirdMap.has(firstArray[j]))) {
                firstTotal++;
            }
            if (!firstMap.has(secondArray[j]) && !thirdMap.has(secondArray[j])) {
                secondTotal += 3;
            }
            else if ((!firstMap.has(secondArray[j]) && thirdMap.has(secondArray[j])) ||
                (firstMap.has(secondArray[j]) && !thirdMap.has(secondArray[j]))) {
                secondTotal++;
            }
            if (!firstMap.has(thirdArray[j]) && !secondMap.has(thirdArray[j])) {
                thridTotal += 3;
            }
            else if ((firstMap.has(thirdArray[j]) && !secondMap.has(thirdArray[j])) ||
                (!firstMap.has(thirdArray[j]) && secondMap.has(thirdArray[j]))) {
                thridTotal++;
            }
        }
        print("".concat(firstTotal, " ").concat(secondTotal, " ").concat(thridTotal));
    }

var t = parseInt(readline());

for (var test = 0; test < t; test++) {
    var n = parseInt(readline());
    var pl1 = readline().split(' ');
    var pl2 = readline().split(' ');
    var pl3 = readline().split(' ');

    var ans = [];

    var arr = pl1.concat(pl2).concat(pl3);
    var map = new Map();

    for (var i = 0; i < 3 * n; i++) {
        var mapEl = map.get(arr[i]);
        if (!mapEl) {
            map.set(arr[i], 1);
        } else {
            map.set(arr[i], mapEl + 1);
        }
    }

    var counter = pl => {
        var count = 0;

        for (var i = 0; i < n; i++) {
            if (map.get(pl[i]) === 1) {
                count += 3;
            } else if (map.get(pl[i]) === 2) {
                count += 1;
            }
        }

        return count;
    }

    ans.push(counter(pl1));
    ans.push(counter(pl2));
    ans.push(counter(pl3));

    print(ans.join(' '));
}

var n, a;

    var tests = parseInt(readline());
    for (var t=0; t<tests;t++) {
        n = parseInt(readline());
        a = [];
        for (var i = 0; i < 3; i++) {
            a.push(readline().split(' '));
        }
        var m = {};
        for (var i = 0; i < n; i++) {
            for (var j = 0; j < 3; j++) {
                if (!m[a[j][i]]) {
                    m[a[j][i]] = 0;
                }
                m[a[j][i]]++;
            }
        }
        var ans = [0, 0, 0];
        for (var i = 0; i < n; i++) {
            for (var j = 0; j < 3; j++) {
                var c = m[a[j][i]];
                if (c == 1) {
                    ans[j] += 3;
                } else if (c == 2) {
                    ans[j] += 1;
                }
            }
        }

        print(ans.join(' '));
    }

var t = +readline();

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

      var nums = [];
    var t1 = +readline();
    var list = [];
    var arr1 = readline().split(' ');
    var arr2 = readline().split(' ');
    var arr3 = readline().split(' ');

    print(WordGame(arr1,arr2,arr3))

}

function WordGame(arr1,arr2,arr3){

    var set1 = new Set();
    var set2 = new Set();
    var set3 = new Set();

    for(var i = 0; i<arr1.length; i++){
        set1.add(arr1[i])
        set2.add(arr2[i])
        set3.add(arr3[i]);
    }

    var c1 = 0;
    var c2 = 0;
    var c3 = 0;
    for(var each of arr1){
        var test = set2.has(each) + set3.has(each)
        if (test === 1) c1 += 1;
        if (test === 0) c1 += 3;
    }
    for(var each1 of arr2){
        var test1 = set1.has(each1) + set3.has(each1)
        if (test1 === 1) c2 += 1;
        if (test1 === 0) c2 += 3;
    }
    for(var each2 of arr3){
        var test2 = set1.has(each2) + set2.has(each2)
        if (test2 === 1) c3 += 1;
        if (test2 === 0) c3 += 3;
    }
    return [c1,c2,c3].join(' ');
}

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

let lines = []

const createReadLine = () => {
  i = 0;
  return () => {
    return lines[i++]
  }
}

rl.on('line', line => lines.push(line))
rl.on('close', () => {
  const readLine = createReadLine();
  let t = parseInt(readLine())
  while (t--) {
    let words = {}
    let n = readLine()
    for (let i = 0; i < 3; i++){
      let playerWords = readLine().split(' ')
      for (const word of playerWords) {
        if (words[word]) {
          words[word].push(i)
        } else {
          words[word] = [i]
        }
      }
    }

    let result = {
      0: 0,
      1: 0,
      2: 0,
    };

    for (const word in words) {
      if (words.hasOwnProperty(word)) {
        if (words[word].length === 1) {
          result[words[word][0]] += 3
        } else if (words[word].length === 2) {
          result[words[word][0]] += 1
          result[words[word][1]] += 1
        }
      }
    }

    console.log(result['0'], result['1'], result['2'])
  }
})

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);

        let a = readline().split(' ');
        let b = readline().split(' ');
        let c = readline().split(' ');

        let arr = [...a, ...b, ...c];

        let freq = {};
        for (let i = 0; i < arr.length; i++) {
            if (freq[arr[i]]) {
                freq[arr[i]]++;
            } else {
                freq[arr[i]] = 1;
            }
        }

        const val = word => {
            if (freq[word] === 1) {
                return 3;
            } else if (freq[word] === 2) {
                return 1;
            } else if (freq[word] === 3) {
                return 0;
            }
        };

        let sa = a.reduce((acc, curr) => acc + val(curr), 0);
        let sb = b.reduce((acc, curr) => acc + val(curr), 0);
        let sc = c.reduce((acc, curr) => acc + val(curr), 0);

        output(`${sa} ${sb} ${sc}`);
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const numberOfTest = Number.parseInt(readline());
    for(let i=0; i<numberOfTest; i++){
        readline();
        const str1 = readline();
        const str2 = readline();
        const str3 = readline();
        Solution(str1, str2, str3);
    }
}

function Solution(s1, s2, s3){
    const frqncy = {};
    const s1Words = s1.split(" ");
    const s2Words = s2.split(" ");
    const s3Words = s3.split(" ");
    s1Words.forEach(word => {
        if(frqncy[word]){
            frqncy[word] = frqncy[word]+1
        } else {
            frqncy[word]= 1;
        }
    });
    s2Words.forEach(word => {
        if(frqncy[word]){
            frqncy[word] = frqncy[word]+1
        } else {
            frqncy[word]= 1;
        }
    });
    s3Words.forEach(word => {
        if(frqncy[word]){
            frqncy[word] = frqncy[word]+1
        } else {
            frqncy[word]= 1;
        }
    });
    const s1Count = s1Words.reduce((acc, curr)=> {
        if(frqncy[curr] == 2){
            acc += 1
        }else if(frqncy[curr] == 1){
            acc += 3
        }
        return acc;
    }, 0);
    const s2Count = s2Words.reduce((acc, curr)=> {
        if(frqncy[curr] == 2){
            acc += 1
        }else if(frqncy[curr] == 1){
            acc += 3
        }
        return acc;
    }, 0);

    const s3Count = s3Words.reduce((acc, curr)=> {
        if(frqncy[curr] == 2){
            acc += 1
        }else if(frqncy[curr] == 1){
            acc += 3
        }
        return acc;
    }, 0);
    console.log(`${s1Count} ${s2Count} ${s3Count}`);
}

let readline = require("readline");
const { start } = require("repl");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);

  if (input.length === +input[0] * 4 + 1) {
    // call your function here
    solve(input);
    rl.close();
  }
});

let solve = (input) => {
  //console.log(input[1 + 1].split(" "));

  for (let i = 1; i < input.length; i += 4) {
    let words1 = input[i + 1].split(" ");
    let words2 = input[i + 2].split(" ");
    let words3 = input[i + 3].split(" ");

    let words1Map = {};
    let words2Map = {};
    let words3Map = {};

    for (const word of words1) {
      words1Map[word] = true;
    }

    for (const word of words2) {
      words2Map[word] = true;
    }
    for (const word of words3) {
      words3Map[word] = true;
    }

    let score1 = 0;
    let score2 = 0;
    let score3 = 0;

    for (const word of words1) {
      if (words2Map[word] && words3Map[word]) continue;
      else if (words2Map[word] || words3Map[word]) score1++;
      else score1 += 3;
    }

    for (const word of words2) {
      if (words1Map[word] && words3Map[word]) continue;
      else if (words1Map[word] || words3Map[word]) score2++;
      else score2 += 3;
    }

    for (const word of words3) {
      if (words1Map[word] && words2Map[word]) continue;
      else if (words1Map[word] || words2Map[word]) score3++;
      else score3 += 3;
    }

    console.log(`${score1} ${score2} ${score3}`);
  }
};

let fs = require("fs");
let sc = {
    _buf: new Buffer.alloc(1 << 14),
    _bufPos: 0,
    _bufLen: 0,
    _ensure: function ()
    {
        if (this._bufPos === this._bufLen)
        {
            this._bufPos = 0;
            this._bufLen = fs.readSync(0, this._buf, 0, this._buf.length, null);
        }
    },
    _isws: function (ch)
    {
        return ch === 32 || ch === 9 || ch === 10 || ch === 13;
    },
    _islf: function (ch)
    {
        return ch === 10 || ch === 13;
    },
    _peekChar: function ()
    {
        this._ensure();
        return this._bufPos === this._bufLen ? 0 : this._buf[this._bufPos];
    },
    _skipWs: function ()
    {
        while (this._isws(this._peekChar()))
            this._bufPos++;
    },
    _readUntil: function (stop)
    {
        this._ensure();
        if (this._bufPos === this._bufLen)
            throw new Error("eof");
        let start = this._bufPos;
        let before = null;
        for (; ;)
        {
            if (this._bufPos === this._bufLen)
            {
                let len = this._bufPos - start, preLen = (before ? before.length : 0);
                let nbuf = new Buffer(len + preLen);
                if (before)
                    before.copy(nbuf);
                before = nbuf;
                this._buf.copy(before, preLen, start);
                this._ensure();
                start = this._bufPos;
            }
            if (this._bufPos === this._bufLen || stop(this._buf[this._bufPos])) break;
            this._bufPos++;
        }
        if (!before)
            return this._buf.toString("utf8", start, this._bufPos);
        let after = this._buf.slice(start, this._bufPos);
        let res = new Buffer(before.length + after.length);
        before.copy(res);
        after.copy(res, before.length);
        return res.toString();
    },

    nextToken: function ()
    {
        this._skipWs();
        return this._readUntil(this._isws);
    },
    L: function ()
    {
        let line = this._readUntil(this._islf);
        if (this._peekChar() === 13) this._bufPos++;
        if (this._peekChar() === 10) this._bufPos++;
        return line;
    },
    N: function ()
    {
        return +this.nextToken();
    },
    S: function ()
    {
        return this.nextToken();
    }
};

// DO NOT CHANGE TEMPLATE BEFORE

const Def = Number(1e9);

const LowerBound = (arr, val) =>
{
    let ng = -1;
    let ok = arr.length;
    while (ok - ng > 1)
    {
        let med = (ok + ng) / 2 | 0;
        if (arr[med] >= val)
        {
            ok = med;
        }
        else
        {
            ng = med;
        }
    }

    return ok;
}

const ReverseLowerBound = (arr, val) =>
{
    let ng = 0;
    let ok = arr.length;
    while (ok - ng > 1)
    {
        let med = (ok + ng) / 2 | 0;
        if (arr[med] <= val)
        {
            ng = med;
        }
        else
        {
            ok = med;
        }
    }
    // Находит наибольший элемент который меньше или равен val
    return ng;
}

const ReverseUpperBound = (arr, val) =>
{
    let ng = 0;
    let ok = arr.length;
    while (ok - ng > 1)
    {
        let med = (ok + ng) / 2 | 0;
        if (arr[med] < val)
        {
            ng = med;
        }
        else
        {
            ok = med;
        }
    }
    // Находит наибольший элемент который меньше val
    return ng;
}

const UpperBound = (arr, val) =>
{
    let ok = arr.length;
    let ng = -1;
    while (ok - ng > 1)
    {
        let med = (ok + ng) / 2 | 0;
        if (arr[med] > val)
        {
            ok = med;
        }
        else
        {
            ng = med;
        }
    }

    return ok;
}

const Solve = () =>
{
    let map1 = new Map();
    let map2 = new Map();
    let map3 = new Map();

    let n = +sc.L();
    let l1 = sc.L().split(' ');
    let l2 = sc.L().split(' ');
    let l3 = sc.L().split(' ');
    let map = new Map();

    for (let s of l1)
    {
        map1.set(s, 1);

        if (map.has(s))
        {
            map.set(s, map.get(s) + 1);
        }
        else map.set(s, 1);
    }

    for (let s of l2)
    {
        map2.set(s, 2);

        if (map.has(s))
        {
            map.set(s, map.get(s) + 1);
        }
        else map.set(s, 1);
    }

    for (let s of l3)
    {
        map3.set(s, 3);

        if (map.has(s))
        {
            map.set(s, map.get(s) + 1);
        }
        else map.set(s, 1);
    }

    let one = 0, two = 0, three = 0;
    for (let [key, value] of map)
    {
        let c = 0;

        if (map1.has(key))
        {
            ++c;
        }

        if (map2.has(key)) ++c;

        if (map3.has(key)) ++c;

        if (c === 2)
        {
            if (map1.has(key)) ++one;
            if (map2.has(key)) ++two;
            if (map3.has(key)) ++three;
        }
        else if (c === 1)
        {
            if (map1.has(key)) one += 3;
            if (map2.has(key)) two += 3;
            if (map3.has(key)) three += 3;
        }
    }

    console.log(`${one} ${two} ${three}`);

}

const main = () =>
{
    let cases = +sc.L();
    while (cases-- > 0) Solve();

    // Solve();
}
main();

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var map = {};
		var one = nextStrArray(N);
		var two = nextStrArray(N);
		var three = nextStrArray(N);
		var oneP = 0;
		var twoP = 0;
		var threeP = 0;
		for(var i = 0; i < N; i++){
			if(map[one[i]] == null){
				map[one[i]] = 0;
			}
			map[one[i]]++;
			if(map[two[i]] == null){
				map[two[i]] = 0;
			}
			map[two[i]]++;
			if(map[three[i]] == null){
				map[three[i]] = 0;
			}
			map[three[i]]++;
		}
		for(var i = 0; i < N; i++){
			if(map[one[i]] == 1){
				oneP += 3;
			}else if(map[one[i]] == 2){
				oneP++;
			}
			if(map[two[i]] == 1){
				twoP += 3;
			}else if(map[two[i]] == 2){
				twoP++;
			}
			if(map[three[i]] == 1){
				threeP += 3;
			}else if(map[three[i]] == 2){
				threeP++;
			}
		}
		myout(oneP + " " + twoP + " " + threeP);
	}
}

const readline = require('readline')

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

function solve(n, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr[i].length; j++) {
            const s = arr[i][j]
            map[s] = (map[s] || 0) + 1
        }
    }
    // return [n, arr]
    // console.log(map)
    return arr.map(x => {
        let p = 0
        for (let i = 0; i < x.length; i++) {
            const s = x[i]
            if (map[s] === 1) {
                p += 3
            } else if (map[s] === 2) {
                p += 1
            }
        }
        return p
    }).join(' ')
}


process.stdin.resume();
process.stdin.setEncoding("ascii");

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on("data", function (data) {
  input_stdin += data;
});

process.stdin.on("end", function () {
  input_stdin_array = input_stdin.split("\n");
  // console.log(input_stdin_array);
  main();
});

function readLine() {
  return input_stdin_array[input_currentline++];
}

function main() {
  var a = readLine();
  while (a--) {
    var b = readLine();
    var c = readLine();
    var res = solveMeFirst(b, c);
    // let out = "";
    // if (res) {
    //   for (let i = 0; i < res.length; i++) {
    //     out += res[i] + " ";
    //   }
    console.log(res);
    // }
  }
}
function solveMeFirst(n, arr) {
  arr = arr.split(" ");
  arr[arr.length - 1] = arr[arr.length - 1].replace("\r", "");
  arr.sort((a, b) => +a - +b);
  if (arr.length > 1) {
    if (
      +arr[arr.length - 1] - +arr[arr.length - 2] == 1 ||
      +arr[arr.length - 1] - +arr[arr.length - 2] == 0
    ) {
      return "YES";
    } else {
      return "NO";
    }
  } else {
    if (+arr[0] == 1) return "YES";
    else return "NO";
  }
}

// console.log(solveMeFirst(2, [2, 3, 2, 4, 1, 3, 4, 1]));
// console.log(timeConversion([100, 90, 90, 80], [70, 80, 105]));

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());
    }
}
function solve() {
    const t = parseInt(readLine());
    const arr = readLine().split(" ").map(i => parseInt(i)).sort((a, b) => a - b);
    let last = arr[arr.length - 1]
    if (t == 1 && last > 1) return "NO";
    if (t == 1 && last == 1) return "YES";
    if ((last - arr[arr.length - 2]) > 1) return "NO"
    return "YES";
}

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

module.exports = E;

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

const EPS = 1e-6;

const calc = (arr, n)=>{
  arr.sort((a, b)=>b-a);
  if (n==1)
    return arr[0]==1;
  return arr[0]-arr[1]<2;
  for (let i=0; i<n-1; i++){
    if (arr[i]>arr[i+1]+1)
      return false;
    arr[i+1] = 0;
  }
  return true;
};

function main() {
    let T = +readline();
    while (T--){
      let n = +readline();
      let a = ra();
      print(calc(a, n) ? 'yes' : 'no')
    }
}

E.calc = calc;

var t = readline();
    for(var i = 0 ; i < t ; i++){
        var n = readline(),
            a = readline().split(' ').sort((a,b)=>{return(a - b)}).reverse();
            if(n == 1 && a[0] > 1){
                print("NO");
            }
            else if(a[0] - a[1] > 1){
                    print('NO');
                }
            else{
                print('YES');
            }
    }

var tests = parseInt(readline());
    for (var t=0; t < tests; t++) {
        var n = parseInt(readline());
        var a = readline().split(' ').map(x=>parseInt(x));
        var ans = 'YES';
        if (n == 1) {
            if (a[0] != 1) {
                ans = 'NO'
            }
        } else {
            var max = Math.max(...a);
            a.splice(a.indexOf(max), 1);
            var second = Math.max(...a);
            if (max - second > 1) {
                ans = 'NO'
            }
        }
        print(ans);
    }

var t = readline();

for (var i = 0; i < t; i++) {
  var n = readline();
  var c = readline().split(' ').map(Number);
  c.sort((a,b) => b - a);

  if (c[0] - c[1] <= 1 || c[0] === 1) print('YES');
  else {
    print('NO');
  }
}

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

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let arr = readline().split(' ').map(Number);

        arr.sort((a, b) => b - a);

        if (arr.length === 1 && arr[0] > 1) {
            output('NO');
        } else if (arr[0] - 1 > arr[1]) {
            output('NO');
        } else {
            output('YES');
        }
    }
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		list.sort(function(a,b){
			return b - a;
		});
		var max = list[0];
		if(N == 1){
			if(max > 1){
				myout("NO");
			}else{
				myout("YES");
			}
		}else{
			var nx = list[1];
			if(max > nx + 1){
				myout("NO");
			}else{
				myout("YES");
			}
		}
	}
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main(){
	let t = parseInt(readLine());
	while(t--){
		let n = parseInt(readLine());
		let ans = true;
		const arr = readLine().split(' ');
		if(n == 1){
			if(parseInt(arr[0]) > 1)console.log("NO");
			else console.log("YES");
			continue;
		}
		arr.sort(function(a, b){return b - a});
		if(arr[0] - 1 > arr[1])ans = false;
		console.log((ans? "YES" : "NO"));
	}

}

process.stdin.resume();process.stdin.setEncoding('utf-8');let inputString = '';let currentLine = 0;process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; }

function main() {
  const N = readLine();
  for (let i = 0; i < N; i++) {
    const n = Number(readLine());
    const arr = readLine().split(' ').map(Number);
    arr.sort((x, y) => x - y);
    if (n === 1) {
      console.log(arr[0] === 1 ? 'YES' : 'NO');
    } else {
      console.log(arr[arr.length - 1] - arr[arr.length - 2] >=2 ? 'NO' : 'YES');
    }
  }
}

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

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

function main() {
  let t = parseInt(readLine());

  for (let i = 0; i < t; i++) {
    let n = parseInt(readLine());
    let arr = readLine().split(" ").map(Number);
    arr.sort((a, b) => a - b);

    if (n == 1) {
      if (arr[0] > 1) {
        console.log("NO");
      } else {
        console.log("YES");
      }
    } else {
      if (arr[n - 2] + 1 < arr[n - 1]) {
        console.log("NO");
      } else {
        console.log("YES");
      }
    }
  }
}

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

let stepeni = [1, 2]
let stepen = function (n) {
    if (stepeni[n]) return stepeni[n];
    let l = stepeni.length - 1;
    while (l < n) {
        stepeni.push(2 * stepeni[l++]);
    }
    return stepeni[n];
}

let parser = e=>parseInt(e);
let sorter = (a,b)=>a-b;

function main() {
    let k = parseInt(readLine());
    for(let i = 0; i<k;i++){
        let n = parseInt(readLine());
        let niz = readLine().split(" ").map(parser).sort(sorter);
        let sme = 1;
        let preth = niz.pop();
        let flag = true;
        if(n==1){
            flag = (preth==1);
        }
        else {
            while(niz.length>0){
                let br = niz.pop();
                if(preth-br>sme){
                    flag = false;
                    break;
                }
                sme+=br;
                preth = br;
            }
        }
        console.log(flag?"YES":"NO");
    }
}

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

const n = Number(inputs[0])

main(n, inputs)

function main(_, lines) {
  let res = []
  next: for (let i = 0; i < _; i++) {
    const n = Number(lines[i * 2 + 1])
    const data = lines[i * 2 + 2].trim().split(' ').map(Number)

    data.sort((a, b) => b - a)
    if ((data.length === 1 && data[0] > 1) || data[0] > data[1] + 1) {
      res.push('NO')
    } else {
      res.push('YES')
    }
  }

  console.log(res.join('\n'))
}

const readline = require('readline')

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

function solve(n, arr) {
    if (n === 1) return arr[0] <= 1

    arr.sort((a, b) => b - a)
    return arr[0] - arr[1] <= 1
}

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


function query(l, r, x, lx, rx) {
  if (lx >= r || rx <= l) return 0;
  if (lx >= l && rx <= r) return tree[x];
  var m = (lx + rx) / 2;
  var left = query(l, r, 2 * x + 1, lx, m),
    right = query(l, r, 2 * x + 2, m, rx);
  return Math.max(left, right);
}

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

var arr = readline().split(" ");
for (var i = 0; i < n; i++) {
  arr[i] = parseInt(arr[i]);
}

var N = 1;
while (N < arr.length) N *= 2;
tree = new Array(N * 2);
for (var i = 0; i < arr.length; i++) {
  tree[N - 1 + i] = arr[i];
}
for (var i = N - 2; i >= 0; i--) {
  var left = tree[2 * i + 1],
    right = tree[2 * i + 2];
  tree[i] = Math.max(left, right);
}

var q = parseInt(readline(), 10);
while (q--) {
  l = readline().split(" ");
  for (var i = 0; i < l.length; i++) l[i] = parseInt(l[i]);
  var xs = --l[0],
    ys = --l[1],
    xf = --l[2],
    yf = --l[3],
    k = l[4];
  xs = m - xs - 1;
  xf = m - xf - 1;
  if (ys > yf) {
    var temp = ys;
    ys = yf;
    yf = temp;
    temp = xs;
    xs = xf;
    xf = temp;
  }
  if ((xf - xs) % k !== 0 || (yf - ys) % k !== 0) {
    print("NO");
  } else {
    var x = xs % k;
    if (x < m - query(ys, yf, 0, 0, N)) {
      print("YES");
    } else {
      print("NO");
    }
  }
}

function query(l, r, x, lx, rx) {
  if (lx >= r || rx <= l) return 0;
  if (lx >= l && rx <= r) return tree[x];
  var m = (lx + rx) / 2;
  var left = query(l, r, 2 * x + 1, lx, m),
    right = query(l, r, 2 * x + 2, m, rx);
  return Math.max(left, right);
}

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

var arr = readline().split(" ");
for (var i = 0; i < n; i++) {
  arr[i] = parseInt(arr[i]);
}

var N = 1;
while (N < arr.length) N *= 2;
tree = new Array(N * 2);
for (var i = 0; i < arr.length; i++) {
  tree[N - 1 + i] = arr[i];
}
for (var i = N - 2; i >= 0; i--) {
  var left = tree[2 * i + 1],
    right = tree[2 * i + 2];
  tree[i] = Math.max(left, right);
}

var q = parseInt(readline(), 10);
while (q--) {
  l = readline().split(" ");
  for (var i = 0; i < l.length; i++) l[i] = parseInt(l[i]);
  var xs = --l[0],
    ys = --l[1],
    xf = --l[2],
    yf = --l[3],
    k = l[4];
  xs = m - xs - 1;
  xf = m - xf - 1;
  if (ys > yf) {
    var temp = ys;
    ys = yf;
    yf = temp;
    temp = xs;
    xs = xf;
    xf = temp;
  }
  if ((xf - xs) % k !== 0 || (yf - ys) % k !== 0) {
    print("NO\n");
  } else {
    var x = xs % k;
    if (x < m - query(ys, yf, 0, 0, N)) {
      print("YES\n");
    } else {
      print("NO\n");
    }
  }
}

'use strict';

function solve(n, m, q, a, b) {
  const segTree = new SegTree(m);
  for (let i = 0; i < m; i++) {
    segTree.update(i, a[i]);
  }
  let res = new Array(q);
  for (let i = 0; i < q; i++) {
    let [x1, y1, x2, y2, k] = b[i];
    if (Math.abs(x2 - x1) % k !== 0 || Math.abs(y2 - y1) % k !== 0) {
      res[i] = 'NO';
    } else if (y1 === y2) {
      res[i] = 'YES';
    } else {
      let max = 0;
      if (y1 > y2) {
        max = segTree.query(y2, y1 - 2);
      } else {
        max = segTree.query(y1, y2 - 2);
      }
      const cur = Math.floor((n - x1) / k) * k + x1;
      if (cur > max) {
        res[i] = 'YES';
      } else {
        res[i] = 'NO';
      }
    }
  }
  return res.join('\n');
}
class SegTree {
  constructor(n) {
    this.n = n;
    this.root = this._newNode();
    this.update = (x, z) => {
      x = Math.max(x, 0);
      x = Math.min(x, n);
      this._update(this.root, 0, n, x, 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 {
      max: 0,
      left,
      right
    };
  }
  _up(node) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    node.max = Math.max(left.max, right.max);
  }
  _update(node, l, r, x, z) {
    if (!node) return;
    if (l === r) {
      node.max = z;
      return;
    }
    const mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    if (x <= mid) this._update(node.left, l, mid, x, z);else this._update(node.right, mid + 1, r, x, z);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return 0;
    if (!node) return 0;
    if (l === x && r === y) return node.max;
    let res = 0,
        mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    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 res = Math.max(this._query(node.left, l, mid, x, mid), this._query(node.right, mid + 1, r, mid + 1, y));
    return res;
  }
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      const b = [];
      const k = Number(await read());
      let tmp = k;
      while (tmp--) {
        b.push((await read()).split(' ').map(Number));
      }
      res[i] = solve(n, m, k, 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);
  process.stdout.write(output);
});