You found a map of a weirdly shaped labyrinth. The map is a grid, consisting of $$$n$$$ rows and $$$n$$$ columns. The rows of the grid are numbered from $$$1$$$ to $$$n$$$ from bottom to top. The columns of the grid are numbered from $$$1$$$ to $$$n$$$ from left to right.The labyrinth has $$$n$$$ layers. The first layer is the bottom left corner (cell $$$(1, 1)$$$). The second layer consists of all cells that are in the grid and adjacent to the first layer by a side or a corner. The third layer consists of all cells that are in the grid and adjacent to the second layer by a side or a corner. And so on. The labyrinth with $$$5$$$ layers, for example, is shaped as follows:   The layers are separated from one another with walls. However, there are doors in these walls.Each layer (except for layer $$$n$$$) has exactly two doors to the next layer. One door is placed on the top wall of the layer and another door is placed on the right wall of the layer. For each layer from $$$1$$$ to $$$n-1$$$ you are given positions of these two doors. The doors can be passed in both directions: either from layer $$$i$$$ to layer $$$i+1$$$ or from layer $$$i+1$$$ to layer $$$i$$$.If you are standing in some cell, you can move to an adjacent by a side cell if a wall doesn't block your move (e.g. you can't move to a cell in another layer if there is no door between the cells).Now you have $$$m$$$ queries of sort: what's the minimum number of moves one has to make to go from cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of layers in the labyrinth. The $$$i$$$-th of the next $$$n-1$$$ lines contains four integers $$$d_{1,x}, d_{1,y}, d_{2,x}$$$ and $$$d_{2,y}$$$ ($$$1 \le d_{1,x}, d_{1,y}, d_{2,x}, d_{2,y} \le n$$$) — the coordinates of the doors. Both cells are on the $$$i$$$-th layer. The first cell is adjacent to the top wall of the $$$i$$$-th layer by a side — that side is where the door is. The second cell is adjacent to the right wall of the $$$i$$$-th layer by a side — that side is where the door is. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — the number of queries. The $$$j$$$-th of the next $$$m$$$ lines contains four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ ($$$1 \le x_1, y_1, x_2, y_2 \le n$$$) — the coordinates of the cells in the $$$j$$$-th query.

For each query, print a single integer — the minimum number of moves one has to make to go from cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$.

NoteHere is the map of the labyrinth from the second example. The doors are marked red.

'use strict';

function solve(n, m, doors, query) {
  const dist = Array.from({
    length: n - 1
  }, () => [0, 0, 0, 0]);
  for (let i = 1; i < n - 1; i++) {
    let [a1, b1, c1, d1] = doors[i],
        [a2, b2, c2, d2] = doors[i - 1];
    dist[i][0] = Math.abs(c1 - c2) + 1;
    dist[i][1] = Math.abs(i - c2) + Math.abs(i - b1) + 1;
    dist[i][2] = Math.abs(i - b2) + Math.abs(i - c1) + 1;
    dist[i][3] = Math.abs(b1 - b2) + 1;
  }
  const segTree = new SegTree(dist);
  let res = new Array(m);
  for (let [i, [a, b, c, d]] of query.entries()) {
    let e = Math.max(a, b),
        f = Math.max(c, d);
    if (e === f) {
      res[i] = Math.abs(a - c) + Math.abs(b - d);
      continue;
    } else if (e > f) {
      [a, b, c, d, e, f] = [c, d, a, b, f, e];
    }
    const st0 = Math.abs(a - doors[e][2]) + Math.abs(b - doors[e][3]),
          st1 = Math.abs(a - doors[e][0]) + Math.abs(b - doors[e][1]),
          en0 = Math.abs(c - doors[f - 1][2]) + Math.abs(d - (doors[f - 1][3] + 1)) + 1,
          en1 = Math.abs(c - (doors[f - 1][0] + 1)) + Math.abs(d - doors[f - 1][1]) + 1;
    let door;
    if (e + 1 === f) {
      door = [0, 0, 0, 0];
      res[i] = Math.min(st0 + door[0] + en0, st1 + door[3] + en1);
    } else {
      door = segTree.query(e + 1, f - 1);
      res[i] = Math.min(st0 + door[0] + en0, st0 + door[1] + en1, st1 + door[2] + en0, st1 + door[3] + en1);
    }
  }
  return res.join('\n');
}
class SegTree {
  constructor(nums = [], n = nums.length - 1) {
    this.nums = nums;
    this.n = n;
    this.root = this._newNode();
    this._build(this.root, 0, n);
    this.query = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._query(this.root, 0, n, x, y);
    };
  }
  _newNode(left = null, right = null) {
    return {
      left,
      right,
      door: [0, 0, 0, 0]
    };
  }
  merge(ld, rd) {
    return [Math.min(ld[0] + rd[0], ld[1] + rd[2]), Math.min(ld[0] + rd[1], ld[1] + rd[3]), Math.min(ld[2] + rd[0], ld[3] + rd[2]), Math.min(ld[2] + rd[1], ld[3] + rd[3])];
  }
  _up(node) {
    if (!node.left || !node.right) return;
    const ld = node.left.door,
          rd = node.right.door;
    node.door = this.merge(ld, rd);
  }
  _build(node = this.root, l, r) {
    if (l === r) {
      node.door = this.nums[l];
      return;
    }
    const mid = Math.floor((l + r) / 2);
    node.left = this._newNode();
    node.right = this._newNode();
    this._build(node.left, l, mid);
    this._build(node.right, mid + 1, r);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return [Infinity, Infinity, Infinity, Infinity];
    if (!node) return [Infinity, Infinity, Infinity, Infinity];
    if (l === x && r === y) return node.door;
    let res,
        mid = Math.floor((l + r) / 2);
    if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else {
      const ld = this._query(node.left, l, mid, x, mid),
            rd = this._query(node.right, mid + 1, r, mid + 1, y);
      res = this.merge(ld, rd);
    }
    return res;
  }
}

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

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

'use strict';

function solve(n, m, doors, query) {
  const dist = Array.from({
    length: n - 1
  }, () => [0, 0, 0, 0]);
  for (let i = 1; i < n - 1; i++) {
    let [a1, b1, c1, d1] = doors[i],
        [a2, b2, c2, d2] = doors[i - 1];
    dist[i][0] = Math.abs(c1 - c2) + 1;
    dist[i][1] = Math.abs(i - c2) + Math.abs(i - b1) + 1;
    dist[i][2] = Math.abs(i - b2) + Math.abs(i - c1) + 1;
    dist[i][3] = Math.abs(b1 - b2) + 1;
  }
  const segTree = new SegTree(dist);
  let res = new Array(m);
  for (let [i, [a, b, c, d]] of query.entries()) {
    let e = Math.max(a, b),
        f = Math.max(c, d);
    if (e === f) {
      res[i] = Math.abs(a - c) + Math.abs(b - d);
      continue;
    } else if (e > f) {
      [a, b, c, d, e, f] = [c, d, a, b, f, e];
    }
    let door;
    if (e + 1 === f) {
      door = [0, 0, 0, 0];
    } else {
      door = segTree.query(e + 1, f - 1);
    }
    const st0 = Math.abs(a - doors[e][2]) + Math.abs(b - doors[e][3]),
          st1 = Math.abs(a - doors[e][0]) + Math.abs(b - doors[e][1]),
          en0 = Math.abs(c - doors[f - 1][2]) + Math.abs(d - (doors[f - 1][3] + 1)) + 1,
          en1 = Math.abs(c - (doors[f - 1][0] + 1)) + Math.abs(d - doors[f - 1][1]) + 1;
    res[i] = Math.min(st0 + door[0] + en0, st0 + door[1] + en1, st1 + door[2] + en0, st1 + door[3] + en1);
  }
  return res.join('\n');
}
class SegTree {
  constructor(nums = [], n = nums.length - 1) {
    this.nums = nums;
    this.n = n;
    this.root = this._newNode();
    this._build(this.root, 0, n);
    this.query = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._query(this.root, 0, n, x, y);
    };
  }
  _newNode(left = null, right = null) {
    return {
      left,
      right,
      door: [0, 0, 0, 0]
    };
  }
  merge(ld, rd) {
    return [Math.min(ld[0] + rd[0], ld[1] + rd[2]), Math.min(ld[0] + rd[1], ld[1] + rd[3]), Math.min(ld[2] + rd[0], ld[3] + rd[2]), Math.min(ld[2] + rd[1], ld[3] + rd[3])];
  }
  _up(node) {
    if (!node.left || !node.right) return;
    const ld = node.left.door,
          rd = node.right.door;
    node.door = this.merge(ld, rd);
  }
  _build(node = this.root, l, r) {
    if (l === r) {
      node.door = this.nums[l];
      return;
    }
    const mid = Math.floor((l + r) / 2);
    node.left = this._newNode();
    node.right = this._newNode();
    this._build(node.left, l, mid);
    this._build(node.right, mid + 1, r);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return [Infinity, Infinity, Infinity, Infinity];
    if (!node) return [Infinity, Infinity, Infinity, Infinity];
    if (l === x && r === y) return node.door;
    let res,
        mid = Math.floor((l + r) / 2);
    if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else {
      const ld = this._query(node.left, l, mid, x, mid),
            rd = this._query(node.right, mid + 1, r, mid + 1, y);
      res = this.merge(ld, rd);
    }
    return res;
  }
}

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

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

'use strict';

