There's a chip in the point $$$(0, 0)$$$ of the coordinate plane. In one operation, you can move the chip from some point $$$(x_1, y_1)$$$ to some point $$$(x_2, y_2)$$$ if the Euclidean distance between these two points is an integer (i.e. $$$\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}$$$ is integer).Your task is to determine the minimum number of operations required to move the chip from the point $$$(0, 0)$$$ to the point $$$(x, y)$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3000$$$) — number of test cases. The single line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 50$$$) — the coordinates of the destination point.

For each test case, print one integer — the minimum number of operations required to move the chip from the point $$$(0, 0)$$$ to the point $$$(x, y)$$$.

NoteIn the first example, one operation $$$(0, 0) \rightarrow (8, 6)$$$ is enough. $$$\sqrt{(0-8)^2+(0-6)^2}=\sqrt{64+36}=\sqrt{100}=10$$$ is an integer.In the second example, the chip is already at the destination point.In the third example, the chip can be moved as follows: $$$(0, 0) \rightarrow (5, 12) \rightarrow (9, 15)$$$. $$$\sqrt{(0-5)^2+(0-12)^2}=\sqrt{25+144}=\sqrt{169}=13$$$ and $$$\sqrt{(5-9)^2+(12-15)^2}=\sqrt{16+9}=\sqrt{25}=5$$$ are integers.

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

let is_sq = (x, y)=>{
  let sq = Math.sqrt((x*x)+(y*y));
  let rsq = Math.round(Math.sqrt((x*x)+(y*y)));
  return Math.abs(sq*sq-rsq*rsq)<EPS;
};

let caches = new Map();
let rec = (x, y)=>{
  if (x==0 && y==0)
    return 0;
  if (x>y)
    return rec(y, x);
  if (is_sq(x, y))
    return 1;
  let k = x+';'+y;
  if (caches.has(k))
    return caches.get(k)
  let min = Infinity;
  for (let dx = 0; dx<=x; dx++){
    for (let dy = 0; dy<=y; dy++){
      if (dx==x && dy==y || dx==0 && dy==0)
        continue;
      if (is_sq(dx, dy))
        min = Math.min(min, rec(x-dx, y-dy)+1);
    }
  }
  caches.set(k, min);
  return min;
};

function main() {
    let n = +readline();
    for (let i=0; i<n; i++){
      let [x, y] = readline().split(' ').map(a=>+a);
      if (x==0 && y==0)
        print(0);
      else if(is_sq(x, y))
        print(1);
        else
        print(2);
    }
}

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 [x,y]=line[_].split(' ').map(x=>{return parseInt(x)});
        let z=Math.floor(Math.sqrt(x*x+y*y));
        if(x===0&&y===0)
        {
            console.log(0);
        }
        else if(z*z===x*x+y*y)
        {
            console.log(1);
        }
        else
        {
            console.log(2);
        }
    }
})

function solve(arr) {
  let data = [...arr];
  data.shift();
  data = data.map((item) => item.split(" ").map((num) => parseInt(num)));
  data.forEach((item) => {
    const x = item[0];
    const y = item[1];
    const len = Math.sqrt(x * x + y * y);
    if (len === 0) {
      console.log(0);
    } else if (len.toString().includes(".")) {
      console.log(2);
    } else {
      console.log(1);
    }
  });
}
let text = "";
process.stdin.resume();
process.stdin.setEncoding("utf-8");
process.stdin.on("data", (t) => {
  if (t === "\r\n" || t === "\n") {
    process.stdin.emit("end");
  } else {
    text += t;
  }
});
process.stdin.on("end", () => {
  const input = text.trim().replace(/\r/g, "").split("\n");
  solve(input);
  process.exit();
});

const readline = require('readline')
let r = readline.createInterface({
    input:process.stdin,
    output:process.stdout
})
r.on('line',line=> {
    let data = line.split(' ')
    let [a,b] = data
    if(data.length==1) return
    let s = a*a+b*b
    if(+a===0&&+b===0) console.log(0)
    else if(Number.isInteger(Math.sqrt(s))) console.log(1)
    else console.log(2)
})

const main = (input) => {
  input = input.trim().split('\n')

  const xy = input.slice(1).map((a) => a.split(' ').map((b) => Number(b)))
  const ans = xy.map(([x, y]) => {
    if (x === 0 && y === 0) {
      return 0
    } else if (Number.isInteger(Math.sqrt(x * x + y * y))) {
      return 1
    } else {
      return 2
    }
  })
  console.log(ans.join('\n'))
}

main(require('fs').readFileSync(0).toString())

const main = (input) => {
  input = input.trim().split('\n')

  const xy = input.slice(1).map((a) => a.split(' ').map((b) => Number(b)))
  const ans = xy.map(([x, y]) => {
    if (x === 0 && y === 0) {
      return 0
    } else if (Math.sqrt(x * x + y * y) % 1 === 0) {
      return 1
    } else {
      return 2
    }
  })
  console.log(ans.join('\n'))
}

main(require('fs').readFileSync(0).toString())

let text = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (t) => {
    if (t === '\r\n' || t === '\n') {
        process.stdin.emit('end');
    } else {
        text += t;
    }
});

class TreeNode {
    constructor(nodeVal) {
        this.nodeVal = nodeVal;
        this.nodeSum = 0;
        this.toParentVal = 0;
        this.related = [];
    }
}

process.stdin.on('end', () => {
    const input = text.trim().replace(/r/g, '').split('\n');
    const total = Number(input[0]);
    for (let i = 1; i <= total; i++) {
        console.log(solve(input[i]));
    }

    process.exit();
});

function solve(str) {
    const [a, b] = str.split(' ').map((ele) => +ele);
    if (!a && !b) {
        return 0;
    }
    const math = Math.sqrt(a * a + b * b);
    if (math >> 0 === math) {
        return 1;
    }
    return 2;
}

function solve(x, y) {
    let result;
    if (x === 0 && y === 0) {
        result = 0;
    } else if (Math.sqrt(x ** 2 + y ** 2) % 1) {
        result = 2;
    } else {
        result = 1;
    }
    console.log(result);
    return result;
}

let text = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', t => {
    if (t === '\r\n' || t === '\n') {
        process.stdin.emit('end');
    } else {
        text += t;
    }
});
process.stdin.on('end', () => {
    const input = text.trim().replace(/\r/g, '').split('\n');
    const total = parseInt(input[0]);
    const dataArr = input
        .slice(1, total + 1)
        .map(item => item.split(/\s/).map(n => parseInt(n)));

    for (const item of dataArr) {
        solve(...item);
    }
});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
	var t = lines[0];
    for(i = 1; i <= t; i++){
        var k = lines[i].split(' ').map(Number);
        var x = k[0];
        var y = k[1];
        var a = 2 * Math.sqrt(Math.pow(0 - x, 2) + Math.pow(0 - y, 2));
        if(x === 0 && y === 0){
            console.log(0);
        }else if(a % 1 === 0){
            console.log(1);
        }else{
            console.log(2);
        }
    }
});

let q = '';
process.stdin.on('data', c => q += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = q.split(EOL);
    var n = lines[0];
    var e = 0;
    for(j = 1; j <= n; j++){
        var k = lines[j].split(' ').map(Number);
        var x = k[0];
        var y = k[1];
        var ans = Math.sqrt(Math.pow(0 - x, 2) + Math.pow(0 - y, 2));
        if(x === 0 && y === 0){
            console.log(0);
        }else if(ans % 1 === 0){
            console.log(1);
        }else{
            console.log(2);
        }
    }
});

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

function solve(a, b) {
    if (a === 0 && b === 0) return 0
    const r = Math.floor(Math.sqrt(a * a + b * b))
    if (r * r === a * a + b * b) return 1
    return 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 [x, y] = readline().split(' ').map(Number);
        if (x === 0 && y === 0) output(0);
        else if (Number.isInteger(Math.sqrt(x*x+y*y))) output(1);
        else output(2);
    }
}

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    var e = 0;
    for(j = 1; j <= n; j++){
        var k = lines[j].split(' ').map(Number);
        var x = k[0];
        var y = k[1];
        var ans = Math.sqrt(Math.pow(0 - x, 2) + Math.pow(0 - y, 2));
        if(x === 0 && y === 0){
            console.log(0);
        }else if(ans % 1 === 0){
            console.log(1);
        }else{
            console.log(2);
        }
    }
});

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

/***
Educational Codeforces Round 125 (Div. 2)
2022-03-22

A. Integer Moves
***/

function main() {
  // INPUT: Number of test cases
  let t = readline();
  t = parseInt(t);
  let s;
  for (let i = 0; i < t; i++) {
    // INPUT: x and y coords of the point `x y`
    s = readline();
    s = s.split(' ');
    s.map(parseInt);

    // Max is 2: we can always move direct x and direct y
    // So we only need to check pythagorean triple
    const eucDist = Math.sqrt(s[0]*s[0] + s[1]*s[1]);
    if (eucDist === 0) {
      console.log(0);
    } else if (Number.isInteger(eucDist)) {
      console.log(1);
    } else {
      console.log(2);
    }
  }
}

