The only difference between the two versions is that in this version $$$n \leq 2 \cdot 10^5$$$ and the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.A terminal is a row of $$$n$$$ equal segments numbered $$$1$$$ to $$$n$$$ in order. There are two terminals, one above the other. You are given an array $$$a$$$ of length $$$n$$$. For all $$$i = 1, 2, \dots, n$$$, there should be a straight wire from some point on segment $$$i$$$ of the top terminal to some point on segment $$$a_i$$$ of the bottom terminal. You can't select the endpoints of a segment. For example, the following pictures show two possible wirings if $$$n=7$$$ and $$$a=[4,1,4,6,7,7,5]$$$.  A crossing occurs when two wires share a point in common. In the picture above, crossings are circled in red.What is the maximum number of crossings there can be if you place the wires optimally?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$) — the elements of the array. The sum of $$$n$$$ across all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the maximum number of crossings there can be if you place the wires optimally.

NoteThe first test case is shown in the second picture in the statement.In the second test case, the only wiring possible has the two wires cross, so the answer is $$$1$$$.In the third test case, the only wiring possible has one wire, so the answer is $$$0$$$.

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const readline_1 = __importDefault(require("readline"));
(() => {
    let readBase = readline_1.default.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    let buffer = [];
    let resolveList = [];
    readBase.on('line', data => {
        buffer.push(data);
        if (buffer.length <= resolveList.length) {
            resolveList[buffer.length - 1](data);
        }
    });
    let input = () => __awaiter(void 0, void 0, void 0, function* () {
        return new Promise(resolve => {
            resolveList.push(resolve);
            if (resolveList.length <= buffer.length) {
                resolve(buffer[resolveList.length - 1]);
            }
        });
    });
    main({ input }).then(() => {
        process.exit(0);
    });
})();
function main({ input }) {
    return __awaiter(this, void 0, void 0, function* () {
        let solve = () => __awaiter(this, void 0, void 0, function* () {
            let getMid = (l, r) => {
                return l + Math.floor((r - l) / 2);
            };
            let n = parseInt(yield input());
            let a = (yield input()).split(' ').map(v => parseInt(v));
            let tree = Array(n * 4 + 5).fill(0);
            let sonOfNode = (nod) => ({
                ls: nod * 2,
                rs: nod * 2 + 1,
            });
            let pushup = (nod) => {
                let { ls, rs } = sonOfNode(nod);
                tree[nod] = tree[ls] + tree[rs];
            };
            let build = (nod, l, r) => {
                if (l === r) {
                    tree[nod] = 0;
                    return;
                }
                let { ls, rs } = sonOfNode(nod);
                let mid = getMid(l, r);
                build(ls, l, mid);
                build(rs, mid + 1, r);
                pushup(nod);
            };
            let modify = (nod, l, r, pos, x) => {
                if (l === r) {
                    tree[nod] += x;
                    return;
                }
                let { ls, rs } = sonOfNode(nod);
                let mid = getMid(l, r);
                if (pos <= mid) {
                    modify(ls, l, mid, pos, x);
                }
                else {
                    modify(rs, mid + 1, r, pos, x);
                }
                pushup(nod);
            };
            let query = (nod, l, r, x, y) => {
                if (l === x && r === y) {
                    return tree[nod];
                }
                let { ls, rs } = sonOfNode(nod);
                let mid = getMid(l, r);
                if (y <= mid) {
                    return query(ls, l, mid, x, y);
                }
                else if (x > mid) {
                    return query(rs, mid + 1, r, x, y);
                }
                else {
                    let ans = query(ls, l, mid, x, mid);
                    return ans + query(rs, mid + 1, r, mid + 1, y);
                }
            };
            build(1, 1, n);
            let ans = 0;
            a.forEach(x => {
                ans += query(1, 1, n, x, n);
                modify(1, 1, n, x, 1);
            });
            console.log(ans);
        });
        let T = parseInt(yield input());
        for (let i = 0; i < T; i++) {
            yield solve();
        }
    });
}

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const readline_1 = __importDefault(require("readline"));
(() => {
    let readBase = readline_1.default.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    let buffer = [];
    let resolveList = [];
    readBase.on('line', data => {
        buffer.push(data);
        if (buffer.length <= resolveList.length) {
            resolveList[buffer.length - 1](data);
        }
    });
    let input = () => __awaiter(void 0, void 0, void 0, function* () {
        return new Promise(resolve => {
            resolveList.push(resolve);
            if (resolveList.length <= buffer.length) {
                resolve(buffer[resolveList.length - 1]);
            }
        });
    });
    main({ input }).then(() => {
        process.exit(0);
    });
})();
function main({ input }) {
    return __awaiter(this, void 0, void 0, function* () {
        let solve = () => __awaiter(this, void 0, void 0, function* () {
            let getMid = (l, r) => {
                return l + Math.floor((r - l) / 2);
            };
            class TreeArray {
                constructor(n) {
                    this.n = n;
                    this.arr = Array(n + 1).fill(0);
                }
                modify(pos, x) {
                    for (let i = pos; i <= n; i += i & -i) {
                        this.arr[i] += x;
                    }
                }
                queryR(pos) {
                    let ans = 0;
                    for (let i = pos; i > 0; i -= i & -i) {
                        ans += this.arr[i];
                    }
                    return ans;
                }
                query(posL, posR) {
                    return this.queryR(posR) - this.queryR(posL - 1);
                }
            }
            let n = parseInt(yield input());
            let a = (yield input()).split(' ').map(v => parseInt(v));
            let treeArray = new TreeArray(n);
            let ans = 0;
            a.forEach(x => {
                ans += treeArray.query(x, n);
                treeArray.modify(x, 1);
            });
            console.log(ans);
        });
        let T = parseInt(yield input());
        for (let i = 0; i < T; i++) {
            yield solve();
        }
    });
}

// ../../lib/ts/BIT.ts
var BIT = class {
  constructor(n2 = 0, op, init) {
    this.n = n2;
    this.op = op;
    this.init = init;
    this.seg = new Array(n2 + 1).fill(init);
  }
  add(i, v) {
    i++;
    while (i <= this.n) {
      this.seg[i] = this.op(this.seg[i], v);
      i += i & -i;
    }
  }
  sumTo(i) {
    let res = this.init;
    while (i > 0) {
      res = this.op(res, this.seg[i]);
      i -= i & -i;
    }
    return res;
  }
};

// codeforces/1676H2/src/ts/solution1.ts
var lines = [];
require("readline").createInterface({
  input: process.stdin
}).on("line", (line) => lines.push(line));
process.stdin.on("end", () => {
  main(lines);
});
var n;
var a;
var main = (lines2) => {
  let _ln = 0;
  const readString = () => lines2[_ln++];
  const readStrings = () => readString().split(" ");
  const readNumber = () => Number(readString());
  const readNumbers = () => readStrings().map(Number);
  for (let t = readNumber(); t > 0; t--) {
    n = readNumber();
    a = readNumbers();
    output(solve());
  }
};
var solve = () => {
  const bit = new BIT(n, (a2, b) => a2 + b, 0);
  let res = 0;
  for (const ai of a) {
    res += bit.sumTo(n) - bit.sumTo(ai - 1);
    bit.add(ai - 1, 1);
  }
  return res;
};
var output = (res) => {
  console.log(res);
};