function solve(n, m, doors, query) {
  const dist = Array.from({
    length: n - 1
  }, () => [0, 0, 0, 0]);
  for (let i = 1; i < n - 1; i++) {
    let [a1, b1, c1, d1] = doors[i],
        [a2, b2, c2, d2] = doors[i - 1];
    dist[i][0] = Math.abs(c1 - c2) + 1;
    dist[i][1] = Math.abs(i - c2) + Math.abs(i - b1) + 1;
    dist[i][2] = Math.abs(i - b2) + Math.abs(i - c1) + 1;
    dist[i][3] = Math.abs(b1 - b2) + 1;
  }
  const segTree = new SegTree(dist);
  let res = new Array(m);
  for (let [i, [a, b, c, d]] of query.entries()) {
    let e = Math.max(a, b),
        f = Math.max(c, d);
    if (e === f) {
      res[i] = Math.abs(a - c) + Math.abs(b - d);
      continue;
    } else if (e > f) {
      [a, b, c, d, e, f] = [c, d, a, b, f, e];
    }
    let door;
    if (e + 1 === f) {
      door = [0, 0, 0, 0];
    } else {
      door = segTree.query(e + 1, f - 1);
    }
    const st0 = Math.abs(a - doors[e][2]) + Math.abs(b - doors[e][3]),
          st1 = Math.abs(a - doors[e][0]) + Math.abs(b - doors[e][1]),
          en0 = Math.abs(c - doors[f - 1][2]) + Math.abs(d - (doors[f - 1][3] + 1)) + 1,
          en1 = Math.abs(c - (doors[f - 1][0] + 1)) + Math.abs(d - doors[f - 1][1]) + 1;
    res[i] = Math.min(st0 + door[0] + en0, st0 + door[1] + en1, st1 + door[2] + en0, st1 + door[3] + en1);
  }
  return res.join('\n');
}
class SegTree {
  constructor(nums = [], n = nums.length - 1) {
    this.nums = nums;
    this.n = n;
    this.root = this._newNode();
    this._build(this.root, 0, n);
    this.query = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._query(this.root, 0, n, x, y);
    };
  }
  _newNode(left = null, right = null) {
    return {
      left,
      right,
      door: [0, 0, 0, 0]
    };
  }
  _up(node) {
    if (!node.left || !node.right) return;
    const ld = node.left.door,
          rd = node.right.door;
    node.door[0] = Math.min(ld[0] + rd[0], ld[1] + rd[2]);
    node.door[1] = Math.min(ld[0] + rd[1], ld[1] + rd[3]);
    node.door[2] = Math.min(ld[2] + rd[0], ld[3] + rd[2]);
    node.door[3] = Math.min(ld[2] + rd[1], ld[3] + rd[3]);
  }
  _build(node = this.root, l, r) {
    if (l === r) {
      node.door = this.nums[l];
      return;
    }
    const mid = Math.floor((l + r) / 2);
    node.left = this._newNode();
    node.right = this._newNode();
    this._build(node.left, l, mid);
    this._build(node.right, mid + 1, r);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return [0, 0, 0, 0];
    if (!node) return [0, 0, 0, 0];
    if (l === x && r === y) return node.door;
    let res,
        mid = Math.floor((l + r) / 2);
    if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else {
      const ld = this._query(node.left, l, mid, x, mid),
            rd = this._query(node.right, mid + 1, r, mid + 1, y);
      res = [Math.min(ld[0] + rd[0], ld[1] + rd[2]), Math.min(ld[0] + rd[1], ld[1] + rd[3]), Math.min(ld[2] + rd[0], ld[3] + rd[2]), Math.min(ld[2] + rd[1], ld[3] + rd[3])];
    }
    return res;
  }
}

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

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

'use strict';

function solve(n, m, doors, query) {
  const dist = Array.from({
    length: n - 1
  }, () => [0, 0, 0, 0]);
  for (let i = 1; i < n - 1; i++) {
    let [a1, b1, c1, d1] = doors[i],
        [a2, b2, c2, d2] = doors[i - 1];
    dist[i][0] = Math.abs(c1 - c2) + 1;
    dist[i][1] = Math.abs(i - c2) + Math.abs(i - b1) + 1;
    dist[i][2] = Math.abs(i - b2) + Math.abs(i - c1) + 1;
    dist[i][3] = Math.abs(b1 - b2) + 1;
  }
  const segTree = new SegTree(dist);
  let res = new Array(m);
  for (let [i, [a, b, c, d]] of query.entries()) {
    let e = Math.max(a, b),
        f = Math.max(c, d);
    if (e === f) {
      res[i] = Math.abs(a - c) + Math.abs(b - d);
      continue;
    } else if (e > f) {
      [a, b, c, d, e, f] = [c, d, a, b, f, e];
    }
    let door;
    if (e + 1 === f) {
      door = [0, 0, 0, 0];
    } else {
      door = segTree.query(e + 1, f);
    }
    const st0 = Math.abs(a - doors[e][2]) + Math.abs(b - doors[e][3]),
          st1 = Math.abs(a - doors[e][0]) + Math.abs(b - doors[e][1]),
          en0 = Math.abs(c - doors[f - 1][2]) + Math.abs(d - (doors[f - 1][3] + 1)) + 1,
          en1 = Math.abs(c - (doors[f - 1][0] + 1)) + Math.abs(d - doors[f - 1][1]) + 1;
    res[i] = Math.min(st0 + door[0] + en0, st0 + door[1] + en1, st1 + door[2] + en0, st1 + door[3] + en1);
  }
  return res.join('\n');
}
class SegTree {
  constructor(nums = [], n = nums.length - 1) {
    this.nums = nums;
    this.n = n;
    this.root = this._newNode();
    this._build(this.root, 0, n);
    this.query = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._query(this.root, 0, n, x, y);
    };
  }
  _newNode(left = null, right = null) {
    return {
      left,
      right,
      door: [0, 0, 0, 0]
    };
  }
  _up(node) {
    if (!node.left || !node.right) return;
    const ld = node.left.door,
          rd = node.right.door;
    node.door[0] = Math.min(ld[0] + rd[0], ld[1] + rd[2]);
    node.door[1] = Math.min(ld[0] + rd[1], ld[1] + rd[3]);
    node.door[2] = Math.min(ld[2] + rd[0], ld[3] + rd[2]);
    node.door[3] = Math.min(ld[2] + rd[1], ld[3] + rd[3]);
  }
  _build(node = this.root, l, r) {
    if (l === r) {
      node.door = this.nums[l];
      return;
    }
    const mid = Math.floor((l + r) / 2);
    node.left = this._newNode();
    node.right = this._newNode();
    this._build(node.left, l, mid);
    this._build(node.right, mid + 1, r);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return [0, 0, 0, 0];
    if (!node) return [0, 0, 0, 0];
    if (l === x && r === y) return node.door;
    let res,
        mid = Math.floor((l + r) / 2);
    if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else {
      const ld = this._query(node.left, l, mid, x, mid),
            rd = this._query(node.right, mid + 1, r, mid + 1, y);
      res = [Math.min(ld[0] + rd[0], ld[1] + rd[2]), Math.min(ld[0] + rd[1], ld[1] + rd[3]), Math.min(ld[2] + rd[0], ld[3] + rd[2]), Math.min(ld[2] + rd[1], ld[3] + rd[3])];
    }
    return res;
  }
}

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

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

'use strict';

function solve(n, m, doors, query) {
  const dist = Array.from({
    length: n - 1
  }, () => [0, 0, 0, 0]);
  for (let i = 1; i < n - 1; i++) {
    let [a1, b1, c1, d1] = doors[i],
        [a2, b2, c2, d2] = doors[i - 1];
    dist[i][0] = Math.abs(c1 - c2) + 1;
    dist[i][1] = Math.abs(i - c2) + Math.abs(i - b1) + 1;
    dist[i][2] = Math.abs(i - b2) + Math.abs(i - c1) + 1;
    dist[i][3] = Math.abs(b1 - b2) + 1;
  }
  const segTree = new SegTree(dist);
  let res = new Array(m);
  for (let [i, [a, b, c, d]] of query.entries()) {
    let e = Math.max(a, b),
        f = Math.max(c, d);
    if (e === f) {
      res[i] = Math.abs(a - c) + Math.abs(b - d);
      continue;
    } else if (e > f) {
      [a, b, c, d, e, f] = [c, d, a, b, f, e];
    }
    let door;
    if (e + 1 === f) {
      door = [0, 0, 0, 0];
    } else {
      door = segTree.query(e + 1, f);
    }
    const st0 = Math.abs(a - doors[e][2]) + Math.abs(b - doors[e][3]),
          st1 = Math.abs(a - doors[e][0]) + Math.abs(b - doors[e][1]),
          en0 = Math.abs(c - doors[f - 1][2]) + Math.abs(d - doors[f - 1][3]),
          en1 = Math.abs(c - doors[f - 1][0]) + Math.abs(d - doors[f - 1][1]);
    res[i] = Math.min(st0 + door[0] + en0, st0 + door[1] + en1, st1 + door[2] + en0, st1 + door[3] + en1);
  }
  return res.join('\n');
}
class SegTree {
  constructor(nums = [], n = nums.length - 1) {
    this.nums = nums;
    this.n = n;
    this.root = this._newNode();
    this._build(this.root, 0, n);
    this.query = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._query(this.root, 0, n, x, y);
    };
  }
  _newNode(left = null, right = null) {
    return {
      left,
      right,
      door: [0, 0, 0, 0]
    };
  }
  _up(node) {
    if (!node.left || !node.right) return;
    const ld = node.left.door,
          rd = node.right.door;
    node.door[0] = Math.min(ld[0] + rd[0], ld[1] + rd[2]);
    node.door[1] = Math.min(ld[0] + rd[1], ld[1] + rd[3]);
    node.door[2] = Math.min(ld[2] + rd[0], ld[3] + rd[2]);
    node.door[3] = Math.min(ld[2] + rd[1], ld[3] + rd[3]);
  }
  _build(node = this.root, l, r) {
    if (l === r) {
      node.door = this.nums[l];
      return;
    }
    const mid = Math.floor((l + r) / 2);
    node.left = this._newNode();
    node.right = this._newNode();
    this._build(node.left, l, mid);
    this._build(node.right, mid + 1, r);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return [0, 0, 0, 0];
    if (!node) return [0, 0, 0, 0];
    if (l === x && r === y) return node.door;
    let res,
        mid = Math.floor((l + r) / 2);
    if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else {
      const ld = this._query(node.left, l, mid, x, mid),
            rd = this._query(node.right, mid + 1, r, mid + 1, y);
      res = [Math.min(ld[0] + rd[0], ld[1] + rd[2]), Math.min(ld[0] + rd[1], ld[1] + rd[3]), Math.min(ld[2] + rd[0], ld[3] + rd[2]), Math.min(ld[2] + rd[1], ld[3] + rd[3])];
    }
    return res;
  }
}