var repeatTimes = readline();

while(repeatTimes) {
      var a = readline().split(' ').map(Number);
  var x = a[0];
  var y = a[1];
    if (x || y) {
      var z = Math.sqrt(x * x + y * y);

  var r = Math.round(z);
  if (Math.abs(z - r) < 0.000001)
        print(1 )
        else
        print(2)
    }else
        print(0)
    repeatTimes -=1

}

var t = readline();

for (var i = 0; i < t; i++) {
  var a = readline().split(' ').map(Number);
  var x = a[0];
  var y = a[1];

  if (x === 0 && y === 0) {
    print(0);
    continue;
  }

  var z = Math.sqrt(x * x + y * y);

  var r = Math.round(z);
  if (Math.abs(z - r) < 0.000001) {
    print(1);
    continue;
  }

  print(2);
}

var t = parseInt(readline());

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

function setCharAt(str,index,chr) {
    if(index > str.length-1) return str;
    return str.substr(0,index) + chr + str.substr(index+1);
}

var ch = 'a';
var acode = ch.charCodeAt(0);

for (var tt = 0; tt < t; tt++) {
    var a = readline().split(' ').map(Number);
    var x = a[0], y = a[1];
    if (x === 0 && y === 0) {
        write('0\n');
        continue;
    }

    var sqrt = Math.sqrt(x * x + y * y);
    var rounded = Math.round(sqrt);
    if (Math.abs(sqrt - rounded) < 0.000001) {
        write('1\n');
        continue;
    }

    write('2\n');
}

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

let is_sq = (x, y)=>{
  let sq = Math.sqrt((x*x)+(y*y));
  let rsq = Math.round(Math.sqrt((x*x)+(y*y)));
  return Math.abs(sq*sq-rsq*rsq)<EPS;
};

let caches = new Map();
let rec = (x, y)=>{
  if (x==0 && y==0)
    return 0;
  if (x>y)
    return rec(y, x);
  if (is_sq(x, y))
    return 1;
  let k = x+';'+y;
  if (caches.has(k))
    return caches.get(k)
  let min = Infinity;
  for (let dx = 0; dx<=x; dx++){
    for (let dy = 0; dy<=y; dy++){
      if (dx==x && dy==y || dx==0 && dy==0)
        continue;
      if (is_sq(dx, dy))
        min = Math.min(min, rec(x-dx, y-dy)+1);
    }
  }
  caches.set(k, min);
  return min;
};

function main() {
    let n = +readline()[0];
    for (let i=0; i<n; i++){
      let [x, y] = readline().split(' ').map(a=>+a);
      if (x==0 && y==0)
        print(0);
      else if(is_sq(x, y))
        print(1);
        else
        print(2);
    }
}

'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-8;

let is_sq = (x, y)=>{
  let sq = Math.sqrt((x*x)+(y*y));
  let rsq = Math.round(Math.sqrt((x*x)+(y*y)));
  return Math.abs(sq*sq-rsq*rsq)<EPS;
};

let caches = new Map();
let rec = (x, y)=>{
  if (x==0 && y==0)
    return 0;
  if (x>y)
    return rec(y, x);
  if (is_sq(x, y))
    return 1;
  let k = x+';'+y;
  if (caches.has(k))
    return caches.get(k)
  let min = Infinity;
  for (let dx = 0; dx<=x; dx++){
    for (let dy = 0; dy<=y; dy++){
      if (dx==x && dy==y || dx==0 && dy==0)
        continue;
      if (is_sq(dx, dy))
        min = Math.min(min, rec(x-dx, y-dy)+1);
    }
  }
  caches.set(k, min);
  return min;
};

function main() {
    let n = +readline()[0];
    for (let i=0; i<n; i++){
      let [x, y] = readline().split(' ').map(a=>+a);
      if (x==0 && y==0)
        print(0);
      else if(is_sq(x, y))
        print(1);
        else
        print(2);
    }
}

'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++];
}
function solve(graph, s) {
  var solutions = {};
  solutions[s] = [];
  solutions[s].dist = 0;
  while(true) {
    var nearest = null;
    var dist = Infinity;
    //for each existing solution
    for(var n in solutions) {
      if(!solutions[n])
        continue
      var ndist = solutions[n].dist;
      var adj = graph[n];
      //for each of its adjacent nodes...
      for(var a in adj) {
        //without a solution already...
        if(solutions[a])
          continue;
        //choose nearest node with lowest *total* cost
        var d = adj[a] + ndist;
        if(d < dist) {
          nearest = a;
          dist = d;
        }
      }
    }
    //no more solutions
    if(dist === Infinity) {
        break;
    }
    solutions[nearest] = {dist};
  }
  return solutions;
}

let add = (graph, a, b, w)=>{
    if (!graph[a])
        graph[a] = {};
    graph[a][b] = w;
};
const EPS = 1e-8;

let is_sq = (x, y)=>{
  let sq = Math.sqrt((x*x)+(y*y));
  let rsq = Math.round(Math.sqrt((x*x)+(y*y)));
  return Math.abs(sq*sq-rsq*rsq)<EPS;
};

let caches = new Map();
let rec = (x, y)=>{
  if (x==0 && y==0)
    return 0;
  if (x>y)
    return rec(y, x);
  if (is_sq(x, y))
    return 1;
  let k = x+';'+y;
  if (caches.has(k))
    return caches.get(k)
  let min = Infinity;
  for (let dx = 0; dx<=x; dx++){
    for (let dy = 0; dy<=y; dy++){
      if (dx==x && dy==y || dx==0 && dy==0)
        continue;
      if (is_sq(dx, dy))
        min = Math.min(min, rec(x-dx, y-dy)+1);
    }
  }
  caches.set(k, min);
  return min;
};

function main() {
    let n = +readline()[0];
    for (let i=0; i<n; i++){
      let [x, y] = readline().split(' ').map(a=>+a);
      if (x<0)
        x = -x;
      if (y<0)
        y = -y;
      print(rec(x, y))
    }
}

'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-8;

let is_sq = (x, y)=>{
  let sq = Math.sqrt((x*x)+(y*y));
  let rsq = Math.round(Math.sqrt((x*x)+(y*y)));
  return Math.abs(sq*sq-rsq*rsq)<EPS;
};

let caches = new Map();
let rec = (x, y)=>{
  if (x==0 && y==0)
    return 0;
  if (x>y)
    return rec(y, x);
  if (is_sq(x, y))
    return 1;
  let k = x+';'+y;
  if (caches.has(k))
    return caches.get(k)
  let min = Infinity;
  for (let dx = 0; dx<=x; dx++){
    for (let dy = 0; dy<=y; dy++){
      if (dx==x && dy==y || dx==0 && dy==0)
        continue;
      if (is_sq(dx, dy))
        min = Math.min(min, rec(x-dx, y-dy)+1);
    }
  }
  caches.set(k, min);
  return min;
};

function main() {
    let n = +readline()[0];
    for (let i=0; i<n; i++){
      let [x, y] = readline().split(' ').map(a=>+a);
      if (x<0)
        x = -x;
      if (y<0)
        y = -y;
      print(rec(x, y))
    }
}

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 [x,y]=line[_].split(' ').map(x=>{return parseInt(x)});
        let z=Math.sqrt(x*x+y*y);
        if(x===0&&y===0)
        {
            console.log(0);
        }
        else if(z*z===x*x+y*y)
        {
            console.log(1);
        }
        else
        {
            console.log(2);
        }
    }
})

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);
    console.log(line);
})

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

let num = -1;
const rows = [];
rl.on('line', line => {
    if (num < 0) {
        num = parseInt(line.trim());
    } else {
        rows.push(line.trim());
        if (rows.length === num) {
            dealInput(rows);
        }
    }
});
const dealInput = (rows) => {
    let location = []
    rows.forEach(item => {
        location.push(item.split(' '))
    })
    let x = 0
    let y = 0
    let s = 0
    location.forEach(item => {
        let num = Math.sqrt(((item[0]-x)*(item[0]-x))+((item[1]-y)*(item[1]-y)))
        x = item[0]
        y = item[1]
        if(parseInt(num)==num) {
            s++
        } else {
            s+=2
        }
    })
    console.log(s);
    rl.close();
};

rl.on('close', () => {
    process.exit(0);
});

function solve(x, y) {
    let result;
    if (x === 0 && y === 0) {
        result = 0;
    } else if (Math.sqrt(x ** 2 + y ** 2) % 1) {
        result = 2;
    } else {
        result = 1;
    }
    console.log(result);
    return result;
}