// ../../lib/ts/segmentTree.ts
var STNode = class {
};
var SegmentTree = class {
  constructor(arr, op, e) {
    this.op = op;
    this.e = e;
    let n2 = 1;
    while (n2 * 2 < arr.length)
      n2 *= 2;
    this.tree = new Array(n2 * 4).fill(void 0).map((_) => new STNode());
    const build = (k, l, r) => {
      this.tree[k].l = l;
      this.tree[k].r = r;
      if (l === r) {
        this.tree[k].v = arr[l - 1];
        return;
      }
      const mid = l + r >> 1;
      const lc = k * 2, rc = lc + 1;
      build(lc, l, mid);
      build(rc, mid + 1, r);
      this.tree[k].v = this.op(this.tree[lc].v, this.tree[rc].v);
    };
    build(1, 1, arr.length);
  }
  update_(k, i, v) {
    if (this.tree[k].l === this.tree[k].r && this.tree[k].l === i) {
      this.tree[k].v = v;
      return;
    }
    const mid = this.tree[k].l + this.tree[k].r >> 1;
    const lc = k * 2, rc = lc + 1;
    if (i <= mid)
      this.update_(lc, i, v);
    else
      this.update_(rc, i, v);
    this.tree[k].v = this.op(this.tree[lc].v, this.tree[rc].v);
  }
  update(i, v) {
    this.update_(1, i + 1, v);
  }
  lazy(k, v) {
    this.tree[k].v = this.tree[k].lazy = v;
  }
  pushDown(k) {
    const lc = 2 * k, rc = lc + 1;
    this.lazy(lc, this.tree[k].lazy);
    this.lazy(rc, this.tree[k].lazy);
    this.tree[k].lazy = void 0;
  }
  updateRange_(k, l, r, v) {
    if (l <= this.tree[k].l && this.tree[k].r <= r)
      return this.lazy(k, v);
    if (this.tree[k].lazy !== void 0)
      this.pushDown(k);
    const mid = this.tree[k].l + this.tree[k].r >> 1;
    const lc = k * 2, rc = lc + 1;
    if (l <= mid)
      this.updateRange_(lc, l, r, v);
    if (mid < r)
      this.updateRange_(rc, l, r, v);
    this.tree[k].v = this.op(this.tree[lc].v, this.tree[rc].v);
  }
  updateRange(l, r, v) {
    this.updateRange_(1, l + 1, r + 1, v);
  }
  query_(k, l, r) {
    if (l <= this.tree[k].l && this.tree[k].r <= r)
      return this.tree[k].v;
    if (this.tree[k].lazy !== void 0)
      this.pushDown(k);
    let res = this.e;
    const mid = this.tree[k].l + this.tree[k].r >> 1;
    const lc = k * 2, rc = lc + 1;
    if (l <= mid)
      res = this.op(res, this.query_(lc, l, r));
    if (mid < r)
      res = this.op(res, this.query_(rc, l, r));
    return res;
  }
  query(l, r) {
    return this.query_(1, l + 1, r + 1);
  }
};

// codeforces/1676H2/src/ts/solution2.ts
var lines = [];
require("readline").createInterface({
  input: process.stdin
}).on("line", (line) => lines.push(line));
process.stdin.on("end", () => {
  main(lines);
});
var n;
var a;
var main = (lines2) => {
  let _ln = 0;
  const readString = () => lines2[_ln++];
  const readStrings = () => readString().split(" ");
  const readNumber = () => Number(readString());
  const readNumbers = () => readStrings().map(Number);
  for (let t = readNumber(); t > 0; t--) {
    n = readNumber();
    a = readNumbers();
    output(solve());
  }
};
var solve = () => {
  const b = new Array(n).fill(0);
  const segTree = new SegmentTree(b, (a2, b2) => a2 + b2, 0);
  let res = 0;
  for (const ai of a) {
    res += segTree.query(ai - 1, n - 1);
    b[ai - 1]++;
    segTree.update(ai - 1, b[ai - 1]);
  }
  return res;
};
var output = (res) => {
  console.log(res);
};

// ../../lib/ts/BIT.ts
var BIT = class {
  constructor(n2 = 0) {
    this.n = n2;
    this.seg = new Array(n2 + 1).fill(0);
  }
  add(i, v) {
    i++;
    while (i <= this.n) {
      this.seg[i] += v;
      i += i & -i;
    }
  }
  sumTo(i) {
    let res = 0;
    while (i > 0) {
      res += this.seg[i];
      i -= i & -i;
    }
    return res;
  }
  sum(a2, b) {
    return this.sumTo(b + 1) - this.sumTo(a2);
  }
};

// codeforces/1676H2/src/ts/solution1.ts
var lines = [];
require("readline").createInterface({
  input: process.stdin
}).on("line", (line) => lines.push(line));
process.stdin.on("end", () => {
  main(lines);
});
var n;
var a;
var main = (lines2) => {
  let _ln = 0;
  const readString = () => lines2[_ln++];
  const readStrings = () => readString().split(" ");
  const readNumber = () => Number(readString());
  const readNumbers = () => readStrings().map(Number);
  for (let t = readNumber(); t > 0; t--) {
    n = readNumber();
    a = readNumbers();
    output(solve());
  }
};
var solve = () => {
  const bit = new BIT(n);
  let res = 0;
  for (const ai of a) {
    res += bit.sum(ai - 1, n - 1);
    bit.add(ai - 1, 1);
  }
  return res;
};
var output = (res) => {
  console.log(res);
};