async function main(read) {
  try {
    let res = [];
    const n = Number(await read());
    const a = [];
    let tmp = n - 1;
    while (tmp--) {
      let [x1, y1, x2, y2] = (await read()).split(' ').map(str => Number(str) - 1);
      if (x1 < x2 || y1 > y2) a.push([x2, y2, x1, y1]);else a.push([x1, y1, x2, y2]);
    }
    const m = Number(await read());
    const b = [];
    tmp = m;
    while (tmp--) {
      b.push((await read()).split(' ').map(str => Number(str) - 1));
    }
    res.push(solve(n, m, a, b));
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

function solve(n, m, doors, query) {
  const dist = Array.from({
    length: n
  }, () => [0, 0, 0, 0]);
  for (let i = 1; i < n - 1; i++) {
    let [a1, b1, c1, d1] = doors[i],
        [a2, b2, c2, d2] = doors[i - 1];
    dist[i][0] = Math.abs(c1 - c2) + 1;
    dist[i][1] = Math.abs(i - c2) + Math.abs(i - b1) + 1;
    dist[i][2] = Math.abs(i - b2) + Math.abs(i - c1) + 1;
    dist[i][3] = Math.abs(b1 - b2) + 1;
  }
  const segTree = new SegTree(dist);
  let res = new Array(m);
  for (let [i, [a, b, c, d]] of query.entries()) {
    let e = Math.max(a, b),
        f = Math.max(c, d);
    if (e === f) {
      res[i] = Math.abs(a - c) + Math.abs(b - d);
      continue;
    } else if (e > f) {
      [a, b, c, d, e, f] = [c, d, a, b, f, e];
    }
    let door;
    if (e + 1 === f) {
      door = [0, 0, 0, 0];
    } else {
      door = segTree.query(e + 1, f);
    }
    const st0 = Math.abs(a - doors[e][2]) + Math.abs(b - doors[e][3]),
          st1 = Math.abs(a - doors[e][0]) + Math.abs(b - doors[e][1]),
          en0 = Math.abs(c - doors[f - 1][2]) + Math.abs(d - doors[f - 1][3]),
          en1 = Math.abs(c - doors[f - 1][0]) + Math.abs(d - doors[f - 1][1]);
    res[i] = Math.min(st0 + door[0] + en0, st0 + door[1] + en1, st1 + door[2] + en0, st1 + door[3] + en1);
  }
  return res.join('\n');
}
class SegTree {
  constructor(nums = [], n = nums.length - 1) {
    this.nums = nums;
    this.n = n;
    this.root = this._newNode();
    this._build(this.root, 0, n);
    this.query = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._query(this.root, 0, n, x, y);
    };
  }
  _newNode(left = null, right = null) {
    return {
      left,
      right,
      door: [0, 0, 0, 0]
    };
  }
  _up(node) {
    if (!node.left || !node.right) return;
    const ld = node.left.door,
          rd = node.right.door;
    node.door[0] = Math.min(ld[0] + rd[0], ld[1] + rd[2]);
    node.door[1] = Math.min(ld[0] + rd[1], ld[1] + rd[3]);
    node.door[2] = Math.min(ld[2] + rd[0], ld[3] + rd[2]);
    node.door[3] = Math.min(ld[2] + rd[1], ld[3] + rd[3]);
  }
  _build(node = this.root, l, r) {
    if (l + 1 === r) {
      node.door = this.nums[l];
      return;
    }
    const mid = Math.floor((l + r) / 2);
    node.left = this._newNode();
    node.right = this._newNode();
    this._build(node.left, l, mid);
    this._build(node.right, mid + 1, r);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return [0, 0, 0, 0];
    if (!node) return [0, 0, 0, 0];
    if (l === x && r === y) return node.door;
    let res,
        mid = Math.floor((l + r) / 2);
    if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else {
      const ld = this._query(node.left, l, mid, x, mid),
            rd = this._query(node.right, mid + 1, r, mid + 1, y);
      res = [Math.min(ld[0] + rd[0], ld[1] + rd[2]), Math.min(ld[0] + rd[1], ld[1] + rd[3]), Math.min(ld[2] + rd[0], ld[3] + rd[2]), Math.min(ld[2] + rd[1], ld[3] + rd[3])];
    }
    return res;
  }
}

async function main(read) {
  try {
    let res = [];
    const n = Number(await read());
    const a = [];
    let tmp = n - 1;
    while (tmp--) {
      let [x1, y1, x2, y2] = (await read()).split(' ').map(str => Number(str) - 1);
      if (x1 < x2 || y1 > y2) a.push([x2, y2, x1, y1]);else a.push([x1, y1, x2, y2]);
    }
    const m = Number(await read());
    const b = [];
    tmp = m;
    while (tmp--) {
      b.push((await read()).split(' ').map(str => Number(str) - 1));
    }
    res.push(solve(n, m, a, b));
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

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


Polycarp found the string $$$s$$$ and the permutation $$$p$$$. Their lengths turned out to be the same and equal to $$$n$$$.A permutation of $$$n$$$ elements — is an array of length $$$n$$$, in which every integer from $$$1$$$ to $$$n$$$ occurs exactly once. For example, $$$[1, 2, 3]$$$ and $$$[4, 3, 5, 1, 2]$$$ are permutations, but $$$[1, 2, 4]$$$, $$$[4, 3, 2, 1, 2]$$$ and $$$[0, 1, 2]$$$ are not.In one operation he can multiply $$$s$$$ by $$$p$$$, so he replaces $$$s$$$ with string $$$new$$$, in which for any $$$i$$$ from $$$1$$$ to $$$n$$$ it is true that $$$new_i = s_{p_i}$$$. For example, with $$$s=wmbe$$$ and $$$p = [3, 1, 4, 2]$$$, after operation the string will turn to $$$s=s_3 s_1 s_4 s_2=bwem$$$.Polycarp wondered after how many operations the string would become equal to its initial value for the first time. Since it may take too long, he asks for your help in this matter.It can be proved that the required number of operations always exists. It can be very large, so use a 64-bit integer type.

The first line of input contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases in input. The first line of each case contains single integer $$$n$$$ ($$$1 \le n \le 200$$$) — the length of string and permutation. The second line of each case contains a string $$$s$$$ of length $$$n$$$, containing lowercase Latin letters. The third line of each case contains $$$n$$$ integers — permutation $$$p$$$ ($$$1 \le p_i \le n$$$), all $$$p_i$$$ are different.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case of input. As an answer output single integer — the minimum number of operations, after which the string $$$s$$$ will become the same as it was before operations.

NoteIn the first sample operation doesn't change the string, so it will become the same as it was after $$$1$$$ operations.In the second sample the string will change as follows: $$$s$$$ = babaa $$$s$$$ = abaab $$$s$$$ = baaba $$$s$$$ = abbaa $$$s$$$ = baaab $$$s$$$ = ababa

const readline = require('readline')

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

function solve(n, str, arr) {
    const adj = {}
    for (let i = 0; i < arr.length; i++) {
        const a = i
        const b = arr[i] - 1
        adj[a] = adj[a] || []
        adj[a].push(b)
    }
    //
    const visited = {}
    let ans = 1n
    for (let i = 0; i < arr.length; i++) {
        if (visited[i]) continue
        const now = dfs(adj, i, visited)

        // let k = 0
        // const base = []
        // now.forEach(x => base[x] = str[x])
        // let prev = base
        // while (k < now.length) {
        //     k++
        //     const dp = []
        //     let same = true
        //     for (let j = 0; j < now.length; j++) {
        //         const x = now[j]
        //         dp[x] = prev[adj[x][0]]
        //         if (dp[x] !== base[x]) {
        //             same = false
        //             // break
        //         }
        //     }
        //     if (same) break
        //     prev = dp
        // }
        const base = now.map(x => str[x]).join('')
        let k = kmp(base + base, base)
        k = BigInt(k)
        const g = gcd(ans, k)
        ans *= k / g
        // console.log(now, k)
    }
    return ans
}
function kmp(source, p) {
  if (p === '') return 0;
  const next = new Array(p.length).fill(0);
  for (let l = 0, r = 1; r < p.length; r++) {
    while (l > 0 && p[l] !== p[r]) l = next[l - 1];
    if (p[l] === p[r]) next[r] = ++l;
  }
  // hack as from 1
  for (let i = 1, j = 0; i < source.length; i++) {
    while (j > 0 && source[i] !== p[j]) j = next[j - 1];
    if (source[i] === p[j]) j++;
    if (j === p.length) return i - j + 1;
  }
  return -1;
}
function dfs(adj, r, visited) {
    const stack = [[r, 0, -1]]
    const now = []
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
            now.push(u)
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (!visited[v]) { // has circle
            // if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            stack.pop()
        }
    }
    return now
}
function gcd(a, b) {
    if (a === 0n) return b
    if (b === 0n) return a

    while (a) {
        const r = b % a
        b = a
        a = r
    }
    return b
}

'use strict';

function solve(n, a, s) {
  let res = 1n;
  a = a.map(num => num - 1);
  const st = new Array(n);
  for (let i = 0; i < n; i++) {
    if (i === a[i] || st[i]) continue;
    const query = [i];
    for (let j of query) {
      st[j] = 1;
      if (a[j] === i) break;
      query.push(a[j]);
    }
    let str = query.map(i => s[i]).join('');
    if (new Set(str).size === 1) continue;
    const change = BigInt(kmp(str + str, str));
    res = res * change / gcd(res, change);
  }
  return res.toString();
}
function gcd(a, b) {
  return b ? gcd(b, a % b) : a;
}
function kmp(source, p) {
  if (p === '') return 0;
  const next = new Array(p.length).fill(0);
  for (let l = 0, r = 1; r < p.length; r++) {
    while (l > 0 && p[l] !== p[r]) l = next[l - 1];
    if (p[l] === p[r]) next[r] = ++l;
  }
  for (let i = 1, j = 0; i < source.length; i++) {
    while (j > 0 && source[i] !== p[j]) j = next[j - 1];
    if (source[i] === p[j]) j++;
    if (j === p.length) return i - j + 1;
  }
  return -1;
}

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

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

const readline = require('readline')

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

function solve(n, str, arr) {
    const adj = {}
    for (let i = 0; i < arr.length; i++) {
        const a = i
        const b = arr[i] - 1
        adj[a] = adj[a] || []
        adj[a].push(b)
    }
    //
    const visited = {}
    let ans = 1n
    for (let i = 0; i < arr.length; i++) {
        if (visited[i]) continue
        const now = dfs(adj, i, visited)

        let k = 0
        const base = {}
        now.forEach(x => base[x] = str[x])
        let prev = base
        while (k < now.length) {
            k++
            const dp = {}
            now.forEach(x => dp[x] = prev[adj[x][0]])
            let same = true
            for (let j = 0; j < now.length; j++) {
                if (base[now[j]] !== dp[now[j]]) {
                    same = false
                    break
                }
            }
            if (same) break
            prev = dp
        }
        // let p
        // let same = true
        // for (let j in now) {
        //     k++
        //     const x = str[+j - 1]
        //     if (p && x !== p) same = false
        //     p = x
        // }
        ans *= BigInt(k)
        // console.log(now, k)
    }
    return ans
}
function dfs(adj, r, visited) {
    const stack = [[r, 0, -1]]
    const now = []
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
            now.push(u)
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (!visited[v]) { // has circle
            // if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            stack.pop()
        }
    }
    return now
}

const readline = require('readline')

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

function solve(n, str, arr) {
    const adj = {}
    for (let i = 0; i < arr.length; i++) {
        const a = i + 1
        const b = arr[i]
        adj[a] = adj[a] || []
        adj[a].push(b)
    }
    //
    const visited = {}
    let ans = 1n
    for (let i = 0; i < arr.length; i++) {
        if (visited[i]) continue
        const now = dfs(adj, i, visited)
        let k = 0n
        let p
        let same = true
        for (let j in now) {
            k++
            const x = str[+j - 1]
            if (p && x !== p) same = false
            p = x
        }
        if (!same) ans *= k
        // console.log(now, k, same)
    }
    return ans
}
function dfs(adj, r, visited) {
    const stack = [[r, 0, -1]]
    const now = {}
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1
        now[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (!visited[v]) { // has circle
            // if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            stack.pop()
        }
    }
    return now
}


Ehab has an array $$$a$$$ of length $$$n$$$. He has just enough free time to make a new array consisting of $$$n$$$ copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.

The first line contains an integer $$$t$$$ — the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of elements in the array $$$a$$$. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array $$$a$$$. The sum of $$$n$$$ across the test cases doesn't exceed $$$10^5$$$.

For each testcase, output the length of the longest increasing subsequence of $$$a$$$ if you concatenate it to itself $$$n$$$ times.

NoteIn the first sample, the new array is $$$[3,2,\textbf{1},3,\textbf{2},1,\textbf{3},2,1]$$$. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be $$$[1,3,4,5,9]$$$.

'use strict'

const getLine = () => readline().split(' ')
const getInts = () => getLine().map(n => parseInt(n))
const getInt = () => getInts()[0]
const D = (...args) => { // D({name})
  [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))
}