let text = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', t => {
    if (t === '\r\n' || t === '\n') {
        process.stdin.emit('end');
    } else {
        text += t;
    }
});
process.stdin.on('end', () => {
    const input = text.trim().replace(/\r/g, '').split('\n');
    const dataArr = input[1].split(/\s/).map(n => parseInt(n));
    solve(...dataArr);
    process.exit();
});

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

function solve(a, b) {
    if (a === 0 && b === 0) return 0
    const r = Math.sqrt(a * a + b * b)
    if (r * r === a * a + b * b) return 1
    return 2
}

var repeatTimes = readline();

while(repeatTimes--) {
      var a = readline().split(' ').map(Number);
  var x = a[0];
  var y = a[1];
    if (x || y)
        print((Math.sqrt(x * x + y * y) === Math.sqrt(x * x + y * y) ? 1 : 2))
    else
        print(0)

}


There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?

There are 2n lines in the input.  The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i > 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)

Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.

NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.

function pair(i,j,r){
    this.i=i;
    this.j=j;
    this.r=r;
}
var n=parseInt(readline());
var data=[];
for(var i=1;i<2*n;i++){
    var s0 = readline();
    var s=s0.split(" ");
    var d=new Array(s.length);
    for(var j=0;j<s.length;j++){
	d[j]=parseInt(s[j]);
    }
    for(var j=0;j<d.length;j++){
	data.push(new pair(i,j,d[j]));
    }
}
data.sort(function(a,b){return b.r-a.r;});
memo = new Array(2*n);
for(var i=0;i<2*n;i++){
    memo[i]=-1;
}
for(var i=0;i<data.length;i++){
    var s=data[i];
    if(memo[s.i] <0 && memo[s.j] < 0){
	memo[s.i]=s.j+1;
	memo[s.j]=s.i+1;
    }
}
print(memo.join(" "))

var numberofTeams = Number(readline());
var strengths = [];
var strength;
var start = 2;
while ((strength = readline())) {
    strength = strength.split(' ');
    for (var i = 0; i < strength.length; i++) {
        strengths.push({
            i: start,
            j: i + 1,
            strength: Number(strength[i])
        });
    }
    start += 1;
}

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

var teams = {};
var teamsCounter = 0;
for (var i = 0; i < strengths.length; i++) {
    if (!(strengths[i].i in teams) && !(strengths[i].j in teams)) {
        teams[strengths[i].i] = strengths[i].j;
        teams[strengths[i].j] = strengths[i].i;
        teamsCounter++;
    }
    if (teamsCounter === numberofTeams)
        break;
}

var output = "";
var noMembers= numberofTeams * 2;
for (var i = 1; i <= noMembers; i++) {
    output = output + teams[i];
    if(output !== noMembers)
        output +=" ";
}
print(output);

var numberofTeams = Number(readline());
var strengths = [];
var strength;
var start = 2;
while ((strength = readline())) {
    strength = strength.split(' ');
    for (var i = 0; i < strength.length; i++) {
        strengths.push({
            i: start,
            j: i + 1,
            strength: Number(strength[i])
        });
    }
    start += 1;
}

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

var teams = {};
var teamsCounter = 0;
for (var i = 0; i < strengths.length; i++) {
    if (!(strengths[i].i in teams) && !(strengths[i].j in teams)) {
        teams[strengths[i].i] = strengths[i].j;
        teamsCounter++;
    }
    if (teamsCounter === numberofTeams)
        break;
}
var output = "";
for (var i = 1; i <= numberofTeams * 2; i++) {
    if (i in teams)
        output += teams[i];
    else {
        for (var x in teams) {
            if (teams[x] === i) {
                output += x;
                break;
            }
        }
    }
    if (i != (numberofTeams * 2))
        output += ' ';
}
print(output);

var numberofTeams = Number(readline());
var strengths = [];
var strength;
var start = 2;
while ((strength = readline())) {
    strength = strength.split(' ');
    for (var i = 0; i < strength.length; i++) {
        strengths.push({
            i: start,
            j: i + 1,
            strength: Number(strength[i])
        });
    }
    start += 1;
}

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

var teams = {};
var teamsCounter = 0;
for (var i = 0; i < strengths.length; i++) {
    if (!(strengths[i].i in teams) && !(strengths[i].j in teams)) {
        print("i " + strengths[i].i + " j " + strengths[i].j);
        teams[strengths[i].i] = strengths[i].j;
        teams[strengths[i].j] = strengths[i].i;
        teamsCounter++;
    }
    if (teamsCounter === numberofTeams)
        break;
}

var output = "";
var noMembers = numberofTeams * 2;
for (var i = 1; i <= noMembers; i++) {
    output = output + teams[i];
    if (output !== noMembers)
        output += " ";
}
print(output);


Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \le r \le 100$$$) — the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive, — the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.

Print all tram lines that Arkady could be in, in arbitrary order.

NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$.

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});
var ost = -1;
var step = 0;
var ostn = [];
function intersect(a, b) {
    return [...new Set(a)].filter(x => new Set(b).has(x));
}

function createAnswer() {
    var marshrut = ostn.splice(0,1)[0];
    ostn.forEach(arr => {
        marshrut = intersect(marshrut,arr);

    });
    console.log(marshrut.join(" "));
}
rl.on('line', function(line){
    if (ost == -1) {
        ost = line;
    } else {
        step++;
        let temp = line.split(" ");
        temp.splice(0,1);
        ostn[ostn.length] = temp;
        if (step >= ost) {
            createAnswer();
            process.exit();
        }
    }
});

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

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var used = new Array(100001).fill(0);
  for(var i = 0; i < N; i++){
    var list = nextIntArray();
    var len = list[0];
    list.shift();
    var ng = new Set();
    for(var j = 0; j < list.length; j++){
      if(!ng.has(list[j])){
        used[list[j]]++;
        ng.add(list[j]);
      }
    }
  }
  var output = [];
  for(var i = 1; i <= 100000; i++){
    if(used[i] == N){
      output.push(i);
    }
  }
  myout(myconv(output, 8));
}

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

const getIntersection = (a, b) => {
  const set2 = new Set(b);
  return a.filter(x => set2.has(x));
}

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

  if (c === 1) {
    c++;
    [y, ...ans] = d.split(' ');

    return;
  }

  let [_, ...curr] = d.split(' ');

  ans = getIntersection(ans, curr);

  c++;
});

rl.on('close', () => {
  console.log(ans.join(' '));
});

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

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var used = new Array(100001).fill(0);
  for(var i = 0; i < N; i++){
    var list = nextIntArray();
    var ng = new Set();
    for(var j = 0; j < list.length; j++){
      if(!ng.has(list[j])){
        used[list[j]]++;
        ng.add(list[j]);
      }
    }
  }
  var output = [];
  for(var i = 1; i <= 100000; i++){
    if(used[i] == N){
      output.push(i);
    }
  }
  myout(myconv(output, 8));
}


There are $$$n$$$ people who want to participate in a boat competition. The weight of the $$$i$$$-th participant is $$$w_i$$$. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.So, if there are $$$k$$$ teams $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, $$$\dots$$$, $$$(a_k, b_k)$$$, where $$$a_i$$$ is the weight of the first participant of the $$$i$$$-th team and $$$b_i$$$ is the weight of the second participant of the $$$i$$$-th team, then the condition $$$a_1 + b_1 = a_2 + b_2 = \dots = a_k + b_k = s$$$, where $$$s$$$ is the total weight of each team, should be satisfied.Your task is to choose such $$$s$$$ that the number of teams people can create is the maximum possible. Note that each participant can be in no more than one team.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of participants. The second line of the test case contains $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le n$$$), where $$$w_i$$$ is the weight of the $$$i$$$-th participant.

For each test case, print one integer $$$k$$$: the maximum number of teams people can compose with the total weight $$$s$$$, if you choose $$$s$$$ optimally.