'use strict';
const readline = require('readline');
const util = require('util');
const lineReader = readline.createInterface({
    input: process.stdin,
});
let inputPos = 0;
const inputWords = [];
lineReader.on('line', (line) => {
    inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));
});
lineReader.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(inputWords[inputPos++]));
}
function nextStr() {
    return inputWords[inputPos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
const INF = Infinity;
function lsone(s) {
    return s & (-s);
}
class FenwickTree {
    constructor(n) {
        this.n = n;
        this.ft = af(n + 1).fill(0);
    }
    adjust(pos, v) {
        for (; pos < this.n; pos += lsone(pos)) {
            this.ft[pos] += v;
        }
        // printf("adjust(%d,%d) ft %j\n", pos, v, this.ft);
    }
    query(pos) {
        let rv = 0;
        for (; pos > 0; pos -= lsone(pos)) {
            rv += this.ft[pos];
        }
        return rv;
    }
}
function main() {
    let tc = nextInt();
    while (tc--) {
        let n = nextInt();
        const a = af(n);
        for (let i = 0; i < n; i++) {
            a[i] = nextInt();
        }
        const ft = new FenwickTree(n);
        let ans = 0;
        for (let i = 0; i < n; i++) {
            let prior = i;
            let left = ft.query(a[i] - 1);
            ans += prior - left;
            ft.adjust(a[i], 1);
        }
        printf("%d\n", ans);
    }
}

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

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

  return obj;
}

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

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

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

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

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

// SOLUTION:
IS_MULTITEST = 1;

const calc = ()=>{
  // READING:
  let [n] = ra();
  let A = ra().map(a=>a-1);
  // PROCESSING:
  let ans = 0;
  let cnt = {};
  let revA = new Array(n).fill(0);
  for (let i=0; i<n; i++){
    cnt[A[i]] = (cnt[A[i]]||0)+1;
    revA[A[i]] = i;
  }
  let t = new Array(n+1).fill(0)
  let sum = (r)=>{
    let result = 0;
    for (; r >= 0; r = (r & (r+1)) - 1)
      result += t[r];
    return result;
  }
  let inc = (i, delta)=>{
    for (; i < n; i = (i | (i+1)))
      t[i] += delta;
  }
  for (let i=0; i<n; i++){
    inc(A[i], 1);
  }
  for (let i=0; i<n; i++){
    inc(A[i], -1);
    ans += sum(A[i])
  }
  return ans;

  let cntLeft = 0;
  let deductLeft = new Array(n).fill(0);
  let cntRight = 0;
  let deductRight = new Array(n).fill(0);

  for (let i=1; i<n; i++){
    cntLeft -= deductLeft[i];
    if (A[i-1]>=i){
      cntLeft++;
      deductLeft[A[i-1]]++;
    }
    cntRight -= deductRight[i];
    if (revA[i-1]>=i){
      cntRight++;
      deductRight[revA[i-1]]++;
    }
    ans += cntLeft*cntRight;
    // maintain cnt of all from left bigger than i
    // maintain all from right lower than i
  }
  return ans;
};

const readline = require('readline')

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

let F
function inc(idx, val) {
    for (; idx < F.length; idx |= idx + 1) {
        F[idx] += val
    }
}
function sum(idx) {
    let s = 0
    for (; idx >= 0; idx = (idx & (idx + 1)) - 1) {
        s += F[idx]
    }
    return s
}

function solve(n, arr) {
    const sorted = arr.map((x, i) => ({ x, i: i + 1 }))
        .sort((a, b) => {
            if (a.x === b.x) {
                return b.i - a.i
            } else {
                return a.x - b.x
            }
        })
    // console.log(sorted)
    F = Array(n + 5).fill(0) // a little larger in case
    let ans = 0
    for (let i = sorted.length - 1; i >= 0; i--) {
        const it = sorted[i]
        ans += sum(it.i)
        //
        inc(it.i, 1)
    }
    return ans
}

//import { readline, print } from '@ip-algorithmics/codeforces-io';
var t = +readline();
var _loop_1 = function () {
    var n = readline().split(' ').map(function (v) { return +v; })[0];
    var a = readline().split(' ').map(function (v) { return +v; });
    var len = n + 1;
    var t_1 = [];
    while (len) {
        t_1.push(Array(len + 1).fill(0));
        len >>= 1;
    }
    var sum = 0;
    var _loop_2 = function (i) {
        var v = a[i] + 1;
        var _loop_3 = function (l) {
            var f = v & 1 ? function () { sum += t_1[l][v]; } : function () { };
            v >>= 1;
            f();
        };
        for (var l = 0; l < t_1.length; l++) {
            _loop_3(l);
        }
        v = a[i];
        for (var l = 0; l < t_1.length; l++) {
            if (~v & 1) {
                t_1[l][v >> 1] += 1;
            }
            v >>= 1;
        }
    };
    for (var i = n; i--;) {
        _loop_2(i);
    }
    print(sum);
};
while (t--) {
    _loop_1();
}

//import { readline, print } from '@ip-algorithmics/codeforces-io';
var t = +readline();
var _loop_1 = function () {
    var n = readline().split(' ').map(function (v) { return +v; })[0];
    var a = readline().split(' ').map(function (v) { return +v; });
    var len = n + 1;
    var t_1 = [];
    while (len) {
        t_1.push(Array(len + 1).fill(0));
        len >>= 1;
    }
    var sum = 0;
    var _loop_2 = function (i) {
        var v = a[i] + 1;
        var _loop_3 = function (l) {
            var f = v & 1 ? function () { sum += t_1[l][v]; } : function () { };
            v >>= 1;
            f();
        };
        for (var l = 0; l < t_1.length; l++) {
            _loop_3(l);
        }
        v = a[i] + 1;
        for (var l = 0; l < t_1.length; l++) {
            if (v ^ 1) {
                t_1[l][v >> 1] += 1;
            }
            v >>= 1;
        }
    };
    for (var i = n; i--;) {
        _loop_2(i);
    }
    print(sum);
};
while (t--) {
    _loop_1();
}


You have a fence consisting of $$$n$$$ vertical boards. The width of each board is $$$1$$$. The height of the $$$i$$$-th board is $$$a_i$$$. You think that the fence is great if there is no pair of adjacent boards having the same height. More formally, the fence is great if and only if for all indices from $$$2$$$ to $$$n$$$, the condition $$$a_{i-1} \neq a_i$$$ holds.Unfortunately, it is possible that now your fence is not great. But you can change it! You can increase the length of the $$$i$$$-th board by $$$1$$$, but you have to pay $$$b_i$$$ rubles for it. The length of each board can be increased any number of times (possibly, zero).Calculate the minimum number of rubles you have to spend to make the fence great again!You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of queries. The first line of each query contains one integers $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of boards in the fence. The following $$$n$$$ lines of each query contain the descriptions of the boards. The $$$i$$$-th line contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$) — the length of the $$$i$$$-th board and the price for increasing it by $$$1$$$, respectively. It is guaranteed that sum of all $$$n$$$ over all queries not exceed $$$3 \cdot 10^5$$$. It is guaranteed that answer to each query will not exceed $$$10^{18}$$$.

For each query print one integer — the minimum number of rubles you have to spend to make the fence great.

NoteIn the first query you have to increase the length of second board by $$$2$$$. So your total costs if $$$2 \cdot b_2 = 2$$$.In the second query you have to increase the length of first board by $$$1$$$ and the length of third board by $$$1$$$. So your total costs if $$$1 \cdot b_1 + 1 \cdot b_3 = 9$$$.In the third query the fence is great initially, so you don't need to spend rubles.

'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 cost = [0]
    const arr = [0]
    for (let i = 1; i <= n; ++i) {
      const ab = getInts()
      arr[i] = ab[0]
      cost[i] = ab[1]
    }

    print(solve(arr, cost))
  }
}

function solve (arr, cost) {
  const n = arr.length
  const dp = [[0, cost[0], cost[0] * 2]]

  for (let i = 1; i < n; ++i) {
    const cur = []
    for (let j = 0; j <= 2; ++j) {
      let best = Number.MAX_SAFE_INTEGER
      for (let k = 0; k <= 2; ++k) {
        if (arr[i - 1] + k !== arr[i] + j) {
          best = Math.min(best, dp[i - 1][k] + cost[i] * j)
        }
      }
      cur[j] = best
    }
    dp[i] = cur
  }

  return Math.min(dp[n - 1][0], dp[n - 1][1], dp[n - 1][2])
}

'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() {
  var t = getInt()
  while (t --> 0) {
    const n = getInt()
    const cost = [0]
    const arr = [0]
    for (var i = 1; i <= n; ++i) {
      const ab = getInts()
      arr[i] = ab[0]
      cost[i] = ab[1]
    }

    print(solve(arr, cost))
  }
}

function solve (arr, cost) {
  const n = arr.length
  const dp = [[0, cost[0], cost[0] * 2]]

  for (var i = 1; i < n; ++i) {
    const cur = []
    for (var j = 0; j <= 2; ++j) {
      var best = Number.MAX_SAFE_INTEGER
      for (var k = 0; k <= 2; ++k) {
        if (arr[i - 1] + k !== arr[i] + j) {
          best = Math.min(best, dp[i - 1][k] + cost[i] * j)
        }
      }
      cur[j] = best
    }
    dp[i] = cur
  }

  return Math.min(dp[n - 1][0], dp[n - 1][1], dp[n - 1][2])
}

'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 cost = [0]
    const arr = [0]
    for (let i = 0; i < n; ++i) {
      const ab = getInts()
      arr.push(ab[0])
      cost.push(ab[1])
    }

    print(solve(arr, cost))
  }
}

function solve (arr, cost) {
  const n = arr.length
  const dp = [[0, 0]]

  for (let i = 1; i < n; ++i) {
    dp.push([0, 0])
    const changeCurrent = calc(i, arr, cost)

    if (arr[i] !== arr[i - 1]) {
      dp[i][0] = Math.min(dp[i - 1][0], dp[i - 1][1])
    }
    else {
      dp[i][0] = dp[i - 1][1]
    }
    dp[i][1] = Math.min(dp[i - 1][0] + changeCurrent, dp[i - 1][1] + changeCurrent)
  }

  return Math.min(dp[n - 1][0], dp[n - 1][1])
}

function calc (i, arr, cost) {
  let times = 1
  while (true) {
    const val = arr[i] + times
    if (val !== arr[i + 1] && val !== arr[i - 1]) break
    times ++
  }

  return times * cost[i]
}