main()

function main() {
  let t = getInt()
  while (t --> 0) {
    const n = getInt()
    const arr = getInts()
    const st = new Set(arr)
    print(st.size)
  }
}

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var n = +readline();
    var arr = readNumArray();
    var s = new Set(arr);
    print(s.size);
  }
}
main()

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

var t = parseInt(readline());
while(t-- > 0){
    var n = parseInt(readline());
    var arr = readline().split(" ").map( Number );
    var len = arr.length;
    arr.sort(compare);
    var count = 0;
    for(var i = 0 ;i<len-1; i++){
        if(arr[i]!=arr[i+1]){
            count++;
        }
    }
    // if(arr[len-1]!=arr[len-2])
    //     count++;
    print(count+1);
}

var toInt = x =>parseInt(x);

var t = parseInt(readline());

for(var tt=0;tt<t;tt++) {
    readline();
    var ar = readline().split(' ').map(toInt);

    var visited = {};
    ar = ar.filter(v => {
        var r = visited[v]===undefined;
        visited[v] = true;
        return r;
    });
    print(ar.length);

    // var sorted = ar.map((v,i) => ({v,i})).sort((a, b) =>{
    //     if (a.v===b.v) {
    //         return a.i-b.i;
    //     }
    //     return a.v-b.v;
    // });

    // var r=1;
    // for(var i=1, cycle=0;i<ar.length && cycle<=ar.length; i++) {
    //     if(sorted[i-1].i > sorted[i].i) {
    //         cycle++;
    //         print('c++ ', sorted[i-1].v);
    //     }
    //     print('>',cycle, sorted[i].v);
    //     r++;
    // }
    // print(r);

    // var q = [];
    // ar.forEach( (v,i) => ( q.push({i,v, cycle:0, l:1}) ));
    // var best = 0;
    // while(q.length > 0) {
    //     var cur = q.shift();
    //     best = Math.max(best, cur.l);
    //     if (cur.cycle >= ar.length) break;

    //     for(var i=cur.i+1; i<ar.length; i++) {
    //         if (ar[i] > ar[cur.i]) {
    //             q.push({i, cycle:cur.cycle, l:cur.l+1});
    //         }
    //     }
    //     for(var i=0; i<cur.i; i++) {
    //         if (ar[i] > ar[cur.i]) {
    //             q.push({i, cycle:cur.cycle+1, l:cur.l+1});
    //         }
    //     }
    // }
    // print(best);
}

var arrLength, arr, arrUniq;
var taskNum = readline();
for (var i = 0; i < taskNum; i++) {
  arrLen = readline();
  arr = readline().split(' ').map(x => parseInt(x));
  arrUniq = new Set(arr);
  print(Math.min(arrLen, arrUniq.size));
}

// input = readline();
var t = parseInt(readline());

while(t-- > 0) {
    var N = parseInt(readline());
    var array = readline().split(' ').map(x => parseInt(x));
    var res = Array.from(new Set(array));
    print(res.length);
}

//var input = readline();
var T = parseInt(readline());

for (var i = 0; i < T; i++) {
    var n = parseInt(readline());
    var ar = readline().split(' ').map(x => parseInt(x));
    var ok = Array.from(new Set(ar));
    print(ok.length);
}

process.stdin.resume();
process.stdin.setEncoding('utf-8')
let inputString = '';
let currentLine = 0;
process.stdin.on('data', input => { inputString += input; })
process.stdin.on('end', _ => { inputString = inputString.split('\n'); main(); })
const readline = () => { return inputString[currentLine++] }

function main() {
    let n = parseInt(readline());
    for (let i = 0; i < n; i++) {
        const len = parseInt(readline());
        const readNumbers = {};
        const uniqueNumber = readline()
          .split(' ')
          .map(line => parseInt(line))
          .reduce((acc, curr) => {
            if (!readNumbers[curr]) {
              readNumbers[curr] = true;
              acc += 1;
            }
            return acc;
          }, 0);

        console.log(uniqueNumber);
    }
}

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

let input = ''
let ptr = 0
process.stdin.on('data', (i) => {
  input += i
})

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

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt() {
  return parseInt(input[ptr++])
}

function readString() {
  return input[ptr++]
}

function readStrings() {
  return input[ptr++].split(' ')
}

function readInts() {
  return input[ptr++].split(' ').map(a => parseInt(a))
}

function main() {
  let t = readInt()
  while(t--) {
    const n = readInt()
    const a = readInts()
    let count = 0
    let map = {}
    for(let i = 0; i < n; i++) {
      if(!map[a[i]]) {
        map[a[i]] = true
        count++
      }
    }
    wr(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 (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 t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
  	var N = nextInt();
  	var list = nextIntArray();
  	var set = new Set();
  	for(var j = 0; j < N; j++){
  		set.add(list[j]);
  	}
  	output[i] = set.size;
  }
  myout(myconv(output, 9));
}

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

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

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

  const ans = new Set(d.split(' ').map(Number)).size;
  console.log(ans);

  c++;
});

rl.on('close', () => {

});

// Sample code to perform I/O:

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

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

function main(input) {
    let output = nameLookUp(input);
    process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split('\n');
    let ind = 0;
    let lis = [];
    for (let index = 0; index < +inputs[0]; index++) {

        ind += 2;
        lis.push([... new Set(inputs[ind].trim().split(' '))].length);
    }

    return lis.join('\n').toString();
}

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

const sol = () => {
     nums = data.trim().split(/\n/g);
     let t = Number(nums.shift());
     result = [];
     for(let i = 0; i < t; i += 1 ){
          let n = Number(nums[2 * i]);
          let arr = nums[2 * i + 1].trim().split(/\s+/g).map(Number);
          let s = new Set();
          arr.forEach((e) => {
               s.add(e);
               });
          result.push(s.size);
     }
     console.log(result.join('\n'));
}

process.stdin.on('end', sol);

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

var t = parseInt(readline());
while(t-- > 0){
    var n = parseInt(readline());
    var arr = readline().split(" ").map( Number );
    var len = arr.length;
    arr.sort(compare);
    var count = 0;
    for(var i = 0 ;i<len-1; i++){
        if(arr[i]!=arr[i+1]){
            count++;
        }
    }
    if(arr[len-1]!=arr[len-2])
        count++;
    print(count);
}

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

const sol = () => {
     nums = data.trim().split(/\n/g);
     let t = Number(nums.shift());
     result = [];
     for(let i = 0; i < t; i += 1 ){
          let n = Number(nums[2 * i]);
          let arr = nums[2 * i + 1].split(/\s+/g).map(Number);
          let s = new Set();
          arr.forEach((e) => {
               s.add(e);
               });
          result.push(s.size);
     }
     console.log(result.join('\n'));
}