NoteIn the first test case of the example, we can reach the optimal answer for $$$s=6$$$. Then the first boat is used by participants $$$1$$$ and $$$5$$$ and the second boat is used by participants $$$2$$$ and $$$4$$$ (indices are the same as weights).In the second test case of the example, we can reach the optimal answer for $$$s=12$$$. Then first $$$6$$$ participants can form $$$3$$$ pairs.In the third test case of the example, we can reach the optimal answer for $$$s=3$$$. The answer is $$$4$$$ because we have $$$4$$$ participants with weight $$$1$$$ and $$$4$$$ participants with weight $$$2$$$.In the fourth test case of the example, we can reach the optimal answer for $$$s=4$$$ or $$$s=6$$$.In the fifth test case of the example, we can reach the optimal answer for $$$s=3$$$. Note that participant with weight $$$3$$$ can't use the boat because there is no suitable pair for him in the list.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    let len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    const sums = [...Array(100).fill(-1)];
    for (let i = 1; i < 101; i++) {
      sums[i] = countPair(i);
    }

    const max = Math.max(...sums);
    console.log(max);

    function countPair(sum) {
      const map = {};
      let count = 0;
      for (let i = 0; i < len; i++) {
        if (map[arr[i]] >= 1) {
          count++;
          map[arr[i]]--;
        } else {
          const sub = sum - arr[i];
          if (sub > 0) {
            if (map[sub] >= 1) map[sub]++;
            else map[sub] = 1;
          }
        }
      }
      return count;
    }
  }
}

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

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var N = nextInt();
    var list = nextIntArray();
    var maxSize = 0;
    var set = new Set();
    for(var j = 0; j < N - 1; j++){
      for(var k = j + 1; k < N; k++){
        var sum = list[j] + list[k];
        set.add(sum);
      }
    }
    var tmpList = Array.from(set);
    for(var j = 0; j < tmpList.length; j++){
      var tmp = makeClone(list);
      var count = 0;
      for(var l = 0; l < N - 1; l++){
        for(var m = l + 1; m < N; m++){
          if(tmp[l] + tmp[m] == tmpList[j]){
            count++;
            tmp[l] = -100000;
            tmp[m] = -100000;
          }
        }
      }
      maxSize = Math.max(maxSize, count);
    }

    output[i] = maxSize;
  }
  myout(myconv(output, 9));
}

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

    main()
})

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

const s2i = s => parseInt(s, 10)

const readLineOfBigInts = () => {
  const split = readLine().split(' ')
  const result = []
  for (let i = 0, l = split.length; i < l; i++) {
    result.push(BigInt(split[i]));
  }
  return result
}

const cmpi = (a, b) => a - b

function main() {
  let T = s2i(readLine())
  let out = ''

  while (T--) {
    const n = s2i(readLine())
    const w = readLine().split(' ').map(s2i)
    w.sort(cmpi)

    const ss = new Array(2*n + 1)
    for (let i = 0; i < n; i++) {
      for (let j = i+1; j < n; j++) {
        ss[w[i] + w[j]] = true
      }
    }

    let maxPairs = 0

    for (let s = 0; s <= 2*n; s++) {
      if (!ss[s]) continue
      let pairs = 0
      for (let izq = 0, der = n-1; izq < der;) {
        if (w[izq] + w[der] > s) der--
        else if (w[izq] + w[der] < s) izq++
        else {
          der--
          izq++
          pairs++
        }
      }

      if (maxPairs < pairs) maxPairs = pairs
    }

    out += maxPairs + '\n'
  }

  console.log(out)
}

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

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

function main() {
	let t = readLine() >> 0;
	while (t--) {
		let n = readLine() >> 0;
		let weights = readLine()
			.split(' ')
			.map(x => x >> 0);

		if (n === 1) {
			console.log(0);
			continue;
		}

		let grid = [],
			hash = {},
			s = 0,
			v = 0;
		for (let i = 0; i < n; i++) {
			grid[i] = Array(n).fill('x');
			for (let j = i + 1; j < n; j++) {
				let w = weights[i] + weights[j];
				grid[i][j] = w;

				if (hash[w] === undefined) {
					hash[w] = {};
					hash[w].cord = [];
					hash[w].value = 0;
				}

				if (
					hash[w].cord.indexOf(i) === -1 &&
					hash[w].cord.indexOf(j) === -1
				) {
					hash[w].cord = [...hash[w].cord, i, j];
					hash[w].value += 1;

					if (hash[w].value > v) {
						v = hash[w].value;
						s = w;
					}
				}
			}
		}

		console.log(hash[s].cord.length / 2);
	}
}

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 k = 0; k < t; k++){
        let n = parseInt(readline());
        let arr = readline().split(' ');
        let map = {};
        let max = 0;
        for(let i = 0; i < arr.length; i++){
            for(let j = i+1; j < arr.length; j++){
                map[parseInt(arr[i]) + parseInt(arr[j])] = 1;
            }
        }

        for(let i = 0; i < arr.length; i++)
            arr[i] = parseInt(arr[i]);

        arr.sort((a,b) => a-b);
        for(let sum in map){
            sum = parseInt(sum);

            let p1 = 0;
            let p2 = arr.length-1;
            let count = 0;
            while(p1 < p2){
                if(arr[p1] + arr[p2] < sum){
                    p1++;
                }else if(arr[p1] + arr[p2] > sum){
                    p2--;
                }else{
                    count += 1;
                    p1++;
                    p2--;
                }
            }

            max = Math.max(max, count);
        }

        console.log(max);
    }
}

'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++];
}
/**
5
3
1 2 2
4
5 5 5 5
3
1 2 4
4
1 3 4 4
1
100
**/

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

    return gcd(b, a % b);
};

function lcm(a, b) {
    return (a / gcd(a, b) * b);
}

function main() {
    let n = Number(readline());

    for(let r=0;r<n;r++) {
        solve(r);
    }

}

function solve(index) {
    let n = Number(readline());
    let a = readline().split(" ").map(Number);
    const hash = {};

    if(a.length === 1) {
        console.log(0);
        return;
    }

    if(a.length === 2) {
        console.log(1);
        return;
    }

    for(let i=0;i<n;i++) {
        for(let j=0;j<n;j++) {
            if(i !== j) {
                let num = a[i] + a[j];
                if(hash[num]) {
                    let array = hash[num];
                    let notFound = false;

                    array.forEach((x) => {
                        if(x[0] === i || x[1] === i || x[0] === j || x[1] === j) {
                            notFound = true;
                        }
                    });

                    if(!notFound) {
                        hash[num].push([i, j]);
                    }
                } else {
                    hash[num] = [[i, j]];
                }
            }
        }
    }

    let sortedKey = Object.keys(hash).sort((a, b) => {
        return hash[b].length - hash[a].length;
    });

    console.log(hash[sortedKey[0]].length);

}

function solve() {
    var n = readInt()
    var arr = sortIntArr(readIntArray())

    if (arr.length <= 1) {
        print(0)
        return
    }

    var maxSum = arr[n-1] + arr[n-2]
    var maxAnswer = Math.floor(n/2)
    var answer = 0

    var diffArr = new Array(n)
    for(var i=maxSum; i >=0; i--) {
        for(var j=0; j<n; j++) {
            diffArr[j] = i - arr[j]
        }

        var numPairs = 0
        var x = 0
        var y = n - 1
        while (x < y) {
            if (arr[x] == diffArr[y]) {
                numPairs += 1
                y -= 1
                x += 1
            } else if (diffArr[y] < arr[x]) {
                y -= 1
            } else {
                x += 1
            }
        }
        if (numPairs == maxAnswer) {
            print(maxAnswer)
            return
        }
        answer = Math.max(numPairs, answer)
    }

    print(answer)
}

var testCases = readInt();
var testCaseNum;
for(testCaseNum=0; testCaseNum<testCases; testCaseNum++) {
  solve()
}

function readIntArray() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function readInt() {
    return parseInt(readline())
}

function sortIntArr(arr) {
  return arr.sort((a, b) => a - b)
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    let len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    const store = {};
    for (let i = 0; i < len; i++) {
      for (let j = i + 1; j < len; j++) {
        const sum = arr[i] + arr[j];
        if (!store[sum]) store[sum] = 1;
        else store[sum]++;
      }
    }

    const max = Math.max(...Object.values(store));
    let avg;

    for (let key of Object.keys(store)) {
      if (store[key] === max) avg = key;
    }

    const map = {};
    let count = 0;
    for (let i = 0; i < len; i++) {
      if (map[arr[i]]) {
        count++;
        delete map[arr[i]];
      } else {
        const sub = avg - arr[i];
        if (sub > 0) map[sub] = true;
      }
    }
    console.log(count);
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    let len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    const sums = [...Array(100).fill(-1)];
    for (let i = 1; i < 101; i++) {
      sums[i] = countPair(i);
    }

    const max = Math.max(...sums);
    console.log(max);

    function countPair(avg) {
      const map = {};
      let count = 0;
      for (let i = 0; i < len; i++) {
        if (map[arr[i]]) {
          count++;
          delete map[arr[i]];
        } else {
          const sub = avg - arr[i];
          if (sub > 0) map[sub] = true;
        }
      }
      return count;
    }
  }
}

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

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

function main() {
	let t = readLine() >> 0;
	while (t--) {
		let n = readLine() >> 0;
		let weights = readLine()
			.split(' ')
			.map(x => x >> 0);

		let grid = [];
		for (let i = 0; i < n; i++) {
			grid[i] = Array(n).fill('x');
			for (let j = i + 1; j < n; j++) {
				grid[i][j] = weights[i] + weights[j];
			}
		}

		let flat = grid.flat().filter(x => x !== 'x');
		let hash = {};
		flat.forEach(x => (hash[x] = (hash[x] || 0) + 1));
		let s = 0,
			m = 0;
		Object.entries(hash).forEach(([k, v]) => {
			if (v >= m) {
				s = k;
				m = v;
			}
		});

		let team = 0;
		let taken = [];
		for (let i = 0; i < n; i++) {
			for (let j = i + 1; j < n; j++) {
				if (
					grid[i][j] === +s &&
					taken.indexOf(i) === -1 &&
					taken.indexOf(j) === -1
				) {
					taken.push(i, j);
					team++;
					break;
				}
			}
		}

		console.log(team);
	}
}

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

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