'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 cost = [0]
    const arr = [0]
    for (let i = 0; i < n; ++i) {
      const ab = getInts()
      arr.push(ab[0])
      cost.push(ab[1])
    }

    print(solve(arr, cost))
  }
}

function solve (arr, cost) {
  const n = arr.length
  const dp = [[0, 0]]
  for (let i = 1; i < n; ++i) {
    dp.push([0, 0])
    if (arr[i] === arr[i - 1]) {
      dp[i][0] = dp[i - 1][1]
      dp[i][1] = dp[i - 1][0] + cost[i]
    } else {
      dp[i][0] = Math.min(dp[i - 1][0], calc(i - 1, dp[i - 1][1], arr, cost))
      dp[i][1] = dp[i - 1][0] + cost[i]
    }
  }

  return Math.min(dp[n - 1][0], dp[n - 1][1])
}

function calc (i, cur, arr, cost) {
  if (arr[i] + 1 === arr[i + 1]) {
    cur += cost[i]
  }
  return cur
}


Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai  ≤  bi).Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!

The first line of the input contains one integer n (2 ≤ n ≤ 100 000) — number of cola cans. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — volume of remaining cola in cans. The third line contains n space-separated integers that b1, b2, ..., bn (ai ≤ bi ≤ 109) — capacities of the cans.

Print "YES" (without quotes) if it is possible to pour all remaining cola in 2 cans. Otherwise print "NO" (without quotes). You can print each letter in any case (upper or lower).

NoteIn the first sample, there are already 2 cans, so the answer is "YES".

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')
  const n = parseInt(arr.shift())
  const remain2 = arr.shift().split(' ')
  const capacity2 = arr.shift().split(' ')
  var remain = []
  var capacity = []
  var sum = 0
  for(let i = 0; i < n; i++) {
    remain.push(parseInt(remain2[i]))
    capacity.push(parseInt(capacity2[i]))
  }
  sum = remain.reduce((a, b) => a + b)

  capacity = capacity.sort((a, b) => b - a)
  // console.log(capacity)

  if(capacity[0] + capacity[1] >= sum) console.log('YES')
  else console.log('NO')
})

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

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

  if (c === 1) {
    c++;
    cola = d.split(' ').map(Number).reduce((a, b) => a + b, 0);
    return;
  }

  cans = d.split(' ').map(Number);
  cans.sort((a, b) => b - a);

  c++;
});

rl.on('close', () => {
  if (n === 2) {
    console.log('YES');
    return;
  }

  const [a, b] = cans;

  if (a + b >= cola) {
    console.log('YES');
  }
  else {
    console.log("NO");
  }
});

var n = parseInt(readline());
var sum = 0, max1 = 0,  max2 = 0;
var array1 = readline().split(' ');
var array2 = readline().split(' ');
for (var i = 0; i < n; i++) {
	array2[i]= parseInt(array2[i]);
	array1[i]= parseInt(array1[i]);
}
for (var i = 0; i < n; i++) {
	sum += array1[i];
	if (array2[i] > max1) {
		max2 = max1;
		max1 = array2[i];
	} else if (array2[i] > max2) {
		max2 = array2[i];
	}
}
if (sum > max1 + max2) {
	print('NO');
} else {
	print('YES');
}

n = +readline();
function add(a, b) {
  return a + b;
}
function cmp(a, b) {
  return b - a;
}
a = readline().split(" ").map(Number).reduce(add, 0);
b = readline().split(" ").map(Number).sort(cmp).slice(0, 2).reduce(add, 0);
print(b >= a ? "YES" : "NO");

n = +readline();
function add(a, b) {
  return a + b;
}
function cmp(a, b) {
  return a - b;
}
a = readline().split(" ").map(Number).reduce(add, 0);
b = readline().split(" ").map(Number).sort(cmp).slice(-2).reduce(add, 0);
// print(b);
print(b >= a ? "YES" : "NO");

function toInt(x) {
	return parseInt(x);
}

var n = toInt(readline());
var sum = 0;
var max1 = 0;
var max2 = 0;
var ar = readline().split(' ').map(toInt);
var br = readline().split(' ').map(toInt);

for (var i = 0; i < n; i++) {
	sum += ar[i];
	if (br[i] > max1) {
		max2 = max1;
		max1 = br[i];
	} else if (br[i] > max2) {
		max2 = br[i];
	}
}

if (sum > max1 + max2) {
	print('NO');
} else {
	print('YES');
}

var n = parseInt(readline(), 10)
    a = readline().split(' ').map(el => parseInt(el, 10)),
    b = readline().split(' ').map(el => parseInt(el, 10)).sort((a,b) => b-a);

print((a.reduce((a,b) => a+b) <= b[0]+b[1]) ? 'YES' : 'NO');

n = +readline();
volume = readline();
banks = readline();
vol = 0;

arrV = volume.split(" ");
arrV.forEach(function(item, i, arr){
  vol = vol + +item;
})

arrB = banks.split(" ");

arrB.sort(compareNumeric);

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

place = +arrB[0] + +arrB[1];
if (place >= vol){
  write("YES");
} else {
  write("NO");
}

n = +readline();
function add(a, b) {
  return a + b;
}
a = readline().split(" ").map(Number).reduce(add, 0);
b = readline().split(" ").map(Number).sort().slice(-2).reduce(add, 0);
// print(b);
print(b >= a ? "YES" : "NO");

n = +readline();
function add(a, b) {
  return a + b;
}
function cmp(a, b) {
  return a - b;
}
a = readline().split(" ").map(Number).reduce(add, 0);
b = readline().split(" ").map(Number).sort(cmp).slice(-2, 0).reduce(add, 0);
print(b >= a ? "YES" : "NO");

n = +readline();
function add(a, b) {
  return a + b;
}
a = readline().split(" ").map(Number).reduce(add, 0);
b = readline().split(" ").map(Number).sort().slice(-2).reduce(add, 0);
print(b >= a ? "YES" : "NO");

n = +readline();
function add(a, b) {
  return a + b;
}
function cmp(a, b) {
  return b - a;
}
a = readline().split(" ").map(Number).reduce(add, 0);
b = readline().split(" ").map(Number).sort(cmp).slice(2).reduce(add, 0);
print(b >= a ? "YES" : "NO");

function toInt(x) {
	return parseInt(x);
}

var n = toInt(readline());
var sum = 0;
var max1 = 0;
var max2 = 0;
var ar = readline().split(' ').map(toInt);
var br = readline().split(' ').map(toInt);

for (var i = 0; i < n; i++) {
	sum += ar[i];
	if (br[i] > max1) {
		max2 = max1;
		max1 = br[i];
	}
}

if (sum > max1 + max2) {
	print('NO');
} else {
	print('YES');
}


You are given an array $$$a_1, a_2, \dots , a_n$$$. Array is good if for each pair of indexes $$$i < j$$$ the condition $$$j - a_j \ne i - a_i$$$ holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if $$$a = [1, 1, 3, 5]$$$, then shuffled arrays $$$[1, 3, 5, 1]$$$, $$$[3, 5, 1, 1]$$$ and $$$[5, 3, 1, 1]$$$ are good, but shuffled arrays $$$[3, 1, 5, 1]$$$, $$$[1, 1, 3, 5]$$$ and $$$[1, 1, 5, 3]$$$ aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 100$$$).

For each test case print the shuffled version of the array $$$a$$$ which is good.

function merge (arrA, arrB) {
  var merged = [];
  var j = 0;
  var k = 0;

  while (merged.length !== (arrA.length + arrB.length)) {
    if (arrB[k] === undefined || arrA[j] >= arrB[k]) {
      merged.push(arrA[j]);
      j++;
    } else if (arrA[j] === undefined || arrA[j] < arrB[k]) {
      merged.push(arrB[k]);
      k++;
    }
  }

  return merged;
}