process.stdin.on('end', sol);


Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000.

On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game.

NoteIn the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5.

var n = parseInt( readline() );
var s = readline().split(' ').map(function(v){ return +v; });

var i = 0, j=n-1;

var k = [0, 0];
var x = 1;
while(i<=j){
	x++;
	k[x%2];

	if(s[i]>s[j]){
		k[x%2] += s[i];
		i++;
	}else{
		k[x%2] += s[j];
		j--;
	}
}

print(k[0], k[1]);

var x=parseInt(readline());

var arr=readline().split(' ').map(a => parseInt(a));

var left=0, right=arr.length-1;
var sereja=0, dima=0, turn=0;

while(left<=right){
  if(arr[left]>=arr[right]){
    if(turn===0){
      sereja+=arr[left];
      turn=1;
    }else{
      dima+=arr[left];
      turn=0;
    }
    left++;
  }else{
    if(turn===0){
      sereja+=arr[right];
      turn=1;
    }else{
      dima+=arr[right];
      turn=0;
    }
    right--;
  }
}

print(sereja+' '+dima);

var sergja = true;
var dima = false;
var n = parseInt(readline());
var input=readline().split(' ').map(x=>parseInt(x));
var i = 0;
var j = n-1;
var big;
var s=0;
var d=0;
while(n>0){
    if(input[i]>input[j]){
        big = input[i];
        i++;
    }
    else{
        big=input[j];
        j--;
    }

    if(sergja){
        s+=big;
        sergja=false;
        dima=true;
    }
    else{
        d+=big;
        sergja=true;
        dima=false;
    }
    n--;
}

print(s+" "+d);

var turn = 0;
var n = parseInt(readline());
var input=readline().split(' ').map(x=>parseInt(x));
var i = 0;
var j = n-1;
var big;
var s=0;
var d=0;
while(n>0){
    if(input[i]>input[j]){
        big = input[i];
        i++;
    }
    else{
        big=input[j];
        j--;
    }

    if(turn%2===0){
        s+=big;
    }
    else{
        d+=big;
    }
    turn++;
    n--;
}

print(s+" "+d);

var n = readline();
var nums = readline().split(' ').map(function(x){return parseInt(x)});
var r = [0, 0];
var m = {true:1,false:0};
var f = false;

while(nums.length) {
  r[m[f]] += (nums[0] > nums[nums.length-1]) ? nums.shift() : nums.pop();
  f = !f;
}
print(r[0] + ' ' + r[1]);

var len = readline()
  var cards = readline().split(' ').map(Number)

  var indexLeft = 0
  var indexRight = len - 1
  var playerAScore = 0
  var playerBScore = 0
  var playerATurn = true

  for (var i = 0; i < len; i++) {
    var biggestNumber
    if (cards[indexLeft] > cards[indexRight]) {
      biggestNumber = cards[indexLeft]
      indexLeft += 1
    } else {
      biggestNumber = cards[indexRight]
      indexRight -= 1
    }

    if (playerATurn) {
      playerAScore += biggestNumber
      playerATurn = false
    } else {
      playerBScore += biggestNumber
      playerATurn = true
    }
  }

  print(playerAScore + ' ' + playerBScore)

var inputLength = readline();
var input =  readline().split(" ").map(x => parseInt(x));
var players = [0, 0];
var turn = 0;
for (var i = 0; i < inputLength; i++) {
	if(input[i] > input[inputLength - 1]) {
		players[turn]+= input[i];
	} else {
		players[turn]+= input[inputLength - 1];
		inputLength--;
		i--;
	}
	turn = turn === 0 ? 1 : 0;
}
print(players[0] + ' ' + players[1]);

;(function () {

	readline();
	var n = readline().split(' ').map(Number);
	var a = 0, b = 0, f = true;

	while (n.length) {
		if (n[0] > n[n.length - 1]) {
			if (f) a += n.shift();
			else b += n.shift();
		} else {
			if (f) a += n.pop();
			else b += n.pop();
		}

		f = !f;
	}

	print(a + " " + b);

}).call(this);

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i]);
	};
	return tokens;
}

function main() {
	var integers = tokenizeIntegers(readline());
	var numCards = integers[0];

	var cards = tokenizeIntegers(readline());
	var left = 0, right = cards.length-1;
	var totals = [0, 0];
	for (var i = 0; i < cards.length; i += 1) {
		if (cards[left] > cards[right]) {
			totals[i%2] += cards[left];
			left += 1;
		}
		else {
			totals[i%2] += cards[right];
			right -= 1;
		}
	}

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

main();

var n = parseInt(readline()) - 1,
	a = readline().split(" ").map(Number),
	i = 0, v = 1, s = 0, d = 0, k;
while (i <= n) {
	if (a[i] > a[n])  {
		k = a[i];
		i++;
	} else {
		k = a[n];
		n--;
	}
	if (v) {
		s += k;
		v = 0;
    } else {
		d += k;
		v = 1;
    }
}
write(s + " " + d);

var n = parseInt(readline());
var cards = readline().split(' ');

for (var i = 0; i < n; i++) {
  cards[i] = parseInt(cards[i]);
}

var sereja = 0;
var dima = 0;
var turn = 0;

while (cards.length > 0) {
  if (turn % 2 == 0) {
    if (cards[0] > cards[cards.length - 1]) {
      sereja += cards[0];
      cards.splice(0, 1);
    } else {
      sereja += cards[cards.length - 1];
      cards.splice(cards.length - 1, 1);
    }
  } else {
    if (cards[0] > cards[cards.length - 1]) {
      dima += cards[0];
      cards.splice(0, 1);
    } else {
      dima += cards[cards.length - 1];
      cards.splice(cards.length - 1, 1);
    }
  }

  turn++;
}

print(sereja, dima);

function trim(s) {
  return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
  return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
  var tokens = tokenize(s);
  for (var i = 0; i < tokens.length; i += 1) {
    tokens[i] = parseInt(tokens[i]);
  }
  return tokens;
}

function main() {
  var integers = tokenizeIntegers(readline());
  var numCards = integers[0];

  var cards = tokenizeIntegers(readline());
  var left = 0, right = cards.length-1;
  var isSergiiTurn = true;
  var sergii = 0;
  var dima = 0;
  for (var i = 0; i < cards.length; i += 1) {
    if (cards[left] > cards[right]) {
      value = cards[left];
      left += 1;
    }
    else {
      value = cards[right];
      right -= 1;
    }

    if (isSergiiTurn) {
      sergii += value;
      isSergiiTurn = false;
    } else {
      dima += value;
      isSergiiTurn = true;
    }
  }

  print(sergii + ' ' + dima);
}

main();

// Input 結尾的每一行應有換行符號，不然readline()會讀不到
var linedataCount = readline();
var linedata = readline().split(" ");
var round = linedata.length;
var sScore=0;
var dScore=0;
var bigvalue;

//var num=0;
while(linedata.length>0)
{
//num++;

     //print('round :'+ i);
     bigvalue = compare();
     sScore +=parseInt(bigvalue);
     //print('s:'+ sScore);
     bigvalue = compare();
     dScore +=parseInt(bigvalue);
     //print('d :'+ dScore);
//if(num>=4)
//break;
}

function compare()
{

     var firstvalue = linedata[0];
     var finalvalue = linedata[linedata.length-1];
     var value;
     if(!(firstvalue&&finalvalue))
     {
           return 0;
     }
     if(parseInt(firstvalue)>parseInt(finalvalue))
     {
        value = firstvalue;
        linedata.shift();
        //print('firstvalue>finalvalue');

     }
     else if (parseInt(firstvalue)==parseInt(finalvalue))
     {
          value = firstvalue;
          linedata.shift();
          //print('firstvalue=finalvalue');
     }
     else
     {
          value = finalvalue;
          linedata.pop();
          //print('firstvalue<finalvalue');
     }
    //print('bigvalue:'+value);
    //print('new linedata : ' + linedata);
    return value;
}
print(sScore,dScore);

var n=parseInt(readline());
var myArray=readline().split(' ').map(Number);
// print(myArray)
var arr=[];
var s=0;
var d=0;
left=0;
right=n-1;

while(left<=right){

  if(myArray[left]>myArray[right]){

    // print(myArray[left])
      arr.push(myArray[left]);
      left++;
  }else{
     arr.push(myArray[right]);
     right--;
  }
}
// print(arr);

for(var i=0; i<arr.length; i++){
  if(i%2==0){
    s=s+arr[i];
  }else{
    d=d+arr[i]
  }
}
print(s +" "+d);

readline();
var nums=readline().split(' ').map(Number);
var Sereja=0;
var Dima=0;
var i = 0;
var j = nums.length - 1;
var turn=0;
 while (i <= j) {
     if (nums[i] > nums[j] ) {
        if(turn%2==0)
        Sereja+=nums[i];

         else
         Dima+=nums[i];
        i++;}
else{
if(turn%2==0)

Sereja+=nums[j];
else
Dima+=nums[j];
j--;}
turn++;
 }

print(Sereja+" "+Dima)

var n = readline();
var length = parseInt(n, 10);
var arr = readline();
arr = arr.split(' ')

for (var index = 0; index < length; index++) {
    arr[index] = parseInt(arr[index], 10);
}

var left = 0;
var right = length-1;
var per1 = 0;
var per2 = 0;
var mid = ( left + right)/2;
for (var index = left; index <= mid; index++) {

    if (left == right ){
        per1 +=arr[left];
        break;
    }

    if(arr[left] > arr[right] ){
        per1 += arr[left];
        left++;
    } else {
        per1 += arr[right];
        right--;
    }

    if(arr[left] > arr[right] ){
        per2 += arr[left];
        left++;
    } else {
        per2 += arr[right];
        right--;
    }
}
print(`${per1 + " " + per2}`)

var n = parseInt(readline().split(' '));
    var input = readline().split(' ');
    input.forEach(function(elem){elem = parseInt(elem);});
    var sereja = 0, dima = 0, move=1;
    while(input.length>0)
    {
        var points = Math.max(input[0],input[input.length-1]);
        if(points==input[0]) input.splice(0,1);
        else input.splice(input.length-1,1);
        if(move%2) sereja+=points;
        else dima+=points;
        move++;
    }
    print(sereja+' '+dima);

var
    num      = parseInt(readline()),
    arr      = readline().split(" "),
    ser      = 0,
    dim      = 0,
    isSer    = true
;

for(var i in arr) {
    arr[i] = parseInt(arr[i]);
}

while(arr.length > 0) {
    var add = 0;
    if (arr[0] > arr[arr.length-1]) {
        add = arr[0];
        arr.shift();
    } else {
        add = arr[arr.length-1];
        arr.pop();
    }

    if (isSer) {
        ser += add;
    } else {
        dim += add;
    }

    isSer = !isSer;
}

print(ser + " " + dim);

function main() {
    var n = Number(readline());
    var data = readline().split(' ').map(Number);
    var i=0;
    var j = n-1;
    var sum1 = 0;
    var sum2 = 0;
    var turn = true;
    while(i<=j){
        if(turn){
            sum1+=Math.max(data[i], data[j])
        } else {
            sum2 += Math.max(data[i], data[j])
        }
        turn = !turn;
        if(data[i] > data[j]){
            i++;
        } else {
            j--;
        }
    }
    print(sum1 + " " + sum2)
}

main()

//  381A    Сережа и Дима

var n = parseInt(readline());

//var input_line = readline().split(' ').map(Number);
var arr = readline().split(' ').map(Number);

var countS = 0;
var countD = 0;
var i = 0;

n --;

while (i <= n) {
    if (arr[i] > arr[n]) {
        countS += arr[i];
        i ++;
    } else {
        countS += arr[n];
        n --;
    };

    if (i <= n) {
        if (arr[i] > arr[n]) {
            countD += arr[i];
            i ++;
        } else {
            countD += arr[n];
            n --;
        };
    };
}

print(countS + ' ' + countD + '\n');

var n = parseInt(readline());
var cards = readline().split(' ').map(Number);

// for (var i = 0; i < n; i++) {
//   cards[i] = parseInt(cards[i]);
// }

var sereja = 0;
var dima = 0;
var turn = 0;

while (cards.length > 0) {
  if (turn % 2 == 0) {
    if (cards[0] > cards[cards.length - 1]) {
      sereja += cards[0];
      cards.splice(0, 1);
    } else {
      sereja += cards[cards.length - 1];
      cards.splice(cards.length - 1, 1);
    }
  } else {
    if (cards[0] > cards[cards.length - 1]) {
      dima += cards[0];
      cards.splice(0, 1);
    } else {
      dima += cards[cards.length - 1];
      cards.splice(cards.length - 1, 1);
    }
  }

  turn++;
}

print(sereja, dima);

var n = parseInt(readline());
var cards = readline().split(' ').map(Number);

var sum_sereja = 0,
	sum_dima = 0;
var score;

var left =0, right = n - 1;

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

	if(cards[left]> cards[right]){
		score = cards[left];
		left ++;
	}else{
		score = cards[right];
		right --;
	}

	if(i%2==0) sum_sereja += score;
	else sum_dima +=score;
}