function main() {
	let t = readLine() >> 0;
	while (t--) {
		let n = readLine() >> 0;
		let weights = readLine()
			.split(' ')
			.map(x => x >> 0);

		let grid = [];
		for (let i = 0; i < n; i++) {
			grid[i] = Array(n).fill('x');
			for (let j = i + 1; j < n; j++) {
				grid[i][j] = weights[i] + weights[j];
			}
		}

		let arr = grid.flat().filter(x => x !== 'x');
		let s = 0,
			v = 0,
			h = {};
		arr.forEach(x => {
			h[x] = (h[x] || 0) + 1;
			if (h[x] > v) {
				v = h[x];
				s = x;
			}
		});

		let l = 0,
			c = 0,
			r = n - 1;
		while (l < r) {
			let tw = weights[l] + weights[r];
			if (tw > s) {
				r--;
			} else if (tw < s) {
				l++;
			} else {
				r--;
				l++;
				c++;
			}
		}

		console.log(c);
	}
}

'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++];
}
/**
5
3
1 2 2
4
5 5 5 5
3
1 2 4
4
1 3 4 4
1
100
**/

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

    return gcd(b, a % b);
};

function lcm(a, b) {
    return (a / gcd(a, b) * b);
}

function main() {
    let n = Number(readline());

    for(let r=0;r<n;r++) {
        solve(r);
    }

}

function solve(index) {
    let n = Number(readline());
    let a = readline().split(" ").map(Number);
    const hash = {};

    if(a.length < 2) {
        console.log(1);
        return;
    }

    for(let i=0;i<n;i++) {
        for(let j=0;j<n;j++) {
            if(i !== j) {
                let num = a[i] + a[j];
                if(hash[num]) {
                    let array = hash[num];
                    let notFound = false;

                    array.forEach((x) => {
                        if(x[0] === i || x[1] === i || x[0] === j || x[1] === j) {
                            notFound = true;
                        }
                    });

                    if(!notFound) {
                        hash[num].push([i, j]);
                    }
                } else {
                    hash[num] = [[i, j]];
                }
            }
        }
    }

    let sortedKey = Object.keys(hash).sort((a, b) => {
        return hash[b].length - hash[a].length;
    });

    console.log(hash[sortedKey[0]].length);

}

function solve() {
    var n = readInt()
    var arr = readIntArray()

    if (arr.length <= 1) {
        print(0)
        return
    }

    var maxSum = arr[n-1] + arr[n-2]
    var maxAnswer = Math.floor(n/2)
    var answer = 0

    var diffArr = new Array(n)
    for(var i=maxSum; i >=0; i--) {
        for(var j=0; j<n; j++) {
            diffArr[j] = i - arr[j]
        }

        var numPairs = 0
        var x = 0
        var y = n - 1
        while (x < y) {
            if (arr[x] == diffArr[y]) {
                numPairs += 1
                y -= 1
                x += 1
            } else if (diffArr[y] < arr[x]) {
                y -= 1
            } else {
                x += 1
            }
        }
        if (numPairs == maxAnswer) {
            print(maxAnswer)
            return
        }
        answer = Math.max(numPairs, answer)
    }

    print(answer)
}

var testCases = readInt();
var testCaseNum;
for(testCaseNum=0; testCaseNum<testCases; testCaseNum++) {
  solve()
}

function readIntArray() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function readInt() {
    return parseInt(readline())
}

function sortIntArr(arr) {
  return arr.sort((a, b) => a - b)
}


Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that:  each student in the team scored at least l points and at most r points;  in total, all members of the team scored exactly sall points;  the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.

The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.

Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.

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

function readNums() {
  return readline().split(' ').map(Number);
}

print(function(n, k, l, r, sa, sk) {
  var i = 0,
    ans = [],
    a = Math.floor(sk / k),
    b = sk % k,
    c = Math.floor((sa - sk) / (n - k)),
    d = k + (sa - sk) % (n - k);

  while (i < b)
    i++, ans.push(a + 1);
  while (i < k)
    i++, ans.push(a);
  while (i < d)
    i++, ans.push(c + 1);
  while (i < n)
    i++, ans.push(c);
  return ans.join(' ');

}.apply(0, readNums()));

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

function readNums() {
  return readline().split(' ').map(Number);
}

print(function(n, k, l, r, sa, sk) {
  var ans = [];
  var a = ~~ (sk / k);
  var b = sk % k;
  for (var i = 0; i < b; i++)
    ans.push(a + 1);
  for (; i < k; i++)
    ans.push(a);

  a = ~~ ((sa - sk) / (n - k));
  b = k + (sa - sk) % (n - k);
  for (; i < b; i++)
    ans.push(a + 1);
  for (; i < n; i++)
    ans.push(a);
  return ans.join(' ');

}.apply(0, readNums()));

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 splitScores(total, count) {
	var low = Math.floor(total/count), high = low+1;
	var highCount = total - count*low;
	var arr = [];
	for (var i = 0; i < count; i += 1) {
		arr.push(i < highCount ? high : low);
	}
	return arr;
}

function main() {
	var integers = tokenizeIntegers(readline());
	var numScores = integers[0], numTopScores = integers[1],
		minScore = integers[2], maxScore = integers[3],
		allTotal = integers[4], topTotal = integers[5];

	var topScores = splitScores(topTotal, numTopScores);
	var restScores = splitScores(allTotal - topTotal, numScores - numTopScores);

	print(topScores.join(' '), restScores.join(' '));
}

main();

(function main() {
    var v = readline().split(' ');
    var n = parseInt(v[0]);
    var k = parseInt(v[1]);
    var l = parseInt(v[2]);
    var r = parseInt(v[3]);
    var sall = parseInt(v[4]);
    var sk = parseInt(v[5]);
    var a = new Array(n);
    var d = ~~(sk / k);
    var o = sk % k;
    var i = 0;
    for ( ; i < o; ++i) a[i] = d + 1;
    for ( ; i < k; ++i) a[i] = d;
    sall -= sk + (n - k) * l;
    for ( ; i < k + ~~(sall / (d - l)); ++i) a[i] = d;
    if(sall % (d - l))
        a[i++] = sall % (d - l) + l;
    for ( ; i < n; ++i) a[i] = l;
    print(a.join(' '));
})();