function mergeSort (array) {
  var result = array.map(num => [num]);

  while (result.length > 1) {
    var oddNumbered = result.length % 2 !== 0;
    var temp = [];

    for (var i = 0; i < result.length; i += 2) {
      var a = result[i];
      var b = result[i + 1];

      if (oddNumbered && i === (result.length - 3)) {
        b = merge(b, result[i + 2]);
        i++;
      }

      temp.push(merge(a, b));
    }

    result = temp;
  }
  return result[0];
}

function processItem() {
    var count = readline();
  var items = readline().split(' ').map(function(i) { return +i; });

  print(mergeSort(items).join(' '));
}

function processItems() {
  var itemsCount = +readline();
  var items = [];

  for (var i = 0; i < itemsCount; ++i) {
    processItem();
  }

  return items;
}

processItems();

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
//atcoderのサンプルは最後に改行入れること
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main() {
    var t = nextInt();
    var output = new Array(t);
    for(var i = 0; i < t; i++){
        var n = nextInt();
        var list = nextIntArray();
        //good list?
        list.sort(function(a,b){
            return b - a;
        });
        output[i] = myconv(list,8);
    }
    myout(myconv(output,9));
}

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

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var len = readline();
    var arr = readNumArray();

    print(arr.sort((a, b) => b - a).join(" "));
  }
}

main()

//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));
    ar.sort((a, b) => b - a);

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

//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));
    print(ar.sort((a, b) => b - a).join(' '));
}

var t=readline();
while(t--)
{
	var n=readline();
	var arr = readline().split(" ").map(x=> parseInt(x));
	var ans=arr.sort((x,y) => x-y).reverse().join(' ');
	print(ans);
}

// https://codeforces.com/contest/1312/problem/B

exports.solveProblem = (lineList) => {
  const caseList = [];
  for (let i = 2; i < lineList.length; i += 2) {
    caseList.push(
      lineList[i]
        .split(' ')
        .map(
          v => parseInt(v.trim())
        )
    );
  }

  const result = [];
  for (let aCase of caseList) {
    // --------------------------------------------
    const n = aCase.length;
    aCase = aCase.sort((a, b) => a > b ? -1 : a < b ? 1 : 0);
    result.push(aCase.join(' '));
    // --------------------------------------------
  }

  return result.join('\n');
};

const processInput = (solveProblem) => {
  const chunkList = [];
  process.stdin.setEncoding('utf8');
  process.stdin.on('readable', () => {
    let chunk;
    while ((chunk = process.stdin.read()) !== null) {
      chunkList.push(chunk);
    }
  });
  process.stdin.on('end', () => {
    const lineList = chunkList.join('').split('\n');
    const result = solveProblem(lineList);
    process.stdout.write(result);
    process.exit(0);
  });
};
if (module === require.main) {
  processInput(exports.solveProblem);
}

const readline = require('readline');

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

let answer = "";

let lines = [];

rl.on('line', (t)=>{
    lines.push(t);
}).on('close', ()=>{
    let t = parseInt(lines[0]);
    for(let i = 0; i < t; i++)
    {
        let n = parseInt(lines[i * 2 + 1]);
        let a = lines[i * 2 + 2].split(" ").map(function (x) {
            return parseInt(x);
        });
        /*
        console.log('a: ' + a.join());
        console.log('a.sort ' + a.sort().join());
        console.log('a[0] + a[1] = ' + (a[0] + a[1]));

         */
        answer += a.sort((x,y)=>x - y).reverse().join(' ') + '\n';
    }
    console.log(answer);
});

const processData = (lines) => {
  const num = +lines[0]

  for (let j=0; j<num; j++) {
    // console.log(lines[j*2+2])
    const a = lines[j*2+2].split(' ')
    const sorted = a.map((x, i) => x).sort((a, b) => b-a)
    console.log(sorted.join(' '))
  }
}

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

const init = () => {
  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();
  });

  global.readline = () => {
    return inputString[currentLine++];
  };
};

if (typeof readline === 'undefined') {
  init();
}

const print = (...args) => {
  console.log(...args);
};

// Write your logic in main();
// let t = readline().split(' ').map(x => parseInt(x));
const main = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let a = readline().split(' ').map(x => parseInt(x));
    a.sort((a, b) => b - a);
    print(a.join(' '));
  }
};