print(sum_sereja, sum_dima);

readline();
var a = readline().split(" "),o=[0,0],sh=0;
while(a.length) o[+(sh++%2)]+=+a[+a[0]>+a[a.length-1]?"shift":"pop"]();
print(o.join(" "));

(function() {
    var i , n = parseInt(readline());
    var cards = readline().split(' ');
    var ser = 0, dima = 0, l = 0 , r = n - 1;
    for( i = 0 ; i < n ; ++i ){
        if (i % 2 == 0)
           ser += parseInt(cards[l]) > parseInt(cards[r]) ?
                    parseInt(cards[l++]) : parseInt(cards[r--]);
        else
            dima += parseInt(cards[l]) > parseInt(cards[r]) ?
                    parseInt(cards[l++]) : parseInt(cards[r--]);
    }
    print(ser+" "+dima);
})();

var num = parseInt(readline());
var row = readline().split(" ").map(x => parseInt(x));

var shreeja = 0;
var dima = 0;
var flag = true; // 1 Shreeja, 0 dima;

function addToValue(value) {
    if (flag) {
        shreeja += value;
    } else {
        dima += value;
    }
}

for (var i = 0; i < num; i++) {
    if (row[0] > row[row.length - 1]) {
        // first Value is bigger
        var val = row.shift();
        addToValue(val);
    } else {
        // last Value is bigger
        var value = row.pop();
        addToValue(value);
    }

    flag = !flag;
}

print(shreeja + " " + dima);

process.stdin.resume();
process.stdin.setEncoding('utf8');

let input_stdin = "";
let input = "";
let input_currentline = 0;

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

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

process.stdin.on('end', function () {
    input = input_stdin.split("\n");
    main();
});

// your code goes here
function main() {
    const T=parseInt(readLine());
    let A = 0;
    let B = 0;
    let cards = readLine().split(' ').map(x => +x);
    for(let k = 0; k < T; k++) {
       if ( cards[0] >= cards[cards.length - 1]) {
            k%2===0 ? A += Number(cards.shift()) : B += Number(cards.shift())
       }
       else {
            k%2===0 ? A += Number(cards.pop()) : B += Number(cards.pop())
       }
    }
    console.log(A + ' ' + B);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    let n = readline().toLowerCase();
    let cards = readline().split(' ').map(x => parseInt(x));
    let DimaTurn = false;
    let dimaSum = 0;
    let serejaSum = 0;

    while (cards.length != 0){
       let num = cards[cards.length -1] >= cards[0] ? cards.pop() : cards.shift();
       if (DimaTurn) dimaSum +=num
        else serejaSum+= num;

        DimaTurn = !DimaTurn
    }

    console.log(serejaSum, dimaSum)

}

const readline = require('readline');

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

let numberOfCards;
let arrOfCards;
let pointsOfSereja = 0;
let pointsOfDima = 0;
let turnsCounter = 0 ;
let temp = 0 ;
rl.on("line", (input) => {
    if (!numberOfCards) {
        numberOfCards = parseInt(input.split(" "));
       // console.log(numberOfCards, typeof (numberOfCards))
    } else {
        if (!arrOfCards) arrOfCards = input.split(" ").map(Number)
        while (arrOfCards != 0) {
            turnsCounter++
            let lastIndex = arrOfCards[arrOfCards.length-1];
           // console.log(lastIndex)
            if (arrOfCards[0] > lastIndex) {
               temp =  arrOfCards.shift()
               // console.log(arrOfCards)
            }
            else {
               temp = arrOfCards.pop()
            }
            if (turnsCounter % 2 === 0 ){
                pointsOfDima += temp
            }
            else{
                pointsOfSereja += temp
            }
          //  console.log(pointsOfSereja , pointsOfDima ,"\n" , arrOfCards.length)

        }
        console.log(pointsOfSereja , pointsOfDima)
        if (turnsCounter == numberOfCards) rl.close();

    }
})

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

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

function main() {
  const x = readline();
  const x2 = readline()
    .split(" ")
    .map((x) => +x);
  serejaAndDima(x2);
}

function serejaAndDima(cards) {
  let serejaPoints = 0;
  let dimaPoints = 0;
  let coin = true;
  let point;

  while (cards.length) {
    if (cards[cards.length - 1] > cards[0]) {
      point = cards.pop();
    } else {
      point = cards.shift();
    }

    if (coin) {
      serejaPoints += point;
    } else {
      dimaPoints += point;
    }

    coin = !coin;
  }

  console.log(serejaPoints, dimaPoints);
}

//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 (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 list = nextIntArray();
  var L = 0;
  var R = 0;
  var turn = true;
  while(list.length > 0){
  	if(turn){
  		if(list[0] > list[list.length - 1]){
  			L += list.shift();
  		}else{
  			L += list.pop();
  		}
  		turn = false;
  	}else{
  		if(list[0] > list[list.length - 1]){
  			R += list.shift();
  		}else{
  			R += list.pop();
  		}
  		turn = true;
  	}
  }
  myout(L + " " + R);
}

const readline = require('readline');

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

let counter = 0;
let cards = [];

rl.on('line', (input) => {
    if (counter++ === 0) return;
    let line = input.split(' ');
    line.forEach(el => {
        cards.push(parseInt(el));
    });
    rl.close();
    let sol = solve(cards);
    console.log(sol[0], sol[1]);
});

const solve = (cards) => {
    let l = 0,
        r = cards.length - 1;
    let isSerejaturn = true;
    let serejaScore = 0;
    let dimaScore = 0;

    while (l <= r) {
        if (isSerejaturn) {
            if (cards[l] > cards[r]) {
                serejaScore += cards[l++];

            } else {
                serejaScore += cards[r--];
            }
            isSerejaturn = false;
        } else {
            if (cards[l] > cards[r]) {
                dimaScore += cards[l++];

            } else {
                dimaScore += cards[r--];
            }
            isSerejaturn = true;
        }
    }

    return [serejaScore, dimaScore];

}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const numOfCards = readline()
  const cards = readline().split(' ').map(card => parseInt(card))

  helper(numOfCards, cards)
}