(function main() {
    var v = readline().split(' ');
    var n = parseInt(v[0]);
    var k = parseInt(v[1]);
    var l = parseInt(v[2]);
    var r = parseInt(v[3]);
    var sall = parseInt(v[4]);
    var sk = parseInt(v[5]);
    var a = new Array(n);
    var d = sk / k;
    var o = sk % k;
    var i = 0;
    for ( ; i < o; ++i) a[i] = d + 1;
    for ( ; i < k; ++i) a[i] = d;
    sall -= sk + (n - k) * l;
    for ( ; i < k + sall / (d - l); ++i) a[i] = d;
    if(sall % (d - l))
        a[i++] = sall % (d - l) + l;
    for ( ; i < n; ++i) a[i] = l;
    print(a.join(' '));
})();


Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell $$$(0, 0)$$$ on an infinite grid.You also have the sequence of instructions of this robot. It is written as the string $$$s$$$ consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell $$$(x, y)$$$ right now, he can move to one of the adjacent cells (depending on the current instruction).  If the current instruction is 'L', then the robot can move to the left to $$$(x - 1, y)$$$;  if the current instruction is 'R', then the robot can move to the right to $$$(x + 1, y)$$$;  if the current instruction is 'U', then the robot can move to the top to $$$(x, y + 1)$$$;  if the current instruction is 'D', then the robot can move to the bottom to $$$(x, y - 1)$$$. You've noticed the warning on the last page of the manual: if the robot visits some cell (except $$$(0, 0)$$$) twice then it breaks.So the sequence of instructions is valid if the robot starts in the cell $$$(0, 0)$$$, performs the given instructions, visits no cell other than $$$(0, 0)$$$ two or more times and ends the path in the cell $$$(0, 0)$$$. Also cell $$$(0, 0)$$$ should be visited at most two times: at the beginning and at the end (if the path is empty then it is visited only once). For example, the following sequences of instructions are considered valid: "UD", "RL", "UUURULLDDDDLDDRRUU", and the following are considered invalid: "U" (the endpoint is not $$$(0, 0)$$$) and "UUDD" (the cell $$$(0, 1)$$$ is visited twice).The initial sequence of instructions, however, might be not valid. You don't want your robot to break so you decided to reprogram it in the following way: you will remove some (possibly, all or none) instructions from the initial sequence of instructions, then rearrange the remaining instructions as you wish and turn on your robot to move. Your task is to remove as few instructions from the initial sequence as possible and rearrange the remaining ones so that the sequence is valid. Report the valid sequence of the maximum length you can obtain.Note that you can choose any order of remaining instructions (you don't need to minimize the number of swaps or any other similar metric).You have to answer $$$q$$$ independent test cases.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^4$$$) — the number of test cases. The next $$$q$$$ lines contain test cases. The $$$i$$$-th test case is given as the string $$$s$$$ consisting of at least $$$1$$$ and no more than $$$10^5$$$ characters 'L', 'R', 'U' and 'D' — the initial sequence of instructions. It is guaranteed that the sum of $$$|s|$$$ (where $$$|s|$$$ is the length of $$$s$$$) does not exceed $$$10^5$$$ over all test cases ($$$\sum |s| \le 10^5$$$).

For each test case print the answer on it. In the first line print the maximum number of remaining instructions. In the second line print the valid sequence of remaining instructions $$$t$$$ the robot has to perform. The moves are performed from left to right in the order of the printed sequence. If there are several answers, you can print any. If the answer is $$$0$$$, you are allowed to print an empty line (but you can don't print it).

6
LRU
DURLDRUDRULRDURDDL
LRUDDLRUDRUL
LLLLRRRR
URDUR
LLL

2
LR
14
RUURDDDDLLLUUR
12
ULDDDRRRUULL
2
LR
2
UD
0

NoteThere are only two possible answers in the first test case: "LR" and "RL".The picture corresponding to the second test case:  Note that the direction of traverse does not matter Another correct answer to the third test case: "URDDLLLUURDR".

'use strict'

const problem = (s) => {
    const r = { L: 0, R: 0, D: 0, U: 0 };
    for (let i = 0; i < s.length; i++) r[s[i]]++;
    const w = Math.min(r.L, r.R);
    const h = Math.min(r.U, r.D);
    if (!w && !h) return [ 0, '' ];
    if (!h) return [ 2, 'LR' ];
    if (!w) return [ 2, 'UD' ];

    return [ 2*(w+h), 'L'.repeat(w) + 'U'.repeat(h) + 'R'.repeat(w) + 'D'.repeat(h) ];
}
let q = +readline();

while(q--) print(problem(readline()).join('\n'));

function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim();}
function myout(t){print(t);}//standard output
//function myout(t){console.log(t);}//standard output
function myerr(t){console.err(t);}//standard error
//[no]param
//0:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
function myconv(i,no){switch(no){case 0:return i;case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));}}

function Main(input) {
  //input = myconv(input,3);
  var N = myconv(readline(),1);
  //input.shift();
  var output = [];
  for(var i = 0; i < N; i++){
    var s = myconv(readline(),6);
    var L = 0;
    var R = 0;
    var U = 0;
    var D = 0;
    for(var j = 0; j < s.length; j++){
      switch(s[j]){
        case "L":
          L++;
          break;
          case "R":
          R++;
          break;
          case "U":
          U++;
          break;
          case "D":
          D++;
          break;
      }
    }
    if(L > 0 && R > 0 && U > 0 && D > 0){
       var LRmin = Math.min(L,R);
      var UDmin = Math.min(U,D);
      output.push(LRmin * 2 + UDmin * 2);
      var add = "";
      for(var j = 0; j < UDmin; j++){add += "D";}
      for(var j = 0; j < LRmin; j++){add += "L";}
      for(var j = 0; j < UDmin; j++){add += "U";}
      for(var j = 0; j < LRmin; j++){add += "R";}
      output.push(add);
    }else if(L > 0 && R > 0){
      output.push(2);
      output.push("LR");
    }else if(U > 0 && D > 0){
		output.push(2);
      output.push("UD");
    }else{
       output.push(0);
    }
  }
  myout(output.join("\n"));
}

Main();

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))

  const t = parseInt(arr.shift())

  for(let j = 0; j < t; j++) {
    const str = arr[j]
    const len = str.length

    let l, r, u, d
    l = r = u = d = 0

    for(let i = 0; i < len; i++) {
      let a = str[i]
      if(a == 'L') l ++
      else if(a == 'R') r++
      else if(a == 'U') u++
      else d++

    }
    // console.log(2 * l + 2 * u)

    if(l != r) l = r = Math.min(l, r)
    if(u != d) u = d = Math.min(u, d)
    if(l == 0 && u >= 1) {
      console.log(2)
      console.log('UD')
      continue
    }
    else if(u == 0 && l >= 1) {
      console.log(2)
      console.log('LR')
      continue
    }
    else if(u == 0 && l == 0){
      console.log(0)
      continue
    }

    // console.log(2 * l + 2 * u)

    let s = new Array(2 * l + 2 * u)

    for(let i = 0; i < l; i++) {
      s[i] = 'L'
    }

    for(let i = 0; i < u; i++) {
      s[i + l] = 'U'
    }

    for(let i = 0; i < r; i++) {
      s[i + l + u] = 'R'
    }

    for(let i = 0; i < d; i++) {
      s[i + l + r + u] = 'D'
    }
    console.log(2 * l + 2 * u)
    console.log(s.join(''))
  }
})

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) {
        const counts = data.reduce((acc, value) => {
            acc[value] = ++acc[value];
            return acc;
        }, { L: 0, R: 0, U: 0, D: 0 })

        const lrP = Math.min(counts.L, counts.R);
        const udP = Math.min(counts.U, counts.D);
        if (!lrP && !udP) return [0, ''];
        if (!lrP) return [2, 'UD'];
        if (!udP) return [2, 'LR'];

        return [(lrP + udP) * 2, (new Array(lrP).fill('L').join('')) + (new Array(udP).fill('U').join('')) + (new Array(lrP).fill('R').join('')) + (new Array(udP).fill('D').join('')) ]
    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let data = lines[testCount].split("");

        let result = foo(data);
        answer += result[0] +"\n";
        answer += result[1] +"\n";
        testCount++;
    }
    console.log(answer);
})

let finalInput = '';

process.stdin.setEncoding('utf-8').on('data', input => {
    finalInput += input;
});

process.stdin.setEncoding('utf-8').on('end', () => {
    const dist = (a, b, c) => Math.abs(a - b) + Math.abs(a - c) + Math.abs(b - c);
    finalInput.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0)
        .forEach(line => {
            const commands = line.split('');
            let L = commands.filter(c => c === 'L').length;
            let R = commands.filter(c => c === 'R').length;
            let U = commands.filter(c => c === 'U').length;
            let D = commands.filter(c => c === 'D').length;

            L = R = Math.min(L, R);
            U = D = Math.min(U, D);

            if (L === 0 && U > 1) {
                U = D = 1;
            }
            if (U === 0 &&  L > 1) {
                L = R = 1;
            }

            let output = new Array(L).fill('L')
                .concat(new Array(U).fill('U'))
                .concat(new Array(R).fill('R'))
                .concat(new Array(D).fill('D'));

            console.log(output.length);
            if (output.length > 0) {
                console.log(output.join(''));
            }
        });
});

let fs = require("fs");

let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0;
});

txt.shift();

for (let i = 0; i < txt.length; i++) {
    doit(txt[i].split("").filter(data => {
        return data.length > 0;
    }));

}