var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
function main(raw) {
    var lines = raw.trim().split("\n").map(function (v) { return v.split(" ").map(function (u) { return parseInt(u, 10); }); });
    var _a = __read(lines.shift(), 1), t = _a[0];
    while (t > 0) {
        var _b = __read(lines.shift(), 1), n = _b[0];
        var as = lines.shift();
        // const as = Array.from({length: 100}).map(_ => Math.ceil(Math.random() * 100));
        console.log(as.sort(function (a, b) { return b - a; }).join(" "));
        t--;
    }
}
function test(as) {
    for (var i = 0; i < as.length; i++) {
        for (var j = i + 1; j < as.length; j++) {
            if (j - as[j] === i - as[i]) {
                return false;
            }
        }
    }
    return true;
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();

var t=readline();
while(t--)
{
	var n=readline();
	var arr = readline().split(" ").map(x=> parseInt(x));
	var ans=arr.sort().reverse().join(' ');
	print(ans);
}

// https://codeforces.com/contest/1312/problem/B

exports.solveProblem = (lineList) => {
  const caseList = [];
  for (let i = 2; i < lineList.length; i += 2) {
    caseList.push(
      lineList[i].split(' ').map(v => parseInt(v.trim()))
    );
  }

  const result = [];
  for (let aCase of caseList) {
    const permu = [];
    const size = aCase.length;

    for (let i = 0; i < size; i++) {
      const val = aCase[i];
      permu.push([]);
      for (var j = 0; j < size; j++) {
        permu[i][j] = j - val;
      }
    }

    const sol = [];
    const diff = [];
    const used = new Map();
    for(let j = 0; j < size; j++) {
      const val = aCase[j];
      let min = Number.MAX_VALUE;
      for (let i = 0; i < size; i++) {
        const iVal = permu[i][j];
        if (!used.has(iVal) && iVal < min) {
          min = iVal;
        }
      }
      used.set(min);
      sol[j] = val;
      diff[j] = min;
    }

    result.push(sol);
  }

  return result.join('\n');
};

const processInput = (solveProblem) => {
  const chunkList = [];
  process.stdin.setEncoding('utf8');
  process.stdin.on('readable', () => {
    let chunk;
    while ((chunk = process.stdin.read()) !== null) {
      chunkList.push(chunk);
    }
  });
  process.stdin.on('end', () => {
    const lineList = chunkList.join('').split('\n');
    const result = solveProblem(lineList);
    process.stdout.write(result);
    process.exit(0);
  });
};
if (module === require.main) {
  processInput(exports.solveProblem);
}

// https://codeforces.com/contest/1312/problem/B

exports.solveProblem = (lineList) => {
  const caseList = [];
  for (let i = 2; i < lineList.length; i += 2) {
    caseList.push(
      lineList[i].split(' ').map(v => parseInt(v.trim()))
    );
  }

  const result = [];
  for (let aCase of caseList) {
    // --------------------------------------------
    const n = aCase.length;
    aCase = aCase.sort((a, b) => a < b);
    result.push(aCase.join(' '));
    // --------------------------------------------
  }

  return result.join('\n');
};

const processInput = (solveProblem) => {
  const chunkList = [];
  process.stdin.setEncoding('utf8');
  process.stdin.on('readable', () => {
    let chunk;
    while ((chunk = process.stdin.read()) !== null) {
      chunkList.push(chunk);
    }
  });
  process.stdin.on('end', () => {
    const lineList = chunkList.join('').split('\n');
    const result = solveProblem(lineList);
    process.stdout.write(result);
    process.exit(0);
  });
};
if (module === require.main) {
  processInput(exports.solveProblem);
}

// https://codeforces.com/contest/1312/problem/B

exports.solveProblem = (lineList) => {
  const caseList = [];
  for (let i = 2; i < lineList.length; i += 2) {
    caseList.push(
      lineList[i].split(' ').map(v => parseInt(v.trim()))
    );
  }

  const result = [];
  for (let aCase of caseList) {
    const permu = [];
    const size = aCase.length;

    for (let i = 0; i < size; i++) {
      const val = aCase[i];
      permu.push([]);
      for (var j = 0; j < size; j++) {
        permu[i][j] = j - val;
      }
    }

    const sol = [];
    const diff = [];
    const used = new Map();
    for(let j = 0; j < size; j++) {
      const val = aCase[j];
      let min = Number.MAX_VALUE;
      for (let i = 0; i < size; i++) {
        const iVal = permu[i][j];
        if (!used.has(iVal) && iVal < min) {
          min = iVal;
        }
      }
      used.set(min);
      sol[j] = val;
      diff[j] = min;
    }

    result.push(sol.join(' '));
  }

  return result.join('\n');
};

const processInput = (solveProblem) => {
  const chunkList = [];
  process.stdin.setEncoding('utf8');
  process.stdin.on('readable', () => {
    let chunk;
    while ((chunk = process.stdin.read()) !== null) {
      chunkList.push(chunk);
    }
  });
  process.stdin.on('end', () => {
    const lineList = chunkList.join('').split('\n');
    const result = solveProblem(lineList);
    process.stdout.write(result);
    process.exit(0);
  });
};
if (module === require.main) {
  processInput(exports.solveProblem);
}

const readline = require('readline');

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

let answer = "";

let lines = [];

rl.on('line', (t)=>{
    lines.push(t);
}).on('close', ()=>{
    let t = parseInt(lines[0]);
    for(let i = 0; i < t; i++)
    {
        let n = parseInt(lines[i * 2 + 1]);
        let a = lines[i * 2 + 2].split(" ").map(function (x) {
            return parseInt(x);
        });
        a = a.sort().reverse();
        answer += a.join(' ') + '\n';
    }

    console.log(answer);
});

const readline = require('readline');

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

let answer = "";

let lines = [];

rl.on('line', (t)=>{
    lines.push(t);
}).on('close', ()=>{
    let t = parseInt(lines[0]);
    for(let i = 0; i < t; i++)
    {
        let n = parseInt(lines[i * 2 + 1]);
        let a = lines[i * 2 + 2].split(" ").map(function (x) {
            return parseInt(x);
        });
        answer += a.sort().reverse().join(' ') + '\n';
    }

    console.log(answer);
});

var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
function main(raw) {
    var lines = raw.trim().split("\n").map(function (v) { return v.split(" ").map(function (u) { return parseInt(u, 10); }); });
    var _a = __read(lines.shift(), 1), t = _a[0];
    while (t > 0) {
        var _b = __read(lines.shift(), 1), n = _b[0];
        var as = lines.shift();
        // const as = Array.from({length: 100}).map(_ => Math.ceil(Math.random() * 100));
        console.log(test(as.sort(function (a, b) { return b - a; })));
        t--;
    }
}
function test(as) {
    for (var i = 0; i < as.length; i++) {
        for (var j = i + 1; j < as.length; j++) {
            if (j - as[j] === i - as[i]) {
                return false;
            }
        }
    }
    return true;
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();


You are given two integers $$$n$$$ and $$$k$$$.You should create an array of $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ such that the sum $$$(a_1 + a_2 + \dots + a_n)$$$ is divisible by $$$k$$$ and maximum element in $$$a$$$ is minimum possible.What is the minimum possible maximum element in $$$a$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le k \le 10^9$$$).

For each test case, print one integer — the minimum possible maximum element in array $$$a$$$ such that the sum $$$(a_1 + \dots + a_n)$$$ is divisible by $$$k$$$.

NoteIn the first test case $$$n = 1$$$, so the array consists of one element $$$a_1$$$ and if we make $$$a_1 = 5$$$ it will be divisible by $$$k = 5$$$ and the minimum possible.In the second test case, we can create array $$$a = [1, 2, 1, 2]$$$. The sum is divisible by $$$k = 3$$$ and the maximum is equal to $$$2$$$.In the third test case, we can create array $$$a = [1, 1, 1, 1, 1, 1, 1, 1]$$$. The sum is divisible by $$$k = 8$$$ and the maximum is equal to $$$1$$$.

'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();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, k] = readline().split(' ').map(x => Number(x));

        var int = Math.floor(n + k - 1 / k)
        // console.log(Math.floor((k * int + n - 1) / n))

        console.log(Math.ceil(Math.ceil(n/k)*k/n))
        // console.log(n, k)
        // if (n < k) {
        // } else {
        //     console.log(Math.ceil(n/k))
        // }
        // console.log(answer)
        // console.log(sum2)

    })

}

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

let inputString = '';
let currentLine = 0;

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

function main() {
  const t = parseInt(readline(), 10);

  for (let i = 0; i < t; i += 1) {
    const a = readline().split(' ').map(num => parseInt(num, 10));
    const n = a[0];
    let k = a[1];

    if (n > k) {
      const div = Math.ceil(n / k);
      k *= div;
    }

    console.log(Math.ceil(k / n));
  }
}

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

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

  main();
});

function solve(len, ...params) {
    for (let i = 0; i < params.length; i++) {
      let arr = params[i].split(" ");
      let n = parseInt(arr[0]);
      let k = parseInt(arr[1]);
      if (n === 1) {
        console.log(k);
        continue;
      }
      if (k === 0) {
        console.log(0);
        continue;
      }
      if (k === 1) {
        console.log(1);
        continue;
      }
      let res = k;
      let p = 0;
      let malti = parseInt(n / k);
      while (res < n) {
        res = k * malti;
        malti += 1;
      }
      p = parseInt(res / n);
      if (res % n === 0) {
        console.log(p);
      } else {
        console.log(p + 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();
});

function solve(n, k) {
    let ans;
    if (k % n === 0) {
        ans = k / n;
    } else {
        if (n > k) {
            ans = n % k === 0 ? 1 : 2
        } else {
            let factor = Math.floor(k / n);
            while (true) {
                const quotient = Math.floor((n * factor) / k);
                factor++;
                const nextQuotient = Math.floor((factor * n) / k);
                if (nextQuotient !== quotient) {
                    ans = factor;
                    break;
                }
            }
        }
    }
    console.log(ans);
}

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
        .slice(1)
        .map(item => item.split(' ').map(n => parseInt(n)));
    const len = dataArr.length;

    for (let i = 0; i < len; i++) {
        solve(...dataArr[i]);
    }
    process.exit();
});

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 gcd(a, b) {
	if (b === 0) return a;
	return gcd(b, a % b);
}

function main() {
	let t = +readLine();
	while (t--) {
		let [a, b] = readLine().split(' ').map(Number);
		if (a > b) {
			const div = Math.ceil(a / b);
			b = b * div;
		}
		console.log(Math.ceil(b / a));
	}
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (n === k || k === 1) console.log(1);
    else if (n === 1) console.log(k);
    else {
      if (n > k) {
        if (n % k === 0) k = n;
        else k = n + (k - (n % k));
      }
      let i = Math.floor(k / n);
      let j = Math.floor(k / n) + (k % n);
      if (j === i) console.log(i);
      else console.log(i + 1);
    }
  }
};
solve();

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

const getNumberList = line => line.split(' ').map(val => Number(val))

const calculate = (n, k) => {
  let index = Math.ceil(n / k)

  const b = Math.ceil((k * index) / n)

  return b
}

let index = -1
let maxRound = 0
let round = 0

let n, k
let answer = []