function helper(numOfCards, cards) {
  let left = 0
  let right = numOfCards - 1
  let firstPlayerSum = 0
  let secondPlayerSum = 0
  let isFirstPlayerTurn = true

  while (left <= right) {
    if (cards[left] > cards[right]) {
      if (isFirstPlayerTurn) {
        firstPlayerSum += cards[left]
      } else {
        secondPlayerSum += cards[left]
      }
      left++
    } else {
      if (isFirstPlayerTurn) {
        firstPlayerSum += cards[right]
      } else {
        secondPlayerSum += cards[right]
      }
      right--
    }

    isFirstPlayerTurn = !isFirstPlayerTurn
  }

  console.log(firstPlayerSum + ' ' + secondPlayerSum)
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

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

function main() {
  // input
  const n = readline();
  const nums = readline().split(' ').map(x => parseInt(x));
  let l = 0;
  let r = nums.length - 1;
  let first = 0, second = 0;
  let turn = 1;
  while(l <= r) {
    if (nums[l] > nums[r]) {
      if (turn > 0) {
        first += nums[l];
      } else {
        second += nums[l];
      }
      l++;
    } else {
      if (turn > 0) {
        first += nums[r];
      } else {
        second += nums[r];
      }
      r--;
    }
    turn *= -1;
  }
  // output
  print(`${first} ${second}`);
}

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

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

  const arr = d.split(' ').map(Number);
  let i = 0;
  let l = 0;
  let r = arr.length - 1;

  let player1 = 0;
  let player2 = 0;
  let isTurn = 0;

  while(i < arr.length) {
    if (arr[l] > arr[r]) {
      if (isTurn === 0) {
        player1 += arr[l];
      }
      else {
        player2 += arr[l];
      }
      l++;
    }
    else {
      if (isTurn === 0) {
        player1 += arr[r];
      }
      else {
        player2 += arr[r];
      }
      r--;
    }

    isTurn = isTurn ? 0 : 1;

    i++;
  }

  console.log(player1, player2);

  c++;
});

function trim(s) {
  return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
  return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
  var tokens = tokenize(s);
  for (var i = 0; i < tokens.length; i += 1) {
    tokens[i] = parseInt(tokens[i]);
  }
  return tokens;
}

function main() {
  var integers = tokenizeIntegers(readline());
  var numCards = integers[0];

  var cards = tokenizeIntegers(readline());
  var left = 0, right = cards.length-1;
  var sergii = 0;
  var dima = 0;
  for (var i = 0; i < cards.length; i += 1) {
    if (cards[left] > cards[right]) {
      sergii += cards[left];
      left += 1;
    }
    else {
      dima += cards[right];
      right -= 1;
    }
  }

  print(sergii + ' ' + dima);
}

main();

// Input 結尾的每一行應有換行符號，不然readline()會讀不到
var linedataCount = readline();
var linedata = readline().split(" ");
var round = linedataCount/2;

var sScore=0;
var dScore=0;
var bigvalue;

for (var i=1;round>=i;i++)
{

     //print('round :'+ i);
     bigvalue = compare();
     sScore +=parseInt(bigvalue);
     //print('s:'+ sScore);
     bigvalue = compare();
     dScore +=parseInt(bigvalue);
     //print('d :'+ dScore);

}

function compare()
{
     var firstvalue = linedata[0];
     var finalvalue = linedata[linedata.length-1];
     var value;
     if(parseInt(firstvalue)>parseInt(finalvalue))
     {
        value = firstvalue;
        linedata.shift();
        //print('firstvalue>finalvalue');

     }
     else if (parseInt(firstvalue)==parseInt(finalvalue))
     {
          value = firstvalue;
          //print('firstvalue=finalvalue');

     }
     else
     {
          value = finalvalue;
          linedata.pop();
          //print('firstvalue<finalvalue');
     }
    //print('bigvalue:'+value);
    //print('new linedata : ' + linedata);
    return value;
}
print(sScore,dScore);

var n=parseInt(readline());
var myArray=readline().split(' ');
var s=0,d=0;
if(myArray.length == n){
 function sortArray(a,b){
    return b-a;
    }
    myArray.sort(sortArray);
    for(var i=0; i<myArray.length;i++){
      if(i%2==0){
        s=s+parseInt(myArray[i]);
      }else{
        d=d+parseInt(myArray[i]);
      }
    }
    print(s)
    print(d)

}

var n=parseInt(readline());
var myArray=readline().split(' ');
var s=0,d=0;
if(myArray.length == n){
 function sortArray(a,b){
    return b-a;
    }
    myArray.sort(sortArray);
    for(var i=0; i<myArray.length;i++){
      if(i%2==0){
        s=s+parseInt(myArray[i]);

      }else{
        d=d+parseInt(myArray[i]);
      }
    }
    print(s , d)

}

var n=parseInt(readline());
var myArray=readline().split(' ');
var s=0,d=0;
if(myArray.length == n){
 function sortArray(a,b){
    return b-a;
    }
    myArray.sort(sortArray);
    for(var i=0; i<myArray.length;i++){
      if(i%2==0){
        s=s+parseInt(myArray[i]);
      }else{
        d=d+parseInt(myArray[i]);
      }
    }
    print(s +" "+ d)
    // print(d)

}

var n=parseInt(readline());
var myArray=readline().split(' ').map(Number);
// print(myArray)
var arr=[];
var s=0;
var d=0;
left=0;
right=n-1;

while(left<=right){

  if(myArray[left]>myArray[right]){

    print(myArray[left])
      arr.push(myArray[left]);
      left++;
  }else{
     arr.push(myArray[right]);
     right--;
  }
}
// print(arr);

for(var i=0; i<arr.length; i++){
  if(i%2==0){
    s=s+arr[i];
  }else{
    d=d+arr[i]
  }
}
print(s +" "+d);

var n = readline();
var length = parseInt(n, 10);
var arr = readline();
arr = arr.split(' ')

for (var index = 0; index < length; index++) {
    arr[index] = parseInt(arr[index], 10);
}

var left = 0;
var right = length-1;
var per1 = 0;
var per2 = 0;

for (var index = left; index <= right; index++) {

    if(arr[left] > arr[right] ){
        per1 += arr[left];
        left++;
    } else {
        per1 += arr[right];
        right--;
    }

    if(arr[left] > arr[right] ){
        per2 += arr[left];
        left++;
    } else {
        per2 += arr[right];
        right--;
    }

    if (left == right ){
        per1 +=arr[left];
        break;
    }

}
print(`${per1 + " " + per2}`)

var n = readline();
var length = parseInt(n, 10);
var arr = readline();
arr = arr.split(' ')

for (var index = 0; index < length; index++) {
    arr[index] = parseInt(arr[index], 10);
}

var left = 0;
var right = length-1;
var per1 = 0;
var per2 = 0;
var mid = ( left + right)/2;
for (var index = left; index <= mid; index++) {

    if(arr[left] > arr[right] ){
        per1 += arr[left];
        left++;
    } else {
        per1 += arr[right];
        right--;
    }

    if(arr[left] > arr[right] ){
        per2 += arr[left];
        left++;
    } else {
        per2 += arr[right];
        right--;
    }

    if (left == right ){
        per1 +=arr[left];
        break;
    }

}
print(`${per1 + " " + per2}`)

(function() {
    var i , n = parseInt(readline());
    var cards = readline().split(' ');
    cards.sort(function(a,b){
        return parseInt(a) - parseInt(b);
    });
    var first = 0, second = 0;
    for( i = 0 ; i < n ; ++i ){
        if ( i % 2 === 1 ){
            first += parseInt(cards[i]);
        }else{
            second += parseInt(cards[i]);
        }
    }
    print(first+" "+second);
})();

(function() {
    var i , n = parseInt(readline());
    var cards = readline().split(' ');
    var ser = 0, dima = 0, l = 0 , r = n - 1;
    for( i = 0 ; i < n ; ++i ){
        if (i % 2 == 0)
           ser += cards[l] > cards[r] ? cards[l++] : cards[r--];
        else
            dima += cards[l] > cards[r] ? cards[l++] : cards[r--];
    }
    print(ser+" "+dima);
})();

(function() {
    var i , n = parseInt(readline());
    var cards = readline().split(' ');
    var ser = 0, dima = 0, l = 0 , r = n - 1;
    while ( l < r ){
       ser += parseInt(cards[l]) > parseInt(cards[r]) ?
               parseInt(cards[l++]) : parseInt(cards[r--]);
       if ( l > r ) break;
       dima += parseInt(cards[l]) > parseInt(cards[r]) ?
               parseInt(cards[l++]) : parseInt(cards[r--]);
    }
    print(ser+" "+dima);
})();

(function() {
    var i , n = parseInt(readline());
    var cards = readline().split(' ');
    cards.sort(function(a,b){
        return parseInt(a) - parseInt(b);
    });
    var ser = 0, dima = 0;
    for( i = 0 ; i < n ; ++i ){
        if ( i % 2 === 0 ){
            ser += parseInt(cards[i]);
        }else{
            dima += parseInt(cards[i]);
        }
    }
    print(ser+" "+dima);
})();

(function() {
    var i , n = parseInt(readline());
    var cards = readline().split(' ');
    var ser = 0, dima = 0, l = 0 , r = n - 1;
    while ( l < r ){
       ser += cards[l] > cards[r] ? parseInt(cards[l++]) : parseInt(cards[r--]);
       if ( l >= r ) break;
       dima += cards[l] > cards[r] ? parseInt(cards[l++]) : parseInt(cards[r--]);
    }
    print(ser+" "+dima);
})();

(function() {
    var i , n = parseInt(readline());
    var cards = readline().split(' ');
    var ser = 0, dima = 0, l = 0 , r = n - 1;
    while ( l < r ){
       ser += parseInt(cards[l]) > parseInt(cards[r]) ?
               parseInt(cards[l++]) : parseInt(cards[r--]);
       if ( l >= r ) break;
       dima += parseInt(cards[l]) > parseInt(cards[r]) ?
               parseInt(cards[l++]) : parseInt(cards[r--]);
    }
    print(ser+" "+dima);
})();

(function() {
    var i , n = parseInt(readline());
    var cards = readline().split(' ');
    var ser = 0, dima = 0, l = 0 , r = n - 1;
    for( i = 0 ; i < n ; ++i ){
        if (i % 2 == 0)
           ser += cards[l] > cards[r] ? parseInt(cards[l++]) : parseInt(cards[r--]);
        else
            dima += cards[l] > cards[r] ? parseInt(cards[l++]) : parseInt(cards[r--]);
    }
    print(ser+" "+dima);
})();