function doit(tab) {
    let moves = {
        L: 0,
        U: 0,
        R: 0,
        D: 0
    };
    tab.forEach(data => {
        ++moves[data];
    });
    let hor = Math.min(moves.L, moves.R);
    let ver = Math.min(moves.U, moves.D);
    if (hor + ver === 0) {
        console.log(0);
        console.log();
    } else if (hor === 0) {
        console.log(2);
        console.log("UD");
    } else if (ver === 0) {
        console.log(2);
        console.log("LR");
    } else {
        moves.U = moves.D = ver;
        moves.L = moves.R = hor;
        let seq = "";
        for (const key in moves) {
            for (let i = 0; i < moves[key]; i++) {
                seq += key;
            }
        }
        console.log(seq.length);
        console.log(seq);
    }
}

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))

  const t = parseInt(arr.shift())

  for(let j = 0; j < t; j++) {
    const str = arr[j]
    const len = str.length

    let l, r, u, d
    l = r = u = d = 0

    for(let i = 0; i < len; i++) {
      let a = str[i]
      if(a == 'L') l ++
      else if(a == 'R') r++
      else if(a == 'U') u++
      else d++

    }
    // console.log(2 * l + 2 * u)

    if(l != r) l = r = Math.min(l, r)
    if(u != d) u = d = Math.min(u, d)
    if(l == 0 && u >= 1) {
      console.log(2)
      console.log('UD')
      continue
    }
    else if(u == 0 && l >= 1) {
      console.log(2)
      console.log('LR')
      continue
    }
    else if(u == 0 && l == 0){
      console.log(0)
      continue
    }

    // console.log(2 * l + 2 * u)

    let s = new Array(2 * l + 2 * u)

    for(let i = 0; i < l; i++) {
      s[i] = 'L'
    }

    for(let i = 0; i < u; i++) {
      s[i + l] = 'U'
    }

    for(let i = 0; i < r; i++) {
      s[i + l + u] = 'R'
    }

    for(let i = 0; i < d; i++) {
      s[i + l + u + d] = 'D'
    }
    console.log(2 * l + 2 * u)
    console.log(s.join(''))
  }
})

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) {
        const counts = data.reduce((acc, value) => {
            acc[value] = ++acc[value];
            return acc;
        }, { L: 0, R: 0, U: 0, D: 0 })

        const lrP = Math.min(counts.L, counts.R);
        const udP = Math.min(counts.U, counts.D);
        if (!lrP && !udP) return [0, ''];
        if (!lrP) return [2, 'UD'];
        if (!udP) return [2, 'LR'];

        return [(lrP + udP) * 2, (new Array(lrP).fill('L').join('')) + (new Array(udP).fill('U').join('')) + (new Array(udP).fill('D').join('')) + (new Array(lrP).fill('R').join('')) ]
    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let data = lines[testCount].split("");

        let result = foo(data);
        answer += result[0] +"\n";
        answer += result[1] +"\n";
        testCount++;
    }
    console.log(answer);
})

process.stdin.setEncoding('utf-8').on('data', input => {
    const dist = (a, b, c) => Math.abs(a - b) + Math.abs(a - c) + Math.abs(b - c);
    input.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0)
        .forEach(line => {
            const commands = line.split('');
            let L = commands.filter(c => c === 'L').length;
            let R = commands.filter(c => c === 'R').length;
            let U = commands.filter(c => c === 'U').length;
            let D = commands.filter(c => c === 'D').length;

            let max = commands.length - Math.abs(L - R) - Math.abs(U - D);

            L = R = Math.min(L, R);
            U = D = Math.min(U, D);

            let output = new Array(L).fill('L')
                .concat(new Array(U).fill('U'))
                .concat(new Array(R).fill('R'))
                .concat(new Array(D).fill('D'));

            console.log(max);
            console.log(output.join(''));
        });
});

process.stdin.setEncoding('utf-8').on('data', input => {
    const dist = (a, b, c) => Math.abs(a - b) + Math.abs(a - c) + Math.abs(b - c);
    input.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0)
        .forEach(line => {
            const commands = line.split('');
            let L = commands.filter(c => c === 'L').length;
            let R = commands.filter(c => c === 'R').length;
            let U = commands.filter(c => c === 'U').length;
            let D = commands.filter(c => c === 'D').length;

            L = R = Math.min(L, R);
            U = D = Math.min(U, D);

            if (L === 0 && U > 1) {
                U = D = 1;
            }
            if (U === 0 &&  L > 1) {
                L = R = 1;
            }

            let output = new Array(L).fill('L')
                .concat(new Array(U).fill('U'))
                .concat(new Array(R).fill('R'))
                .concat(new Array(D).fill('D'));

            console.log(output.length);
            if (output.length > 0) {
                console.log(output.join(''));
            }
        });
});

process.stdin.setEncoding('utf-8').on('data', input => {
    const dist = (a, b, c) => Math.abs(a - b) + Math.abs(a - c) + Math.abs(b - c);
    input.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0)
        .forEach(line => {
            const commands = line.split('');
            let L = commands.filter(c => c === 'L').length;
            let R = commands.filter(c => c === 'R').length;
            let U = commands.filter(c => c === 'U').length;
            let D = commands.filter(c => c === 'D').length;

            L = R = Math.min(L, R);
            U = D = Math.min(U, D);

            if (L === 0 && U > 1) {
                U = D = 1;
            }
            if (U === 0 &&  L > 1) {
                L = R = 1;
            }

            let output = new Array(L).fill('L')
                .concat(new Array(U).fill('U'))
                .concat(new Array(R).fill('R'))
                .concat(new Array(D).fill('D'));

            console.log(output.length);
            console.log(output.join(''));
        });
});


One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:  Find the number that goes k-th in the current sequence and add the same number to the end of the sequence;  Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.

Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.

NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.

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

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  const [len, k] = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  const arr = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  let [ok, count] = [true, 0];
  const target = arr[k - 1];

  for (let i = k; i < len; i++) {
    if (arr[i] !== target) {
      ok = false;
      break;
    }
  }

  let same = true;
  for (let i = k - 2; i >= 0; i--) {
    if (arr[i] === target && same) continue;
    else {
      same = false;
      count++;
    }
  }

  if (!ok) console.log(-1);
  else {
    console.log(count);
  }
}