readline.on('line', line => {
  if (index === -1) {
    maxRound = Number(line)
    index = 0
  } else {
    ;[n, k] = getNumberList(line)

    answer.push(calculate(n, k))

    round++
    if (round === maxRound) {
      readline.close()
      console.log(answer.join('\n'))
      return
    }
    index++
  }
})
// console.log(calculate(6, 5, [1, 2, 3, 3, 2, 1]))

'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() {
    let testCases = readline()
    while(testCases--)
        solve()
}

// function to solve problems
function solve (){
    let line = readline().split(' ')
    let n = line[0]
    let k = line[1]
    // let ans = ''
    // ------------------
    let startingDigit = 0
    let cF = Math.ceil(n/k)
    // startingDigit == 0 ? maxDigit = 1 : maxDigit = startingDigit
    // let arrayCounter = 0
    let total = cF * k
    let maxDigit = Math.ceil(total / n)
    // console.log('total = ', total)

    // while (total % k != 0) {
    //     total++
    //     // console.log('arrayCounter = ', arrayCounter)
    //     if (arrayCounter == 0)
    //         maxDigit++
    //     arrayCounter = (++arrayCounter) % n
    //     // console.log('arrayCounter After = ', (arrayCounter) % n)
    // }
    console.log(maxDigit)
}

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

let inputString = "";
let currentLine = 0;

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

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

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

function main() {
  let t = parseInt(readline());
  while (t--) {
    let [n, k] = readline()
      .split(" ")
      .map((x) => parseInt(x));
    if (k < n) {
      k = k * Math.ceil(n / k);
    }
    let res = Math.ceil(k / n);
    console.log(res);
  }
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var K = nextInt();
		var sum = Math.ceil(N / K) * K;
		var L = Math.floor(sum / N);
		var R = sum % N;
		if(R > 0){
			L++;
		}
		myout(L);
	}
}

'use-strict'

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

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const [n , k] = readLine().split(' ').map(Number);

        console.log(a(n , k));

    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function a(n, k){
    /*
    You should create an array of n positive integers a1,a2,…,an such that the sum (a1+a2+⋯+an) is divisible by k and maximum element in a is minimum possible.

    What is the minimum possible maximum element in a?
    */
    return Math.floor((Math.floor((n + k -1)/k)*k + (n - 1))/n);
}

module.exports = a;

 T=+readline();
while(T--){
    var n,k,ans=0;
    var nk =readline().split(' ').map(x=>+x);
    n=nk[0];
    k=nk[1];

    if(n%k===0){
        ans=1;
    }

    else if(k%n===0){
        ans =k/n;
    }

    else if(n>k){
        ans =2;
    }

    else {
        ans = parseInt(k/n)+1;
    }

  print(ans);
}

var t = parseInt(readline());
while(t--)
{
	var ar = readline().split(' ').map(x => +x);
	var n = ar[0];
	var k = ar[1];
	if(n>k)
	{
		k = n + (k-n%k)%k;
	}
	var ans = k/n;
	ans = Math.ceil(ans);
	print(ans);
}

'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();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, k] = readline().split(' ').map(x => Number(x));

        if (n < k) {
            console.log(Math.ceil(k/n))
        } else {
            console.log(Math.ceil(n/k))
        }
        // console.log(answer)
        // console.log(sum2)

    })

}

'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();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, k] = readline().split(' ').map(x => Number(x));
        var odd1 = n % 2
        var odd2 = k % 2
        if (k === 1) return console.log(1)
        if (n === 1) return console.log(k)
        if (n > k && odd1 === odd2 || k === 1) return console.log(1)
        if (n > k && odd1 !== odd2) return console.log(2)
        console.log(Math.floor(k / n) + (k % n === 0 ? 0 : 1))

    })

}

function gcd(a, b) {
    if (b === 0n) return a
    return gcd(b, 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++];
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, k] = readline().split(' ').map(x => Number(x));
        var odd1 = n % 2
        var odd2 = k % 2
        if(k === 1) return console.log(1)
        if(n === 1) return console.log(k)
        if(n > k && odd1 === odd2 || k === 1) return console.log(1)
        if(n > k && odd1 !== odd2) return console.log(2)
        console.log(Math.floor(k/n) +(odd1 === odd2 ? 0 : 1))

    })

}

function gcd(a, b) {
    if (b === 0n) return a
    return gcd(b, 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++];
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, k] = readline().split(' ').map(x => Number(x));
        var odd1 = n % 2
        var odd2 = k % 2
        if(n > k && odd1 === odd2 || k === 1) return console.log(1)
        if(n > k && odd1 !== odd2) return console.log(2)
        console.log(Math.floor(k/n) +(odd1 === odd2 ? 0 : 1))

    })

}

function gcd(a, b) {
    if (b === 0n) return a
    return gcd(b, 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++];
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, k] = readline().split(' ').map(x => Number(x));
        var odd1 = n % 2
        var odd2 = k % 2
        if(n > k && odd1 !== odd2) return console.log(2)
        if(n > k && odd1 === odd2) return console.log(1)
        console.log(Math.floor(k/n) +(odd1 === odd2 ? 0 : 1))

    })

}

function gcd(a, b) {
    if (b === 0n) return a
    return gcd(b, 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++];
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, k] = readline().split(' ').map(x => Number(x));
        var odd1 = n % 2
        var odd2 = k % 2
        if(n > k && odd1 !== odd2) return console.log(2)
        if(n > k && odd1 === odd2) return console.log(1)
        console.log(Math.floor(k/n) +(k % n === 0 ? 0 : 1))

    })

}

function gcd(a, b) {
    if (b === 0n) return a
    return gcd(b, a % b)
}

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

let inputString = '';
let currentLine = 0;

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

function main() {
  const t = parseInt(readline(), 10);

  for (let i = 0; i < t; i += 1) {
    const a = readline().split(' ').map(num => parseInt(num, 10));
    const n = a[0];
    let k = a[1];

    if (n <= k) {
      console.log(Math.ceil(k / n));
    } else {
      while (k < n) {
        k *= 2;
      }

      console.log(Math.ceil(k / n));
    }
  }
}

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

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

  main();
});

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

let inputString = '';
let currentLine = 0;

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

function main() {
  const t = parseInt(readline(), 10);

  for (let i = 0; i < t; i += 1) {
    const a = readline().split(' ').map(num => parseInt(num, 10));
    const n = a[0];
    const k = a[1];

    if (n >= k) {
      console.log(Math.ceil(n / k));
    } else {
      console.log(Math.ceil(k / n));
    }
  }
}

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

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

  main();
});

function solve(n, k) {
    let ans;
    if (k % n === 0) {
        ans = k / n;
    } else {
        let factor = 1;
        while (true) {
            const quotient = Math.floor((n * factor) / k);
            const nextQuotient = Math.floor((factor + 1) * n);
            if (nextQuotient !== quotient) {
                ans = factor + 1;
                break;
            }
        }
    }
    console.log(ans);
}

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
        .slice(1)
        .map(item => item.split(' ').map(n => parseInt(n)));
    const len = dataArr.length;

    for (let i = 0; i < len; i++) {
        solve(...dataArr[i]);
    }
    process.exit();
});

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 gcd(a, b) {
	if (b === 0) return a;
	return gcd(b, a % b);
}

function main() {
	let t = +readLine();
	while (t--) {
		let [a, b] = readLine().split(' ').map(Number);
		if (a > b) {
			const div = Math.ceil(a / b);
			console.log(div);
		} else {
			console.log(`${Math.floor(b / a) + (b % a)}`);
		}
	}
}

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 gcd(a, b) {
	if (b === 0) return a;
	return gcd(b, a % b);
}