(function() {
    var i , n = parseInt(readline());
    var cards = readline().split(' ');
    cards.sort(function(a,b){
        return parseInt(a) - parseInt(b);
    });
    var first = 0, second = 0;
    for( i = 0 ; i < n ; ++i ){
        if ( i % 2 === 0 ){
            first += parseInt(cards[i]);
        }else{
            second += parseInt(cards[i]);
        }
    }
    print(first+" "+second);
})();

(function() {
    var i , n = parseInt(readline());
    var cards = readline().split(' ');
    cards.sort(function(a,b){
        return parseInt(b) - parseInt(a);
    });
    var ser = 0, dima = 0;
    for( i = 0 ; i < n ; ++i ){
        if ( i % 2 === 0 ){
            ser += parseInt(cards[i]);
        }else{
            dima += parseInt(cards[i]);
        }
    }
    print(ser+" "+dima);
})();

var num = parseInt(readline());
var row = readline().split(" ").map(x => parseInt(x));

var shreeja = 0;
var dima = 0;
var flag = true; // 1 Shreeja, 0 dima;

function addToValue(value) {
    if (flag) {
        shreeja += value;
    } else {
        dima += value;
    }
}

for (var i = 0; i < num; i++) {
    if (row[0] > row[row.length - 1]) {
        // first Value is bigger
        var val = row.unshift();
        addToValue(val);
    } else {
        // last Value is bigger
        var value = row.pop();
        addToValue(value);
    }

    flag = !flag;
}

print(shreeja + " " + dima);

const readline = require('readline');

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

let numberOfCards;
let arrOfCards;
let pointsOfSereja = 0;
let pointsOfDima = 0;
let turnsCounter = 0 ;
let temp = 0 ;
rl.on("line", (input) => {
    if (!numberOfCards) {
        numberOfCards = parseInt(input.split(" "));
       // console.log(numberOfCards, typeof (numberOfCards))
    } else {
        if (!arrOfCards) arrOfCards = input.split(" ").map(Number)
        while (arrOfCards != 0) {
            turnsCounter++
            let lastIndex = arrOfCards.length;
            if (arrOfCards[0] > lastIndex) {
               temp =  arrOfCards.shift()
               // console.log(arrOfCards)
            }
            else {
               temp = arrOfCards.pop()
            }
            if (turnsCounter % 2 === 0 ){
                pointsOfDima += temp
            }
            else{
                pointsOfSereja += temp
            }
          //  console.log(pointsOfSereja , pointsOfDima ,"\n" , arrOfCards.length)

        }
        console.log(pointsOfSereja , pointsOfDima)
        if (turnsCounter == numberOfCards) rl.close();

    }
})

const readline = require('readline');

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

let numberOfCards;
let arrOfCards;
let pointsOfSereja = 0;
let pointsOfDima = 0;
let turnsCounter = 1 ;
let temp = 0 ;
rl.on("line", (input) => {
    if (!numberOfCards) {
        numberOfCards = parseInt(input.split(" "));
       // console.log(numberOfCards, typeof (numberOfCards))
    } else {
        if (!arrOfCards) arrOfCards = input.split(" ").map(Number)
        while (arrOfCards != 0) {
            let lastIndex = arrOfCards.length;
            if (arrOfCards[0] > lastIndex) {
               temp =  arrOfCards.shift()
               // console.log(arrOfCards)
            }
            else {
               temp = arrOfCards.pop()
            }
            if (turnsCounter % 2 === 0 ){
                turnsCounter++

                pointsOfDima += temp
            }
            else{
                turnsCounter++

                pointsOfSereja += temp
            }
          //  console.log(pointsOfSereja , pointsOfDima ,"\n" , arrOfCards.length)

        }
        console.log(pointsOfSereja , pointsOfDima)
        if (turnsCounter == numberOfCards) rl.close();

    }
})


This problem is different from the easy version. In this version Ujan makes at most $$$2n$$$ swaps. In addition, $$$k \le 1000, n \le 50$$$ and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.Ujan has two distinct strings $$$s$$$ and $$$t$$$ of length $$$n$$$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most $$$2n$$$ times: he takes two positions $$$i$$$ and $$$j$$$ ($$$1 \le i,j \le n$$$, the values $$$i$$$ and $$$j$$$ can be equal or different), and swaps the characters $$$s_i$$$ and $$$t_j$$$.Ujan's goal is to make the strings $$$s$$$ and $$$t$$$ equal. He does not need to minimize the number of performed operations: any sequence of operations of length $$$2n$$$ or shorter is suitable.

The first line contains a single integer $$$k$$$ ($$$1 \leq k \leq 1000$$$), the number of test cases. For each of the test cases, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 50$$$), the length of the strings $$$s$$$ and $$$t$$$.  Each of the next two lines contains the strings $$$s$$$ and $$$t$$$, each having length exactly $$$n$$$. The strings consist only of lowercase English letters. It is guaranteed that strings are different.

For each test case, output "Yes" if Ujan can make the two strings equal with at most $$$2n$$$ operations and "No" otherwise. You can print each letter in any case (upper or lower). In the case of "Yes" print $$$m$$$ ($$$1 \le m \le 2n$$$) on the next line, where $$$m$$$ is the number of swap operations to make the strings equal. Then print $$$m$$$ lines, each line should contain two integers $$$i, j$$$ ($$$1 \le i, j \le n$$$) meaning that Ujan swaps $$$s_i$$$ and $$$t_j$$$ during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than $$$2n$$$ is suitable.

4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca

'use strict'

const problem = (n, s, t) => {
    const S = s.split('');
    const T = t.split('');
    const C = S.concat(T).reduce((r, i) => { r[i] = r[i] ? 0 : 1; return r; }, {});
    if (Object.keys(C).some(i => C[i])) return 'No';

    const ans = [];
    let x;
    for (let i = 0; i < n; i++) {
        if (S[i] === T[i]) continue;
        for (let j = i+1; j < n; j++) {
            if (S[i] === S[j]) {
                ans.push(`${j+1} ${i+1}`);
                x = S[j]; S[j] = T[i]; T[i] = x;
                break;
            }
            if (S[i] === T[j]) {
                ans.push(`${j+1} ${j+1}`);
                x = S[j]; S[j] = T[j]; T[j] = x;
                ans.push(`${j+1} ${i+1}`);
                x = S[j]; S[j] = T[i]; T[i] = x;
                break;
            }
        }
    }
    return `Yes\n${ans.length}\n${ans.join('\n')}`;
}
let q = +readline();
while(q--) print(problem(+readline(), readline(), readline()));

'use strict'

const problem = (n, s, t) => {
    const r = [];
    const S = [];
    const T = [];
    for (let i = 0; i < n; i++) {
        if (s[i] !== t[i]) {
            S.push(s[i]);
            T.push(t[i]);
            r.push(i+1);
        }
    }
    const check = {};
    for (let i = 0; i < S.length; i++) {
        check[S[i]] = (check[S[i]] || 0) + 1;
        check[T[i]] = (check[T[i]] || 0) + 1;
    }
    if (Object.keys(check).some(i => check[i]%2)) return 'No';

    const ans = [];
    for (let i = 0; i < S.length; i++) {
        if (S[i] === T[i]) continue;
        let x = S[i];
        let j = S.slice(i + 1).indexOf(x) + 1;
        if (!j) {
            ans.push(`${r[i]} ${r[i]}`);
            S[i] = T[i];
            T[i] = x;
            x = S[i];
            j = S.slice(i + 1).indexOf(x) + 1;
        }
        S[j] = T[i];
        T[i] = x;
        ans.push(`${r[i]} ${r[j]}`);
    }
    return `Yes\n${ans.length}\n${ans.join('\n')}`;
}
let q = +readline();
while(q--) print(problem(+readline(), readline(), readline()));

'use strict'

const problem = (n, s, t) => {
    const r = [];
    const S = [];
    const T = [];
    for (let i = 0; i < n; i++) {
        if (s[i] !== t[i]) {
            S.push(s[i]);
            T.push(t[i]);
            r.push(i+1);
        }
    }
    const check = {};
    for (let i = 0; i < S.length; i++) {
        check[S[i]] = (check[S[i]] || 0) + 1;
        check[T[i]] = (check[T[i]] || 0) + 1;
    }
    if (Object.keys(check).some(i => check[i]%2)) return 'No';

    const ans = [];
    for (let i = 0; i < S.length; i++) {
        if (S[i] === T[i]) continue;
        let x = S[i];
        let j = S.slice(i + 1).indexOf(x) + 1;
        if (!j) {
            ans.push(`${r[i]} ${r[i]}`);
            S[i] = T[i];
            T[i] = x;
            x = S[i];
            j = S.slice(i + 1).indexOf(x) + 1;
        }
        S[j] = T[i];
        T[i] = x;
        ans.push(`${r[j]} ${r[i]}`);
    }
    return `Yes\n${ans.length}\n${ans.join('\n')}`;
}
let q = +readline();
while(q--) print(problem(+readline(), readline(), readline()));

'use strict'

const problem = (n, s, t) => {
    const r = [];
    const S = [];
    const T = [];
    for (let i = 0; i < n; i++) {
        if (s[i] !== t[i]) {
            S.push(s[i]);
            T.push(t[i]);
            r.push(i+1);
        }
    }
    const check = {};
    for (let i = 0; i < S.length; i++) {
        check[S[i]] = (check[S[i]] || 0) + 1;
        check[T[i]] = (check[T[i]] || 0) + 1;
    }
    if (Object.keys(check).some(i => check[i]%2)) return print('No');

    print('Yes');
    for (let i = 0; i < S.length; i++) {
        if (S[i] === T[i]) continue;
        let x = S[i];
        let j = S.slice(i + 1).indexOf(x) + 1;
        if (!j) {
            print(r[i], r[i]);
            S[i] = T[i];
            T[i] = x;
            x = S[i];
            j = S.slice(i + 1).indexOf(x) + 1;
        }
        S[j] = T[i];
        T[i] = x;
        print(r[i], r[j])
    }
    return r;
}
let q = +readline();
while(q--) problem(+readline(), readline(), readline());