print(function(n, k) {

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

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

	return 0;

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

print(function(n, k) {

	var a = readline().split(' ').map(Number);
	var x = 0;
	for (var i = n - 2; i >= 0; i--)
		if (a[i] !== a[i + 1]) {
			x = i + 1;
			break;
		}

	return x >= k ? -1 : x;

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

;(function () {

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

	var a = readline().split(' ').map(Number), y = a[k - 1];

	print((function () {
		if (a.slice(k - 1).filter(function (e, i, _a) { return e !== y; }).length) return -1;
		for (var i = k - 2; i >= 0; i--) if (a[i] !== y) return i + 1;
		return 0;
	})());

}).call(this)

print(function(n, k) {

	var a = readline().split(' ').map(Number);
	var x = 0;
	for (var i = n - 2; i >= 0; i--)
		if (a[i] !== a[i + 1]) {
			x = i + 1;
			break;
		}

	return x > k ? -1 : x;

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


Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster.There are $$$n$$$ books in the family library. The $$$i$$$-th book is described by three integers: $$$t_i$$$ — the amount of time Alice and Bob need to spend to read it, $$$a_i$$$ (equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ if not), and $$$b_i$$$ (equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ if not).So they need to choose some books from the given $$$n$$$ books in such a way that:  Alice likes at least $$$k$$$ books from the chosen set and Bob likes at least $$$k$$$ books from the chosen set;  the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of $$$t_i$$$ over all books that are in the chosen set.Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$). The next $$$n$$$ lines contain descriptions of books, one description per line: the $$$i$$$-th line contains three integers $$$t_i$$$, $$$a_i$$$ and $$$b_i$$$ ($$$1 \le t_i \le 10^4$$$, $$$0 \le a_i, b_i \le 1$$$), where:   $$$t_i$$$ — the amount of time required for reading the $$$i$$$-th book;  $$$a_i$$$ equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ otherwise;  $$$b_i$$$ equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ otherwise.

If there is no solution, print only one integer -1. Otherwise print one integer $$$T$$$ — the minimum total reading time of the suitable set of books.

function sortFunc(x, y) {
   return x - y;
}

function solve() {
   var nk = read().split(' ').map(Number);
   var n = nk[0];
   var k = nk[1];
   var tboth = [];
   var ta = [];
   var tb = [];
   var ca = 0;
   var cb = 0;

   for (var i = 0; i < n; i++) {
      var tab = read().split(' ').map(Number);
      var cCase = tab[2] * 2 + tab[1];
      if (cCase === 1) {
         ca++;
         ta.push(tab[0]);
      }
      if (cCase === 2) {
         cb++;
         tb.push(tab[0]);
      }
      if (cCase === 3) {
         ca++;
         cb++;
         tboth.push(tab[0]);
      }
   }
   ta.sort(sortFunc);
   tb.sort(sortFunc);
   tboth.sort(sortFunc);
   if (ca < k || cb < k) {
      write(-1);
      return;
   }
   var ans = 0;
   var ia = 0;
   var na = ta.length;
   var ib = 0;
   var nb = tb.length;
   var iboth = 0;
   var nboth = tboth.length;
   for (var i = 0; i < k; i++) {
      if (ia >= na || ib >= nb) {
         ans += tboth[iboth++];
         continue;
      }
      if (iboth >= nboth) {
         ans += ta[ia++] + tb[ib++];
         continue;
      }
      if (ta[ia] + tb[ib] < tboth[iboth]) {
         ans += ta[ia++] + tb[ib++];
      } else {
         ans += tboth[iboth++];
      }
   }
   write(ans);
}

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

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;
   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();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', init);
   }
} else {
   init();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

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() {
    var aliceOnly = [], bobOnly = [], both = []
    var n, k;
    [n, k] = readline().split(" ").map(x => parseInt(x));
    for (var i=0; i<n; i++) {
        var a, b, c;
        [a, b, c] = readline().split(" ").map(x => parseInt(x));
        if (b === 1 && c === 1) {
            both.push(a);
        }
        else if (c === 1) {
            bobOnly.push(a);
        }
        else if (b === 1) {
            aliceOnly.push(a);
        }
    }
    aliceOnly.sort(function(a, b){return a-b});
    bobOnly.sort(function(a, b){return a-b});
    both.sort(function(a, b){return a-b});

    const cum = (a => b => a+=b);
    const aCum = aliceOnly.map(cum(0)), bCum = bobOnly.map(cum(0)), cCum = both.map(cum(0));
    var time = 1000000000000000;
    for (var i=0; i<=k; i++) {
        // i: number of books both read
        var sum = 0;
        if (i <= cCum.length && k-i <= aCum.length && k-i <= bCum.length) {
            if (i >= 1) { sum += cCum[i-1]; }
            if (k-i >= 1) { sum += aCum[k-i-1] + bCum[k-i-1]; }
            time = Math.min(time, sum);
        }
    }
    if (time === 1000000000000000) { console.log(-1); }
    else { console.log(time); }
}

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

    E1();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function C(){
    let [n,m] = ti(readline().split(' '));
    let a = ti(readline().split(' '));
    let b = ti(readline().split(' '));
    let o = new Array(10);
    let z = new Array(10);
    o.fill(0);
    z.fill(0);
    for(let i = 0; i < m; i++){
        let t = 1;
        for(let j = 0; j < 10; j++){
            if(b[i] & t !== 0)
                o[j] = 1;
            else
                z[j] = 1;

            t << 1;
        }
    }

    let c = new Array(10);
    for(let i = 0; i < n; i++){
        let t = 1;
        for(let j = 0; j < 10; j++){
            if(a[i] & t !== 0){
                if(z[j] === 1)
                    c[j] = 0;
                else
                    c[j] = 1;
            }
            t << 1;
        }
    }

    let res = 0;
    for(let i = 9; i >= 0; i--){
        res += pi(c[i])*Math.pow(2,9-i);
    }
    console.log(res);
}

function B(){
    let t = pi(readline());
    while(t){
        t--;
        let [n,k,z] = ti(readline().split(' '));
        let a = ti(readline().split(' '));

        // pre -> 0,1 -> right,left
        let dp = new Array(z+1);
        for(let i = 0; i < z+1; i++){
            dp[i] = new Array(n);
            dp[i].fill(-1);
        }

        let solve = (i,j,index,pre) => {
            if(index < 0 || index >= n)
                return 0;
            if(i > k)
                return 0;
            if(dp[j][index] !== -1)
                return dp[j][index];
            if(pre){
                return dp[j][index] = a[index] + solve(i+1, j, index+1, 0);
            }else{
                return dp[j][index] = a[index] + Math.max(j < z ? solve(i+1,j+1,index-1,1) : 0, solve(i+1,j,index+1,0));
            }
        }

        console.log(solve(0,0,0,1));
    }
}

function E1(){
    let [n,k] = ti(readline().split(' '));
    let t = new Array(n);
    for(let i = 0; i < n; i++){
        t[i] = ti(readline().split(' '));
    }
    let ab = [];
    let a = [];
    let b = [];
    let unlikeCount = 0;

    for(let i = 0; i < n; i++){
        if(t[i][1] === 1 && t[i][2] === 1){
            ab.push(t[i]);
        }else if(t[i][1] === 1){
            a.push(t[i]);
        }else if(t[i][2] === 1){
            b.push(t[i]);
        }else{
            unlikeCount += 1;
        }
    }

    ab.sort((x,y) => x[0]-y[0]);
    a.sort((x,y) => x[0]-y[0]);
    b.sort((x,y) => x[0]-y[0]);
    // let max = Math.max(max, ab.length, a.length, b.length);
    // let min = Math.min(min, ab.length, a.length, b.length);
    // let inf = 9999999999;
    // for(let i = min+1; i <= max; i++){
    //     if(i >= ab.length) ab.push(inf);
    //     if(i >= a.length) a.push(inf);
    //     if(i >= b.length) b.push(inf);
    // }

    let p1 = p2 = p3 = 0;
    let ka = k;
    let kb = k;
    let res = 0;
    while(p1 < ab.length || p2 < a.length || p3 < b.length){
        if(ka === 0 && kb === 0)
            break;
        if(p2 < a.length && p3 < b.length){
            if(p1 < ab.length){
                if(a[p2][0]+b[p3][0] > ab[p1][0]){
                    res += ab[p1][0];
                    p1++;
                }else{
                    res += a[p2][0]+b[p3][0];
                    p2++;
                    p3++;
                }
            }else{
                res += a[p2][0]+b[p3][0];
                p2++;
                p3++;
            }
            ka--;
            kb--;
        }else{
            if(p1 >= ab.length){
                console.log(-1);
                return;
            }
            res += ab[p1][0];
            ka--;
            kb--;
            p1++;
        }
    }
    if(ka !== 0 || kb !== 0){
        console.log(-1);
        return;
    }
    console.log(res);
}

function sortFunc(x, y) {
   var likeBothX = x[1] && x[2];
   var likeBothY = y[1] && y[2];
   if (likeBothX) {
      if (likeBothY) {
         return x[0] - y[0];
      }
      return -1;
   }
   if (likeBothY) {
      return 1;
   }
   return x[0] - y[0];
}

function solve() {
   var nk = read().split(' ').map(Number);
   var n = nk[0];
   var k = nk[1];
   var ca = 0;
   var cb = 0;
   var arr = [];
   for (var i = 0; i < n; i++) {
      var tab = read().split(' ').map(Number);
      if (!tab[1] && !tab[2]) {
         continue;
      }
      arr.push(tab);
      ca += tab[1];
      cb += tab[2];
   }
   if (ca < k || cb < k) {
      write(-1);
      return;
   }
   n = arr.length;
   arr.sort(sortFunc);
   var ans = 0;
   ca = k;
   cb = k;
   for (var i = 0; i < n; i++) {
      if (arr[i][1]) {
         if (arr[i][2]) {
            ca--;
            cb--;
            if (ca >=0 || cb >= 0) {
               ans += arr[i][0];
            }
         } else {
            ca--;
            if (ca >= 0) {
               ans += arr[i][0];
            }
         }
      } else {
         if (arr[i][2]) {
            cb--;
            if (cb >= 0) {
               ans += arr[i][0];
            }
         }
      }
   }
   write(ans);
}

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

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;
   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();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', init);
   }
} else {
   init();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

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() {
    var aliceOnly = [], bobOnly = [], both = []
    var n, k;
    [n, k] = readline().split(" ").map(x => parseInt(x));
    for (var i=0; i<n; i++) {
        var a, b, c;
        [a, b, c] = readline().split(" ").map(x => parseInt(x));
        if (b === 1 && c === 1) {
            both.push(a);
        }
        else if (c === 1) {
            bobOnly.push(a);
        }
        else if (b === 1) {
            aliceOnly.push(a);
        }
    }
    aliceOnly.sort(); bobOnly.sort(); both.sort();
    const cum = (a => b => a+=b);
    const aCum = aliceOnly.map(cum(0)), bCum = bobOnly.map(cum(0)), cCum = both.map(cum(0));
    console.log(aCum, bCum, cCum);
    var time = 1000000000000000;
    for (var i=0; i<=k; i++) {
        // i: number of books both read
        var sum = 0;
        if (i <= cCum.length && k-i <= aCum.length && k-i <= bCum.length) {
            if (i >= 1) { sum += cCum[i-1]; }
            if (k-i >= 1) { sum += aCum[k-i-1] + bCum[k-i-1]; }
            time = Math.min(time, sum);
        }
    }
    if (time === 1000000000000000) { console.log(-1); }
    else { console.log(time); }
}

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() {
    var aliceOnly = [], bobOnly = [], both = []
    var n, k;
    [n, k] = readline().split(" ").map(x => parseInt(x));
    for (var i=0; i<n; i++) {
        var a, b, c;
        [a, b, c] = readline().split(" ").map(x => parseInt(x));
        if (b === 1 && c === 1) {
            both.push(a);
        }
        else if (c === 1) {
            bobOnly.push(a);
        }
        else if (b === 1) {
            aliceOnly.push(a);
        }
    }
    aliceOnly.sort(); bobOnly.sort(); both.sort();
    const cum = (a => b => a+=b);
    const aCum = aliceOnly.map(cum(0)), bCum = bobOnly.map(cum(0)), cCum = both.map(cum(0));
    var time = 1000000000000000;
    for (var i=0; i<=k; i++) {
        // i: number of books both read
        var sum = 0;
        if (i <= cCum.length && k-i <= aCum.length && k-i <= bCum.length) {
            if (i >= 1) { sum += cCum[i-1]; }
            if (k-i >= 1) { sum += aCum[k-i-1] + bCum[k-i-1]; }
            time = Math.min(time, sum);
        }
    }
    if (time === 1000000000000000) { console.log(-1); }
    else { console.log(time); }
}