function main() {
	let t = +readLine();
	while (t--) {
		const [a, b] = readLine().split(' ').map(Number);
		const min = Math.min(a, b);
		const max = Math.max(a, b);
		console.log(`${Math.floor(max / min) + (max % min)}`);
	}
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (n === k || k === 1) console.log(1);
    else if (n === 1) console.log(k);
    else {
      if (n > k) k = n + (k - (n % k));
      let i = Math.floor(k / n);
      let j = Math.floor(k / n) + (k % n);
      if (j === i) console.log(i);
      else console.log(i + 1);
    }
  }
};
solve();

 T=+readline();
while(T--){
    var n,k,ans=0;
    var nk =readline().split(' ').map(x=>+x);
    n=nk[0];
    k=nk[1];

    if(n%k===0){
        ans=1;
    }

    else if(k%n===0){
        ans =k/n;
    }

    else if(n>k){
        ans =parseInt(n/k)+1 ;
    }

    else {
        ans = parseInt(k/n)+1;
    }

  print(ans);
}


This problem is actually a subproblem of problem G from the same contest.There are $$$n$$$ candies in a candy box. The type of the $$$i$$$-th candy is $$$a_i$$$ ($$$1 \le a_i \le n$$$).You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $$$1$$$ and two candies of type $$$2$$$ is bad). It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.Your task is to find out the maximum possible size of the single gift you can prepare using the candies you have.You have to answer $$$q$$$ independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Each query is represented by two lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of candies. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the type of the $$$i$$$-th candy in the box. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.

For each query print one integer — the maximum possible size of the single gift you can compose using candies you got in this query with the restriction described in the problem statement.

NoteIn the first query, you can prepare a gift with two candies of type $$$8$$$ and one candy of type $$$5$$$, totalling to $$$3$$$ candies.Note that this is not the only possible solution — taking two candies of type $$$4$$$ and one candy of type $$$6$$$ is also valid.

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

    var q = read.number();
    var res = '';
    while (q) {
        q--;

        var n = read.number();
        var a = read.arrNumber(' ');
        var t = {};
        a.forEach(i => {
            if(t[i]) {
                t[i]++;
            }
            else {
                t[i] = 1;
            }
        });

        var unic = {};
        for(var type in t) {
            if(unic[t[type]]) {
                unic[t[type]]++;
            }
            else {
                unic[t[type]] = 1;
            }
        }

        var f = Object.keys(unic).sort((a,b) => b - a);

        var count = 0;
        var max = +f[0];

        f.forEach(key => {
            if(max === 0) {
                return;
            }
            if(max > key) {
                max = +key;
            }
            while(unic[key]) {
                if(max === 0) {
                    break;
                }
                unic[key]--;
                count += max;
                max--;
            }
        });
        res += count + '\n';
    }
    print(res);
}());

var interationsCount = parseInt(readline());
for (var i = 0; i < interationsCount; i++) {
    readline();
    var candies = readline().split(" ").map(x => parseInt(x));

    var groupedCandies = groupByCount(candies);

    var numberOfCandies = 0;
    var maxCandies = groupedCandies[0][1];
    for (j = 0; j < groupedCandies.length - 1; j++) {
        if (maxCandies <= 0) {
            break;
        }

        numberOfCandies += maxCandies;
        maxCandies = Math.min(maxCandies - 1, groupedCandies[j + 1][1]);
    }

    numberOfCandies += maxCandies;

    print(numberOfCandies);
}

function groupByCount(candies) {
    var map = new Map();
    for (var j = 0; j < candies.length; j++) {
        var currentTypeCount = map.get(candies[j]);
        if (!currentTypeCount) {
            map.set(candies[j], 1);
        } else {
            map.set(candies[j], currentTypeCount + 1)
        }
    }

    return Array.from(map).sort((a, b) => {
        return b[1] - a[1];
    });
}

"use strict";

var q = +readline()

while (q--) {
    var n = +readline();
    var A = readline().split(' ').map(value => +value);
    var M = {};

    for (var i = 0; i < A.length; ++i) {
        var value = A[i];
        M[value] = (M[value] || 0) + 1;
    }

    var R = {};
    for (var key in M) {
        if (M.hasOwnProperty(key)) {
            var value = M[key];
            R[value] = (R[value] || 0) + 1;
        }
    }

    var L = Object.keys(R).map(value => +value).sort(function(a, b){return b - a});
    var result = 0;
    var lastMax = L[0];
    loop:for (var i = 0; i < L.length; ++i) {
        if (lastMax > L[i]) {
            lastMax = L[i];
        }
        var count = +R[L[i]];

        while (count--) {
            result += lastMax;
            lastMax--;
            if (lastMax === 0) {
                break loop;
            }
        }
    }

    write(result, '\n');
}

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

    var q = read.number();
    var res = '';
    while (q) {
        q--;

        var n = read.number();
        var a = read.arrNumber(' ');
        var t = {};
        a.forEach(i => {
            if(t[i]) {
                t[i]++;
            }
            else {
                t[i] = 1;
            }
        });

        var unic = {};
        for(var type in t) {
            if(unic[t[type]]) {
                unic[t[type]]++;
            }
            else {
                unic[t[type]] = 1;
            }
        }

        var f = Object.keys(unic).sort((a,b) => b - a);

        var count = 0;
        var max = +f[0];

        f.forEach(key => {
            if(max === 0) {
                return;
            }
            if(max > key) {
                max = +key;
            }
            while(unic[key]) {
                unic[key]--;
                count += max;
                max--;
            }
        });

        res += count + '\n';

    }
    print(res);

}());

var interationsCount = parseInt(readline());
for (var i = 0; i < interationsCount; i++) {
    var candiesCount = parseInt(readline());
    var candies = readline().split(" ").map(x => parseInt(x));

    var groupedCandies = groupByCount(candies);
    var maxNumberOfTypesInPresent = Math.min(groupedCandies.length, groupedCandies[0][1]);

    var numberOfCandies = 0;
    var previousNumber = -1;
    for (j = 0; j < maxNumberOfTypesInPresent; j++) {
        var currentTypeCandiesMax = groupedCandies[j][1];
        numberOfCandies += groupedCandies[j][1];

        if (previousNumber != -1) {
            if (previousNumber === currentTypeCandiesMax) {
                numberOfCandies -= j;
            }
        }

        previousNumber = currentTypeCandiesMax;
    }

    print(numberOfCandies);
}

function groupByCount(candies) {
    var map = new Map();
    for (var j = 0; j < candies.length; j++) {
        var currentTypeCount = map.get(candies[j]);
        if (!currentTypeCount) {
            map.set(candies[j], 1);
        } else {
            map.set(candies[j], currentTypeCount + 1)
        }
    }

    return Array.from(map).sort((a, b) => {
        return b[1] - a[1];
    });
}

var interationsCount = parseInt(readline());
for (var i = 0; i < interationsCount; i++) {
    var candiesCount = parseInt(readline());
    var candies = readline().split(" ").map(x => parseInt(x));

    var groupedCandies = groupByCount(candies);
    var maxNumberOfTypesInPresent = Math.min(groupedCandies.length, groupedCandies[0][1]);

    var numberOfCandies = 0;
    var maxCandies = groupedCandies[0][1];
    for (j = 0; j < maxNumberOfTypesInPresent - 1; j++) {
        numberOfCandies += maxCandies;
        maxCandies = Math.min(maxCandies - 1, groupedCandies[j+1][1]);
    }
    numberOfCandies += maxCandies;

    print(numberOfCandies);
}

function groupByCount(candies) {
    var map = new Map();
    for (var j = 0; j < candies.length; j++) {
        var currentTypeCount = map.get(candies[j]);
        if (!currentTypeCount) {
            map.set(candies[j], 1);
        } else {
            map.set(candies[j], currentTypeCount + 1)
        }
    }

    return Array.from(map).sort((a, b) => {
        return b[1] - a[1];
    });
}