You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases — two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) — the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.

NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.

T=+readline()
function gcd(a,b){
    if (!b)
        return a;
    return gcd(b,a%b)
}
for (t=0;t<T;t++){
    s=readline().split(' ')
    n=+s[0]
    x=+s[1]
    s=readline()
    q=0
    for (i=0;i<=n;i++){
        if (i){
            if (s[i-1]=='1')
                --q
            else
                ++q
        }
    }
    bal=0
    ans=0
    for (i=0;i<n;i++){
        if (i){
            if (s[i-1]=='1')
                --bal
            else
                ++bal
        }
        if (q==0&&bal==x){
            ans=-1;
            break;
        }
        if ((x-bal)%q==0){
            if ((x-bal)/q>=0){
                ++ans
            }
        }
    }
    print(ans)
}

'use strict'

const problem = (n, x, s) => {
    let r = +!x, y = 0
    const t = s.reduce((a, b) => a + b, 0)
    for (let i = 0; i < n; i++) {
        y += s[i];
        if (y === x) {
            if (!t) return -1
            r += 1
        } else if ((x - y) * t > 0 && (x - y) % t === 0) r += 1
    }
    return r
}

let t = +readline()
while(t--) {
    const nx = readline().split(' ').map(i => +i);
    const s = readline().split('').map(i => i === '0' ? 1 : -1);
    print(problem(nx[0], nx[1], s));
}

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

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

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

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

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

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

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

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

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

function main() {
  let t = readInt()
  while(t--) {
    const [n, x] = readInts()
    const s = readString()
    let c0 = 0, c1 = 0
    let count = x === 0 ? 1 : 0
    for(let i = 0; i < n; i++) {
      if(s[i] === '0') c0++
      else c1++
    }
    let b = c0 - c1
    let r = 0
    if(b === 0) {
      let f = false
      for(let i = 0; i < n; i++) {
        if(s[i] === '0') r++
        else r--
        if(r === x){
          wr(-1)
          f = true
          break
        }
      }
      if(!f) wr(0)
    }
    else {
      r = 0
      for(let i = 0; i < n; i++) {
        if(s[i] === '0') r++
        else r--
        if((x - r) % b === 0 && (x - r) / b >= 0) {
          count++
        }
      }
      wr(count)
    }
  }
}

'use strict'

const problem = (n, x, s) => {
    s = s.map(i => i === '1' ? -1 : 1);
    let r = {}, p = 0;
    for (let i = 0; i < n; i++) { p += s[i]; if (r[p]) r[p]++; else r[p] = 1 }
    let max = -1, min = 1
    Object.keys(r).forEach(i => {
        if (i < min) min = i;
        if (i > max) max = i;
    })

    if (p > 0 && x < min) return +!x;
    if (p < 0 && x > max) return 0;
    if (p === 0) if (x >= min && x <= max) return -1; else return 0;

    const a = Math.ceil((x - max-1)/p);
    const b = Math.ceil((x - min-1)/p);

    let res = 0;
    for (let i = a - 1; i <= b + 1; i++) {
        res += r[x - i*p] || 0;
    }
    return res;
}
let t = +readline()
while(t--) {
    const nx = readline().split(' ').map(i => +i);
    print(problem(nx[0], nx[1], readline().split('')));
}

'use strict'

const problem = (n, x, s) => {
    s = s.map(i => i === '1' ? -1 : 1);
    let r = {}, p = 0;
    for (let i = 0; i < n; i++) { p += s[i]; if (r[p]) r[p]++; else r[p] = 1 }
    let max = -1, min = 1
    Object.keys(r).forEach(i => {
        if (i < min) min = i;
        if (i > max) max = i;
    })

    if (p > 0 && x < min) return +!x;
    if (p < 0 && x > max) return 0;
    if (p === 0) if (x >= min && x <= max) return -1; else return 0;

    const a = Math.ceil((x - max-1)/p);
    const b = Math.ceil((x - min-1)/p);

    let res = 0;
    for (let i = a; i <= b; i++) {
        res += r[x - i*p];
    }
    return res;
}
let t = +readline()
while(t--) {
    const nx = readline().split(' ').map(i => +i);
    print(problem(nx[0], nx[1], readline().split('')));
}

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

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

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

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

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

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let i = 0
  let t = readInt(input, i++)
  while(t--) {
    let [n, x] = readInts(input, i++)
    const s = input[i++]
    const len = s.length
    let c0 = 0, c1 = 0
    for (let j = 0; j < len; j++) {
      if(s[j] == '0') c0++
      else c1++
    }

    if(c0 > c1 && x < 0) wr('0')
    else if(c0 < c1 && x > 0) wr('0')
    else if(c0 === c1 && x !== 0) wr('0')
    else if(c0 === c1 && x === 0) wr(-1)
    else if((c0 === 0 || c1 === 0) && x !== 0) wr(-1)
    else {
      // wr('j')
      let count = 0
      if(x < 0) {
        x = -x
        let t = c0
        c0 = c1
        c1 = t
      }
      let r = x % (c0 - c1)
      let qu = Math.floor(x / (c0 - c1))
      let cc1 = qu * c1
      let cc0 = qu * c0
      let k = 0
      if(cc0 - cc1 === x) count ++
      while(k < len) {
        // console.log("c", count, cc0, cc1)
        if(s[k] == '0') cc0++
        else cc1++
        if(cc0 - cc1 === x) count ++
        k++
      }
      k = len - 1
      cc1 = qu * c1
      cc0 = qu * c0
      while(k >= 0) {
        // console.log("c", count, cc0, cc1)
        if(s[k] == '0') cc0--
        else cc1--
        if(cc0 - cc1 === x) count ++
        k--
      }
      wr(count)

    }
  }
}

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

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

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

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

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

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

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

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

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

function main() {
  let t = readInt()
  while(t--) {
    const [n, x] = readInts()
    const s = readString()
    let c0 = 0, c1 = 0
    let count = x === 0 ? 1 : 0
    for(let i = 0; i < n; i++) {
      if(s[i] === '0') c0++
      else c1++
    }
    let b = c0 - c1
    let r = 0
    if(b === 0) {
      let f = false
      for(let i = 0; i < n; i++) {
        if(s[i] === '0') r++
        else r--
        if(r === x){
          wr(-1)
          f = true
          break
        }
      }
      if(!f) wr(0)
    }
    else {
      r = 0
      for(let i = 0; i < n; i++) {
        if(s[i] === '0') r++
        else r--
        if((x - r) % b === 0 && (x - r) / b > 0) {
          count++
        }
      }
      wr(count)
    }
  }
}

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

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

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

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

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

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let i = 0
  let t = readInt(input, i++)
  while(t--) {
    let [n, x] = readInts(input, i++)
    let s = input[i++]
    const len = s.length
    let c0 = 0, c1 = 0
    for (let j = 0; j < len; j++) {
      if(s[j] == '0') c0++
      else c1++
    }

    if(c0 > c1 && x < 0) wr('0')
    else if(c0 < c1 && x > 0) wr('0')
    else if(c0 === c1 && x !== 0) wr('0')
    else if(c0 === c1 && x === 0) wr(-1)
    else if((c0 === 0 || c1 === 0) && x !== 0) wr(0)
    else {
      // wr('j')
      let count = 0
      if(x < 0) {
        x = -x
        let t = c0
        c0 = c1
        c1 = t
        let s2 = []
        for (let j = 0; j < len; j++) {
          if(s[j] == '0') s2.push('1')
          else s2.push('0')
        }
        s = s2.join('')
      }
      let r = x % (c0 - c1)
      let qu = Math.floor(x / (c0 - c1))
      let cc1 = qu * c1
      let cc0 = qu * c0
      let k = 0
      if(cc0 - cc1 === x) count ++
      while(k < len) {
        // console.log("c", count, cc0, cc1, s)
        if(s[k] == '0') cc0++
        else cc1++
        if(cc0 - cc1 === x) count ++
        k++
      }
      k = len - 1
      cc1 = qu * c1
      cc0 = qu * c0
      while(k >= 0) {
        // console.log("c", count, cc0, cc1)
        if(s[k] == '0') cc0--
        else cc1--
        if(cc0 - cc1 === x) count ++
        k--
      }
      wr(count)

    }
  }
}


Monocarp is a tutor of a group of $$$n$$$ students. He communicates with them using a conference in a popular messenger.Today was a busy day for Monocarp — he was asked to forward a lot of posts and announcements to his group, that's why he had to write a very large number of messages in the conference. Monocarp knows the students in the group he is tutoring quite well, so he understands which message should each student read: Monocarp wants the student $$$i$$$ to read the message $$$m_i$$$.Of course, no one's going to read all the messages in the conference. That's why Monocarp decided to pin some of them. Monocarp can pin any number of messages, and if he wants anyone to read some message, he should pin it — otherwise it will definitely be skipped by everyone.Unfortunately, even if a message is pinned, some students may skip it anyway. For each student $$$i$$$, Monocarp knows that they will read at most $$$k_i$$$ messages. Suppose Monocarp pins $$$t$$$ messages; if $$$t \le k_i$$$, then the $$$i$$$-th student will read all the pinned messages; but if $$$t > k_i$$$, the $$$i$$$-th student will choose exactly $$$k_i$$$ random pinned messages (all possible subsets of pinned messages of size $$$k_i$$$ are equiprobable) and read only the chosen messages.Monocarp wants to maximize the expected number of students that read their respective messages (i.e. the number of such indices $$$i$$$ that student $$$i$$$ reads the message $$$m_i$$$). Help him to choose how many (and which) messages should he pin!

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of students in the conference. Then $$$n$$$ lines follow. The $$$i$$$-th line contains two integers $$$m_i$$$ and $$$k_i$$$ ($$$1 \le m_i \le 2 \cdot 10^5$$$; $$$1 \le k_i \le 20$$$) — the index of the message which Monocarp wants the $$$i$$$-th student to read and the maximum number of messages the $$$i$$$-th student will read, respectively.

In the first line, print one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of messages Monocarp should pin. In the second line, print $$$t$$$ distinct integers $$$c_1$$$, $$$c_2$$$, ..., $$$c_t$$$ ($$$1 \le c_i \le 2 \cdot 10^5$$$) — the indices of the messages Monocarp should pin. The messages can be listed in any order. If there are multiple answers, print any of them.

NoteLet's consider the examples from the statement. In the first example, Monocarp pins the messages $$$5$$$ and $$$10$$$.  if the first student reads the message $$$5$$$, the second student reads the messages $$$5$$$ and $$$10$$$, and the third student reads the messages $$$5$$$ and $$$10$$$, the number of students which have read their respective messages will be $$$2$$$;  if the first student reads the message $$$10$$$, the second student reads the messages $$$5$$$ and $$$10$$$, and the third student reads the messages $$$5$$$ and $$$10$$$, the number of students which have read their respective messages will be $$$3$$$. So, the expected number of students which will read their respective messages is $$$\frac{5}{2}$$$. In the second example, Monocarp pins the message $$$10$$$.  if the first student reads the message $$$10$$$, the second student reads the message $$$10$$$, and the third student reads the message $$$10$$$, the number of students which have read their respective messages will be $$$2$$$. So, the expected number of students which will read their respective messages is $$$2$$$. If Monocarp had pinned both messages $$$5$$$ and $$$10$$$, the expected number of students which read their respective messages would have been $$$2$$$ as well. In the third example, the expected number of students which will read their respective messages is $$$\frac{8}{3}$$$. In the fourth example, the expected number of students which will read their respective messages is $$$2$$$.

const readline = require('readline')

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

function solve(n, arr) {
    const map = {}
    arr.forEach(([m, k]) => {
        map[m] = map[m] || []
        map[m].push(k)
    })
    for (let m in map) {
        map[m].sort((a, b) => a - b)
    }
    const ms = Object.keys(map)
    const limit = Math.min(ms.length, 20)

    let max = 0
    let ans
    for (let i = 1; i <= limit; i++) {
        const sorted = ms.map(m => ({
            m,
            e: map[m].reduce((s, k) => s + Math.min(k, i) / i, 0),
        })).sort((a, b) => b.e - a.e)

        let now = 0
        const selected = []
        for (let j = 0; j < i; j++) {
            now += sorted[j].e
            selected.push(sorted[j].m)
        }
        if (now > max) {
            max = now
            ans = selected
        }
    }
    return ans.length + '\n' + ans.join(' ')
}


There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed.

The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j.

Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added.

NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42.

var beaconsAmount = readline();
var beaconsPowers = [];
for (var i = 0; i < beaconsAmount; i++) {
	var positionAndPower = readline().split(' ');
	beaconsPowers[positionAndPower[0]] = positionAndPower[1];
}

var minimumDestroyedBeacons = findMinimumDestroyedBeacons(beaconsAmount, beaconsPowers);

print(minimumDestroyedBeacons);

function findMinimumDestroyedBeacons(beaconsAmount, beaconsPowers) {
	var minimumDestroyedBeacons = beaconsAmount;

	var destroyedBeaconsToLeft = [];
	var destroyedBeaconsToRight = [];

	var remainingBeacons = beaconsAmount;
	for (i = 0; i < beaconsPowers.length; i++) {

		if (beaconsPowers[i] === undefined) {
			if (i === 0) {
				destroyedBeaconsToRight[i] = beaconsAmount;
				destroyedBeaconsToLeft[i] = 0;
			}
			else {
				destroyedBeaconsToRight[i] = destroyedBeaconsToRight[i - 1];
				destroyedBeaconsToLeft[i] = destroyedBeaconsToLeft[i - 1];
			}
		}

		if (beaconsPowers[i] !== undefined) {
			remainingBeacons--;
			destroyedBeaconsToRight[i] = remainingBeacons;

			var toLeft, toRight;
			if (i - beaconsPowers[i] - 1 < 0) {
				toLeft = 0;
				toRight = beaconsAmount;
			}
			else {
				toLeft = destroyedBeaconsToLeft[i - beaconsPowers[i] - 1];
				toRight = destroyedBeaconsToRight[i - beaconsPowers[i] - 1];
			}

			destroyedBeaconsToLeft[i] = toLeft + toRight - destroyedBeaconsToRight[i] - 1;
		}

		if (minimumDestroyedBeacons > destroyedBeaconsToLeft[i] + destroyedBeaconsToRight[i]) {
			minimumDestroyedBeacons = destroyedBeaconsToLeft[i] + destroyedBeaconsToRight[i];
		}
	}

	return minimumDestroyedBeacons;
}


Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that:   r ≥ 2;  for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds;  each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled:   no pair of tubes has common cells;  each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.

The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.

Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.

NotePicture for the first sample:   Picture for the second sample:

var nextToken = new function() {
    var line = [];
    var lineIndex = 0;

    return function() {
        while (lineIndex >= line.length) {
            line = readline().split(/\s+/);
            lineIndex = 0;
        }

        return line[lineIndex++];
    }
}();

var nextInt = function() {
    return parseInt(nextToken(), 10);
};

var createMatrix = function (n, m, e) {
    var i, j;
    var a = [], b;

    for (i = 0; i < n; ++i) {
        b = [];
        for (j = 0; j < m; ++j) {
            b.push(e);
        }
        a.push(b);
    }

    return a;
}

var dx = [0, 1,  0, -1];
var dy = [1, 0, -1,  0];

var fill = function(n, m, a, x, y, e, cnt) {
   var i, dir, nx, ny, good;
   var result = [];
   for (i = 0; i < cnt; ++i) {
       a[x][y] = e;
       result.push(x + 1);
       result.push(y + 1);

       if (i + 1 < cnt) {
           good = false;
           for (dir = 0; dir < 4; ++dir) {
               nx = x + dx[dir];
               ny = y + dy[dir];

               if (0 <= nx && nx < n && 0 <= ny && ny < m && a[nx][ny] == -1) {
                   x = nx;
                   y = ny;
                   good = true;
                   break;
               }
           }

           if (!good) {
               throw "FAIL!";
           }
       }
   }
   return result;
}

var main = function () {
    var n = nextInt();
    var m = nextInt();
    var a = createMatrix(n, m, -1);

    var go = fill(n, m, createMatrix(n, m, -1), 0, 0, 0, n * m);
    var cnt = nextInt();
    var left = n * m;

    var x, y, cur, i;
    for (i = 0; i < go.length; i += 2) {
        x = go[i] - 1;
        y = go[i + 1] - 1;
        //print(x + ", " + y);
        if (a[x][y] === -1) {
            if (cnt == 1) {
                cur = fill(n, m, a, x, y, cnt, left);
            } else {
                cur = fill(n, m, a, x, y, cnt, 2);
                left -= 2;
                cnt--;
            }
            print((cur.length / 2) + " " + cur.join(" "));
        }
    }

};

main();

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

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

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

function main() {
	var data = tokenizeIntegers(readline()),
		rNum = data[0], cNum = data[1], snakeNum = data[2],
		cells = rNum*cNum, snakeLen = Math.floor(cells/snakeNum),
		result = [], r = 0, c = -1, dir = +1;
	for (var i = 0; i < snakeNum; ++i) {
		var len = (i == snakeNum-1 ? cells : snakeLen),
			snake = new Array(2*len+1);
		snake[0] = len;
		cells -= len;
		for (var j = 0; j < len; ++j) {
			if (dir == +1) {
				if (c == cNum-1) {
					++r;
					dir = -1;
				} else {
					c += 1;
				}
			} else {
				if (c == 0) {
					++r;
					dir = +1;
				} else {
					c -= 1;
				}
			}
			snake[2*j+1] = r+1;
			snake[2*j+2] = c+1;
		}
		result.push(snake.join(' '));
	}
	print(result.join('\n'));
}

main();

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

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

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

function main() {
	var data = tokenizeIntegers(readline()),
		rNum = data[0], cNum = data[1], snakeNum = data[2],
		cells = rNum*cNum, snakeLen = Math.ceil(cells/snakeNum),
		result = [], r = 0, c = -1, dir = +1;
	for (var i = 0; i < snakeNum; ++i) {
		var len = Math.min(snakeLen, cells),
			snake = new Array(2*len+1);
		snake[0] = len;
		cells -= len;
		for (var j = 0; j < len; ++j) {
			if (dir == +1) {
				if (c == cNum-1) {
					++r;
					dir = -1;
				} else {
					c += 1;
				}
			} else {
				if (c == 0) {
					++r;
					dir = +1;
				} else {
					c -= 1;
				}
			}
			snake[2*j+1] = r+1;
			snake[2*j+2] = c+1;
		}
		result.push(snake.join(' '));
	}
	print(result.join('\n'));
}

main();


You are given a non-empty string s consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.In a more formal way, you have to find the quantity of tuples (a, b, x, y) such that 1 ≤ a ≤ b < x ≤ y ≤ |s| and substrings s[a... b], s[x... y] are palindromes.A palindrome is a string that can be read the same way from left to right and from right to left. For example, "abacaba", "z", "abba" are palindromes.A substring s[i... j] (1 ≤ i ≤ j ≤ |s|) of string s = s1s2... s|s| is a string sisi + 1... sj. For example, substring s[2...4] of string s = "abacaba" equals "bac".

The first line of input contains a non-empty string s which consists of lowercase letters ('a'...'z'), s contains at most 2000 characters.

Output a single number — the quantity of pairs of non-overlapping palindromic substrings of s. Please do not use the %lld format specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d format specifier.

print(function(s) {
	var i, j,
		l = s.length,
		isP = [];

	for (i = 0; i < l; i++)
		isP[i] = new Int8Array(l);

	isP[0][0] = 1;

	for (i = l; i >= 0; i--)
		for (j = i; j < l; j++)
			if (s[i] === s[j])
				isP[i][j] = j - i > 1 ? isP[i + 1][j - 1] : 1;
			else
				isP[i][j] = 0;

	var sum = [1];
	for (j = 1; j < l; j++) {
		sum[j] = sum[j - 1];
		for (i = 0; i <= j; i++)
			sum[j] += isP[i][j];
	}

	var ans = 0;
	for (j = 1; j < l; j++)
		for (i = 1; i <= j; i++)
			if (isP[i][j] === 1)
				ans += sum[i - 1];

	return ans;
}(readline()));


You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.You are playing the game on the new generation console so your gamepad have $$$26$$$ buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.You are given a sequence of hits, the $$$i$$$-th hit deals $$$a_i$$$ units of damage to the opponent's character. To perform the $$$i$$$-th hit you have to press the button $$$s_i$$$ on your gamepad. Hits are numbered from $$$1$$$ to $$$n$$$.You know that if you press some button more than $$$k$$$ times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons.To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of $$$a_i$$$ over all $$$i$$$ for the hits which weren't skipped.Note that if you skip the hit then the counter of consecutive presses the button won't reset.Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the number of hits and the maximum number of times you can push the same button in a row. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the damage of the $$$i$$$-th hit. The third line of the input contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters — the sequence of hits (each character is the letter on the button you need to press to perform the corresponding hit).

Print one integer $$$dmg$$$ — the maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons.

NoteIn the first example you can choose hits with numbers $$$[1, 3, 4, 5, 6, 7]$$$ with the total damage $$$1 + 16 + 18 + 7 + 2 + 10 = 54$$$.In the second example you can choose all hits so the total damage is $$$2 + 4 + 1 + 3 + 1000 = 1010$$$.In the third example you can choose all hits expect the third one so the total damage is $$$2 + 4 + 3 + 1000 = 1009$$$.In the fourth example you can choose hits with numbers $$$[2, 3, 6, 8]$$$. Only this way you can reach the maximum total damage $$$15 + 2 + 8 + 16 = 41$$$.In the fifth example you can choose only hits with numbers $$$[2, 4, 6]$$$ with the total damage $$$18 + 19 + 15 = 52$$$.In the sixth example you can change either first hit or the second hit (it does not matter) with the total damage $$$10$$$.

(function() {
    var t = readline().split(' ');
    var n = +t[0];
    var q = +t[1];
    var u = readline().split(' ');
    var b = readline().split('');

    var bs = [];
    var bsi = -1;

    var dmg = 0;

    var lastb = '';
    for(var i = 0; i < n; i++) {
        if(lastb === b[i]) {
            bs[bsi].push(+u[i]);
        }
        else {
            bsi++;
            bs[bsi] = [+u[i]];
        }
        lastb = b[i];
    }

    for(var j = 0; j< bs.length; j++) {
        var g = bs[j];
        if(g.length <= q) {
            for(var i = 0; i < g.length; i++) {
                dmg += g[i];
            }
        }
        else {
            g.sort((a,b) => b - a);
            for(var i = 0; i < q; i++) {
                dmg += g[i];
            }
        }
    }
    print(dmg);
}());

var qq = readline().split(" ").map(function(x) { return parseInt(x); });
//var numbers = prompt("Enter data: ").split(" ").map(function(x) { return parseInt(x); });   // Chrome run

var N = qq[0];
var K = qq[1];

var uron = readline().split(" ").map(function(x) { return parseInt(x); });
var st = readline();

var p_sum = Array(N).fill(0);
p_sum[0] = uron[0];
for (var i=1; i<N; i++) p_sum[i] = p_sum[i-1] + uron[i];

function get_sum(i, j) {
	if (i <= 0)
		return p_sum[j];
	return p_sum[j] - p_sum[i-1];
}

var k = 0, glob = 0;

do {
	var bg = k;
	while (k+1<N && st[k]===st[k+1]) k++;
	var en = k;
	k++;

	var mx = 0;
	if (en-bg+1 <= K)
		mx = get_sum(bg, en);
	else {
		var ww = [];
		for (var pp=bg; pp<=en; pp++) ww.push(uron[pp]);
		ww.sort(function(a,b) {return a-b;});
		for (var pp=ww.length-1; pp>=ww.length-K; pp--) mx += ww[pp];
	}

	glob += mx;
} while (k < N);

write(glob);

(function() {
    var t = readline().split(' ');
    var n = +t[0];
    var q = +t[1];
    var u = readline().split(' ');
    var b = readline().split('');

    var bs = {};
    var dmg = 0;

    for(var i = 0; i < n; i++) {
        if(bs[b[i]]) {
            bs[b[i]].push(+u[i]);
        }
        else {
            bs[b[i]] = [+u[i]];
        }
    }

    for(var bi in bs) {
        var g = bs[bi];

        if(g.length <= q) {
            for(var i = 0; i < g.length; i++) {
                dmg += g[i];
            }
        }
        else {
            g = g.sort(function(a, b) {
                return b - a;
            });
            print(g);
            for(var i = 0; i < q; i++) {
                dmg += g[i];
            }
        }
    }
    print(dmg);
}());

(function() {
    var t = readline().split(' ');
    var n = +t[0];
    var q = +t[1];
    var u = readline().split(' ');
    var b = readline().split('');

    var bs = {};
    var dmg = 0;

    for(var i = 0; i < n; i++) {
        if(bs[b[i]]) {
            bs[b[i]].push(+u[i]);
        }
        else {
            bs[b[i]] = [+u[i]];
        }
    }

    for(var bi in bs) {
        var g = bs[bi];

        if(g.length <= q) {
            for(var i = 0; i < g.length; i++) {
                dmg += g[i];
            }
        }
        else {
            g = g.sort(function(a, b) {
                return b - a;
            });
            for(var i = 0; i < q; i++) {
                dmg += g[i];
            }
        }
    }
    print(dmg);
}());


You are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and q.For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".Note it is allowed to split the string s to the strings only of length p or to the strings only of length q (see the second sample test).

The first line contains three positive integers n, p, q (1 ≤ p, q ≤ n ≤ 100). The second line contains the string s consists of lowercase and uppercase latin letters and digits.

If it's impossible to split the string s to the strings of length p and q print the only number "-1". Otherwise in the first line print integer k — the number of strings in partition of s. Each of the next k lines should contain the strings in partition. Each string should be of the length p or q. The string should be in order of their appearing in string s — from left to right. If there are several solutions print any of them.

function resolve(s, p, q) {
  var res = [];
  var k = 1;
  // case 1
  while (k <= s.length / p) {
    var r = (s.length - k * p) % q;
    if (r === 0) {
      var i = 1;
      while (i <= k) {
        res.push(s.substring((i - 1) * p, i * p));
        i++;
      }
      i = 1;
      while (i <= (s.length - k * p) / q) {
        res.push(s.substr(k * p + (i - 1) * q, q));
        i++;
      }
      return res;
    }
    k++;
  }

  // case 2
  k = 1;
  while (k <= s.length / q) {
    var r = (s.length - k * q) % p;
    if (r === 0) {
      var i = 1;
      while (i <= k) {
        res.push(s.substring((i - 1) * q, i * q));
        i++;
      }
      i = 1;
      while (i <= (s.length - k * q) / p) {
        res.push(s.substr(k * q + (i - 1) * p, p));
        i++;
      }
      return res;
    }
    k++;
  }
  return -1;
}

/*console.log(
  resolve('XCgVJUu4aMQ7HMxZjNxe3XARNiahK303g9y7NV8oN6tWdyXrlu', 16, 3)
);*/

const z = readline().split(' ');
const s = readline();
const res = resolve(s, parseInt(z[1], 10), parseInt(z[2], 10));
if (res === -1) {
  print(res);
} else {
  print(res.length);
  for (var i = 0; i < res.length; i++) {
    print(res[i]);
  }
}

function main() {

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

    var n = arr[0],
        p = arr[1],
        q = arr[2];

    var str = readline();

    var flag=false;

    for (var i = 0; i <= n; i++) {
        for (var j = 0; j <= n; j++) {
            if ((i * p + j * q) == n) {
                print(i+j);
                var m;
                for(m=0;m<i;m++){
                    print(str.slice(p*m,p*(m+1)));
                }
                for(var n=0;n<j;n++){
                    print(str.slice(q*n+p*m,q*(n+1)+p*m));
                }
                flag=true;
                return;
            }
        }
    }

    if(flag==false){
        print(-1);
    }

}

main();

!function(r){function __webpack_require__(t){if(e[t])return e[t].exports;var n=e[t]={exports:{},id:t,loaded:!1};return r[t].call(n.exports,n,n.exports,__webpack_require__),n.loaded=!0,n.exports}var e={};return __webpack_require__.m=r,__webpack_require__.c=e,__webpack_require__.p="",__webpack_require__(0)}([function(r,e,t){r.exports=t(1)},function(r,e){"use strict";function solve(r,e,n,i){function calculate(r,e,t){for(var n=0;r>=n;n++){if(e*n>r)return[-1,0];var i=Math.floor((r-e*n)/t);if(n*e+i*t===r)return[n,i]}return[-1,0]}function resout(r,e,t,n,i){if(print(n+i),-1!==n){for(var u=0;n>u;u++)print(r.substr(0,e)),r=r.substr(e);for(var u=0;i>u;u++)print(r.substr(0,t)),r=r.substr(t)}}var u=calculate(r,e,n),a=t(u,2),o=a[0],c=a[1];resout(i,e,n,o,c)}var t=function(){function sliceIterator(r,e){var t=[],n=!0,i=!1,u=void 0;try{for(var a,o=r[Symbol.iterator]();!(n=(a=o.next()).done)&&(t.push(a.value),!e||t.length!==e);n=!0);}catch(c){i=!0,u=c}finally{try{!n&&o.return&&o.return()}finally{if(i)throw u}}return t}return function(r,e){if(Array.isArray(r))return r;if(Symbol.iterator in Object(r))return sliceIterator(r,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),n=readline().split(" ").map(function(r){return parseInt(r)}),i=t(n,3),u=i[0],a=i[1],o=i[2],c=readline();solve(u,a,o,c)}]);

var npq = readline().split(' ').map(Number);
var n = npq[0];
var p = npq[1];
var q = npq[2];
var s = readline();
var k = -1;
var np = 0;
var nq = 0;
if (n%p == 0) {
	k = n/p;
	np = k;
} else if (n%q == 0){
	k = n/q;
	nq = k;
} else {
		for (var i=1; i<n/p; i++)	{
			if ( (n-i*p)%q == 0) {
				np = i;
				nq = (n-i*p)/q;
				k = np + nq;
				break;
			}
	}
}
print(k);
if (k != -1) {
	for (var i=0; i<np; i++) {
		print(s.substr(i*p, p));
	}
	for (var i=0; i<nq; i++) {
		print(s.substr(p*np+i*q, q));
	}
}

var input = readline().split(" ").map(i => +i);
var n = input[0];
var p = input[1];
var q = input[2];
var s = readline();

var pCount = 0;
var qCount = 0;
var maxQCount = Math.floor(n/q);
var noCombination = true;
for (; qCount <= maxQCount; ++qCount) {
    if ((n - qCount*q)%p === 0) {
        pCount = (n - qCount*q) / p;
        noCombination = false;
        break;
    }
}
if (noCombination) {
    print(-1);
} else {
    var output = pCount + qCount + "\n";
    for (var i = 0; i < pCount; ++i) {
        for (var j = 0; j < p; ++j) {
            output += s.charAt(j+p*i);
        }
        output += "\n";
    }
    for (var i = 0; i < qCount; ++i) {
        for (var j = 0; j < q; ++j) {
            output += s.charAt(j+q*i+p*pCount);
        }
        output += "\n";
    }
    print(output);
}

// https://codeforces.com/contest/612/problem/A

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

const getXY = (n, p, q) => {
  const isFit = (m, r) => (m % r) === 0;
  const nFits = (m, r) => Math.floor(m / r);
  const getFits = (m, a, b) => {
    for (let aX = nFits(m, a); aX > -1; aX--) {
      const mN = m - (a * aX);
      if (isFit(mN, b)) {
        return [aX, nFits(mN, b)];
      }
    }
    return [0, 0];
  };

  let x, y;
  if (Math.max(p, q) === p) {
    ([x, y] = getFits(n, p, q));
  } else {
    ([y, x] = getFits(n, q, p));
  }
  return {x, y};
};

exports.solveProblem = (lineList) => {
  const [n, p, q] = lineList[0].split(' ').map((v) => parseInt(v));
  const s = lineList[1];

  let {x, y} = getXY(n, p, q);
  let idx = 0;
  const lst = [];
  for (let i = 0; i < x; i++) {
    lst.push(s.slice(idx, idx + p));
    idx += p;
  }

  for (let i = 0; i < y; i++) {
    lst.push(s.slice(idx, idx + q));
    idx += q;
  }

  if (lst.length < 1) {
    return '-1';
  }
  return `${lst.length}\n${lst.join('\n')}`;
};

if (module === require.main) {
  processInput(exports.solveProblem);
}

function resolve(s, p, q) {
  var res = [];
  var i = 1;
  // case 1
  var r1 = s.length % p;
  var r2 = r1 % q;
  if (r2 === 0) {
    while (i <= s.length / p) {
      res.push(s.substring((i - 1) * p, i * p));
      i++;
    }
    i = 1;
    while (i <= r1 / q) {
      res.push(s.substr(Math.floor(s.length / p) * p + (i - 1) * q, q));
      i++;
    }
    return res;
  }
  // case 2
  r1 = s.length % q;
  r2 = r1 % p;
  if (r2 === 0) {
    while (i <= s.length / q) {
      res.push(s.substring((i - 1) * q, i * q));
      i++;
    }
    i = 1;
    while (i <= r1 / p) {
      res.push(s.substr(Math.floor(s.length / q) * q + (i - 1) * p, p));
      i++;
    }
    return res;
  }
  return -1;
}

//console.log(resolve('abacabac', 1, 1));

const z = readline().split(' ');
const s = readline();
const res = resolve(s, parseInt(z[1], 10), parseInt(z[2], 10));
if (res === -1) {
  print(res);
} else {
  print(res.length);
  for (var i = 0; i < res.length; i++) {
    print(res[i]);
  }
}

function resolve(s, p, q) {
  var res = [];
  var i = 1;
  // case 1
  var r1 = s.length % p;
  var r2 = r1 % q;
  if (r2 === 0) {
    while (i <= s.length / p) {
      res.push(s.substring((i - 1) * p, i * p));
      i++;
    }
    i = 1;
    while (i <= r1 / q) {
      res.push(s.substr(Math.floor(s.length / p) * p + (i - 1) * q, q));
      i++;
    }
    return res;
  }
  // case 2
  r1 = s.length % q;
  r2 = r1 % p;
  if (r2 === 0) {
    while (i <= s.length / q) {
      res.push(s.substring((i - 1) * q, i * q));
      i++;
    }
    i = 1;
    while (i <= r1 / p) {
      res.push(s.substr(Math.floor(s.length / q) * q + (i - 1) * p, p));
      i++;
    }
    return res;
  }
  return -1;
}

//console.log(resolve('abacabac', 1, 1));

const z = readline().split(' ');
const s = readline();
const res = resolve(s, parseInt(z[1], 10), parseInt(z[2], 10));
print(res.length);
for (var i = 0; i < res.length; i++) {
  print(res[i]);
}

function main() {

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

    var n = arr[0],
        p = arr[1],
        q = arr[2];

    var str = readline();

    var flag=false;

    for (var i = 0; i < n; i++) {
        for (var j = 0; j < n; j++) {
            if ((i * p + j * q) == n) {
                print(i+j);
                var m;
                for(m=0;m<i;m++){
                    print(str.slice(p*m,p*(m+1)));
                }
                for(var n=0;n<j;n++){
                    print(str.slice(q*n+p*m,q*(n+1)+p*m));
                }
                flag=true;
                return;
            }
        }
    }

    if(flag==false){
        print(-1);
    }

}

main();

!function(r){function __webpack_require__(e){if(t[e])return t[e].exports;var n=t[e]={exports:{},id:e,loaded:!1};return r[e].call(n.exports,n,n.exports,__webpack_require__),n.loaded=!0,n.exports}var t={};return __webpack_require__.m=r,__webpack_require__.c=t,__webpack_require__.p="",__webpack_require__(0)}([function(r,t,e){r.exports=e(1)},function(r,t){"use strict";function solve(r,t,n,i){function calculate(r,t,e){for(var n=1;r>=n;n++){if(t*n>r)return[-1,0];var i=Math.floor((r-t*n)/e);if(n*t+i*e===r)return[n,i]}return[-1,0]}function resout(r,t,e,n,i){if(print(n+i),-1!==n){for(var u=0;n>u;u++)print(r.substr(0,t)),r=r.substr(t);for(var u=0;i>u;u++)print(r.substr(0,e)),r=r.substr(e)}}var u=calculate(r,t,n),a=e(u,2),o=a[0],c=a[1];print("nsp="+o+" nsq="+c),resout(i,t,n,o,c)}var e=function(){function sliceIterator(r,t){var e=[],n=!0,i=!1,u=void 0;try{for(var a,o=r[Symbol.iterator]();!(n=(a=o.next()).done)&&(e.push(a.value),!t||e.length!==t);n=!0);}catch(c){i=!0,u=c}finally{try{!n&&o.return&&o.return()}finally{if(i)throw u}}return e}return function(r,t){if(Array.isArray(r))return r;if(Symbol.iterator in Object(r))return sliceIterator(r,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),n=readline().split(" ").map(function(r){return parseInt(r)}),i=e(n,3),u=i[0],a=i[1],o=i[2],c=readline();solve(u,a,o,c)}]);

!function(r){function __webpack_require__(t){if(e[t])return e[t].exports;var n=e[t]={exports:{},id:t,loaded:!1};return r[t].call(n.exports,n,n.exports,__webpack_require__),n.loaded=!0,n.exports}var e={};return __webpack_require__.m=r,__webpack_require__.c=e,__webpack_require__.p="",__webpack_require__(0)}([function(r,e,t){r.exports=t(1)},function(r,e){"use strict";function solve(r,e,n,i){function calculate(r,e,t){for(var n=1;r>=n;n++){if(e*n>r)return[-1,0];var i=Math.floor((r-e*n)/t);if(n*e+i*t===r)return[n,i]}return[-1,0]}function resout(r,e,t,n,i){if(print(n+i),-1!==n){for(var u=0;n>u;u++)print(r.substr(0,e)),r=r.substr(e);for(var u=0;i>u;u++)print(r.substr(0,t)),r=r.substr(t)}}var u=calculate(r,e,n),a=t(u,2),o=a[0],c=a[1];resout(i,e,n,o,c)}var t=function(){function sliceIterator(r,e){var t=[],n=!0,i=!1,u=void 0;try{for(var a,o=r[Symbol.iterator]();!(n=(a=o.next()).done)&&(t.push(a.value),!e||t.length!==e);n=!0);}catch(c){i=!0,u=c}finally{try{!n&&o.return&&o.return()}finally{if(i)throw u}}return t}return function(r,e){if(Array.isArray(r))return r;if(Symbol.iterator in Object(r))return sliceIterator(r,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),n=readline().split(" ").map(function(r){return parseInt(r)}),i=t(n,3),u=i[0],a=i[1],o=i[2],c=readline();solve(u,a,o,c)}]);

var input = readline().split(" ").map(i => +i);
var n = input[0];
var p = input[1];
var q = input[2];
var s = readline();

var pCount = 0;
var qCount = 0;
var maxQCount = Math.floor(n/q);
var noCombination = true;
for (; qCount <= maxQCount; ++qCount) {
    if ((n - qCount*q)%p === 0) {
        pCount = (n - qCount*q) / p;
        noCombination = false;
        break;
    }
}
if (noCombination) {
    print(-1);
} else {
    var output = pCount + qCount + "\n";
    for (var i = 0; i < pCount; ++i) {
        for (var j = 0; j < p; ++j) {
            output += s.charAt(i+j);
        }
        output += "\n";
    }
    for (var i = 0; i < qCount; ++i) {
        for (var j = 0; j < q; ++j) {
            output += s.charAt(i+j+pCount*p);
        }
        output += "\n";
    }
    print(output);
}

const getXY = (n, p, q) => {
  const pR = n % p;
  const qR = n % q;

  if (pR === 0) {
    return {
      x: Math.floor(n / p),
      y: 0
    };
  }

  if (qR === 0) {
    return {
      x: 0,
      y: Math.floor(n / q)
    };
  }

  x = Math.floor(n / p);
  n = n - (x * p);
  if (n % q > 0) {
    return {
      x: 0,
      y: 0
    };
  }

  return {
    x,
    y: Math.floor(n / q)
  };
};

const processInput = ([n, p, q, s]) => {
  let {x, y} = getXY(n, p, q);

  let idx = 0;
  const lst = [];
  for (let i = 0; i < x; i++) {
    lst.push(s.slice(idx, idx + p));
    idx += p;
  }

  for (let i = 0; i < y; i++) {
    lst.push(s.slice(idx, idx + q));
    idx += q;
  }

  if (lst.length < 1) {
    process.stdout.write('-1');
    return;
  }

  process.stdout.write(`${lst.length}\n${lst.join('\n')}`);
};

(() => {
  process.stdin.setEncoding('utf8');
  const chunkList = [];
  process.stdin.on('readable', () => {
    let chunk;
    while ((chunk = process.stdin.read()) !== null) {
      chunkList.push(chunk);
    }
  });
  process.stdin.on('end', () => {
    let [one, two] = chunkList.join('').trim().split('\n');
    one = one.split(' ');
    one = one.map((v) => parseInt(v));
    processInput([...one, two]);
    process.exit(0);
  });
})();

const getXY = (n, p, q) => {
  const pR = n % p;
  const qR = n % q;

  if (pR === 0) {
    return {
      x: Math.floor(n / p),
      y: 0
    };
  }

  if (qR === 0) {
    return {
      x: 0,
      y: Math.floor(n / q)
    };
  }

  if (Math.max(p, q) === p) {
    x = Math.floor(n / p);
    let nn = n - (x * p);
    if (nn % q > 0) {
      return {
        x: 0,
        y: 0
      };
    }

    return {
      x,
      y: Math.floor(nn / q)
    };
  }

  let y = Math.floor(n / q);
  let nn = n - (y * q);
  if (nn % p > 0) {
    return {
      x: 0,
      y: 0
    };
  }

  return {
    x: Math.floor(nn / p),
    y
  };
};

const processInput = ([n, p, q, s]) => {
  let {x, y} = getXY(n, p, q);

  let idx = 0;
  const lst = [];
  for (let i = 0; i < x; i++) {
    lst.push(s.slice(idx, idx + p));
    idx += p;
  }

  for (let i = 0; i < y; i++) {
    lst.push(s.slice(idx, idx + q));
    idx += q;
  }

  if (lst.length < 1) {
    process.stdout.write('-1');
    return;
  }

  process.stdout.write(`${lst.length}\n${lst.join('\n')}`);
};

(() => {
  process.stdin.setEncoding('utf8');
  const chunkList = [];
  process.stdin.on('readable', () => {
    let chunk;
    while ((chunk = process.stdin.read()) !== null) {
      chunkList.push(chunk);
    }
  });
  process.stdin.on('end', () => {
    let [one, two] = chunkList.join('').trim().split('\n');
    one = one.split(' ');
    one = one.map((v) => parseInt(v));
    processInput([...one, two]);
    process.exit(0);
  });
})();

// https://codeforces.com/contest/612/problem/A

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

const getXY = (n, p, q) => {
  const isFit = (m, r) => (m % r) === 0;
  const nFits = (m, r) => Math.floor(m / r);
  const getFits = (m, a, b) => {
    let aX = nFits(m, a);
    let mN = m - (a * aX);
    if (isFit(mN, b)) {
      return [aX, nFits(mN, b)];
    }

    aX = Math.max(aX - 1, 0);
    mN = m - (a * aX);
    if (isFit(mN, b)) {
      return [aX, nFits(mN, b)];
    }

    return [0, 0];
  };

  let x, y;
  if (Math.max(p, q) === p) {
    ([x, y] = getFits(n, p, q));
  } else {
    ([y, x] = getFits(n, q, p));
  }
  return {x, y};
};

exports.solveProblem = (lineList) => {
  const [n, p, q] = lineList[0].split(' ').map((v) => parseInt(v));
  const s = lineList[1];

  let {x, y} = getXY(n, p, q);
  let idx = 0;
  const lst = [];
  for (let i = 0; i < x; i++) {
    lst.push(s.slice(idx, idx + p));
    idx += p;
  }

  for (let i = 0; i < y; i++) {
    lst.push(s.slice(idx, idx + q));
    idx += q;
  }

  if (lst.length < 1) {
    return '-1';
  }
  return `${lst.length}\n${lst.join('\n')}`;
};

if (module === require.main) {
  processInput(exports.solveProblem);
}


Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can.But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is ai. If some free time remains, she can spend it on reading.Help Luba to determine the minimum number of day when she finishes reading.It is guaranteed that the answer doesn't exceed n.Remember that there are 86400 seconds in a day.

The first line contains two integers n and t (1 ≤ n ≤ 100, 1 ≤ t ≤ 106) — the number of days and the time required to read the book. The second line contains n integers ai (0 ≤ ai ≤ 86400) — the time Luba has to spend on her work during i-th day.

Print the minimum day Luba can finish reading the book. It is guaranteed that answer doesn't exceed n.

s=readline().split(' ')
n=+s[0]
t=+s[1]
a=readline().split(' ').map(function(x){return +x;})
for (i=1;i<=n;i++)
{
    t-=(86400-a[i-1]);
    if (t<=0)
    {
        print(i)
        break
    }
}

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

var n = readline().split(' ').map(toInt);
var t = [n[1], n  = n[0]][0];
var ar = readline().split(' ').map(toInt);
var res = 0;

for (var i = 0; i < ar.length; i++) {
	res += (86400 - ar[i]);
	if (res >= t) {
		print(i+1);
		break;
	}
}

n_t =readline().split(' ');
a =readline().split(' ');
ans=0;
for(var i of a){
      n_t[1]-=86400-i;ans++;
      if(n_t[1]<=0){print(ans);break;}
}

(function main(){

    var tiempoRequerido = readline().split(" ")[1];
    var tiemposTrabajadosPorDia = readline().split(" ");

    var tiemposSobrantesPorDia = calcularTiempoSobrantePorDia();
    function calcularTiempoSobrantePorDia(){
        var tiemposSobrantesPorDia = [];
        for (var i = 0; i < tiemposTrabajadosPorDia.length; i++) {
            tiemposSobrantesPorDia[i] = 86400 - tiemposTrabajadosPorDia[i];
        }
        return tiemposSobrantesPorDia;
    }

    function calcularDiasNecesarios(){
        var diasNecesarios = 0;
        var segundosAcumulados = 0;
        for (var i = 0; i < tiemposSobrantesPorDia.length; i++) {
            diasNecesarios++;
            segundosAcumulados += tiemposSobrantesPorDia[i];
            if(segundosAcumulados >= tiempoRequerido){
                break;
            }
        }
        return diasNecesarios;
    }

    write(calcularDiasNecesarios());
})();

var input1=readline().split(" ");//reads the 1st input line to array
var a=readline().split(" ");//reads the 2nd input line to array a

var n=input1[0];
var t=parseInt(input1[1]);
var totalTime=t;
var prevTime=0;
const maxSecsPerDay=86400;
var noOfDays=0;

for(var i=0;i<n;i++) { //iterate for each day
  if (totalTime<=(maxSecsPerDay-parseInt(a[i]))) {
      noOfDays=i+1;
      break;
  } else {
     prevTime= totalTime;
     totalTime=totalTime-(maxSecsPerDay-parseInt(a[i]));
      if (totalTime<prevTime) noOfDays=i+1;
  }
}

print(noOfDays);

nt = readline().split(' ').map(Number);
str = readline().split(' ').map(Number);

var n = nt[0], t = nt[1], count = 1;

for (var i = 0; i < str.length; i++) {
	var freeTime = 86400 - str[i];

	if (t - freeTime <= 0) {
		break;
	} else {
		t = t - freeTime;
		count++;
	};
};

print(count);

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

//Don't have to see. end------------------------------------------
function Main(){
  var one = nextIntArray();
  var N = one[0];
  var t = one[1];
  var list = nextIntArray();
  for(var i = 0; i < N; i++){
    t -= 86400 - list[i];
    if(t <= 0){
      myout(i + 1);
      return;
    }
  }
}

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

rl.on('line', (d) => {
  if (c === 0) {
    [n, t] = d.split(' ').map(Number);
    c++;
    return;
  }

  let freeTime = 0;
  let ans = 1;
  const arr = d.split(' ').map(Number);

  for (let i = 0; i < arr.length; i++) {
    freeTime += daySeconds - arr[i];

    if (freeTime >= t) {
      ans += i;
      break;
    }
  }

  console.log(ans);

  c++;
});

(function main(){

    var tiempoRequerido = readline().split()[1];
    var tiemposTrabajadosPorDia = readline().split();

    var tiemposSobrantesPorDia = calcularTiempoSobrantePorDia();
    function calcularTiempoSobrantePorDia(){
        var tiemposSobrantesPorDia = [];
        for (var i = 0; i < tiemposTrabajadosPorDia.length; i++) {
            tiemposSobrantesPorDia[i] = 86400 - tiemposTrabajadosPorDia[i];
        }
        return tiemposSobrantesPorDia;
    }

    function calcularDiasNecesarios(){
        var diasNecesarios = 0;
        var segundosAcumulados = 0;
        for (var i = 0; i < tiemposSobrantesPorDia.length; i++) {
            diasNecesarios++;
            segundosAcumulados += tiemposSobrantesPorDia[i];
            if(segundosAcumulados >= tiempoRequerido){
                break;
            }
        }
        return "diasNecesarios:" + diasNecesarios +";segundosAcumulados:" + segundosAcumulados +
                "tiemporequerido: " + tiempoRequerido;

    }

    write(calcularDiasNecesarios());

})();

(function main(a, b){

    var tiempoRequerido = readline().split()[1];
    var tiemposTrabajadosPorDia = readline().split();

//    var tiempoRequerido = a.split(" ")[1];
//    var tiemposTrabajadosPorDia = b.split(" ");

    var tiemposSobrantesPorDia = calcularTiempoSobrantePorDia();
    function calcularTiempoSobrantePorDia(){
        var tiemposSobrantesPorDia = [];
        for (var i = 0; i < tiemposTrabajadosPorDia.length; i++) {
            tiemposSobrantesPorDia[i] = 86400 - tiemposTrabajadosPorDia[i];
        }
        return tiemposSobrantesPorDia;
    }

    function calcularDiasNecesarios(){
        var diasNecesarios = 0;
        var segundosAcumulados = 0;
        for (var i = 0; i < tiemposSobrantesPorDia.length; i++) {
            diasNecesarios++;
            segundosAcumulados += tiemposSobrantesPorDia[i];
            if(segundosAcumulados >= tiempoRequerido){
                break;
            }
        }
        return diasNecesarios;
    }

    write(calcularDiasNecesarios());
//    console.log(calcularDiasNecesarios());
})();

//main("2 86400", "86369 86369 86369 86369 86369 86355");

var input1=readline().split(" ");//reads the 1st input line to array
var a=readline().split(" ");//reads the 2nd input line to array a

var n=input1[0];
var t=parseInt(input1[1]);
const maxSecsPerDay=86400;
var noOfDays=0;

for(var i=0;i<n;i++) { //iterate for each day
  if (t<=(maxSecsPerDay-parseInt(a[i]))) {
      noOfDays+=i+1;
      break;
  } else {
      noOfDays+=i+1;
      t=t-(maxSecsPerDay-parseInt(a[i]));
  }
}

print(noOfDays);

var input1=readline().split(" ");//reads the 1st input line to array
var a=readline().split(" ");//reads the 2nd input line to array a

var n=input1[0];
var t=parseInt(input1[1]);
var totalTime=t;
var prevTime=0;
const maxSecsPerDay=86400;
var noOfDays=0;

for(var i=0;i<n;i++) { //iterate for each day
  if (totalTime<=(maxSecsPerDay-parseInt(a[i]))) {
      noOfDays+=i+1;
      break;
  } else {
     prevTime= totalTime;
     totalTime=totalTime-(maxSecsPerDay-parseInt(a[i]));
      if (totalTime<prevTime) noOfDays+=i+1;
  }
}

print(noOfDays);


Let $$$a$$$ and $$$b$$$ be two arrays of lengths $$$n$$$ and $$$m$$$, respectively, with no elements in common. We can define a new array $$$\mathrm{merge}(a,b)$$$ of length $$$n+m$$$ recursively as follows:  If one of the arrays is empty, the result is the other array. That is, $$$\mathrm{merge}(\emptyset,b)=b$$$ and $$$\mathrm{merge}(a,\emptyset)=a$$$. In particular, $$$\mathrm{merge}(\emptyset,\emptyset)=\emptyset$$$.  If both arrays are non-empty, and $$$a_1<b_1$$$, then $$$\mathrm{merge}(a,b)=[a_1]+\mathrm{merge}([a_2,\ldots,a_n],b)$$$. That is, we delete the first element $$$a_1$$$ of $$$a$$$, merge the remaining arrays, then add $$$a_1$$$ to the beginning of the result.  If both arrays are non-empty, and $$$a_1>b_1$$$, then $$$\mathrm{merge}(a,b)=[b_1]+\mathrm{merge}(a,[b_2,\ldots,b_m])$$$. That is, we delete the first element $$$b_1$$$ of $$$b$$$, merge the remaining arrays, then add $$$b_1$$$ to the beginning of the result. This algorithm has the nice property that if $$$a$$$ and $$$b$$$ are sorted, then $$$\mathrm{merge}(a,b)$$$ will also be sorted. For example, it is used as a subroutine in merge-sort. For this problem, however, we will consider the same procedure acting on non-sorted arrays as well. For example, if $$$a=[3,1]$$$ and $$$b=[2,4]$$$, then $$$\mathrm{merge}(a,b)=[2,3,1,4]$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).There is a permutation $$$p$$$ of length $$$2n$$$. Determine if there exist two arrays $$$a$$$ and $$$b$$$, each of length $$$n$$$ and with no elements in common, so that $$$p=\mathrm{merge}(a,b)$$$.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases.  The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 2000$$$). The second line of each test case contains $$$2n$$$ integers $$$p_1,\ldots,p_{2n}$$$ ($$$1\le p_i\le 2n$$$). It is guaranteed that $$$p$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$2000$$$.

For each test case, output "YES" if there exist arrays $$$a$$$, $$$b$$$, each of length $$$n$$$ and with no common elements, so that $$$p=\mathrm{merge}(a,b)$$$. Otherwise, output "NO".

NoteIn the first test case, $$$[2,3,1,4]=\mathrm{merge}([3,1],[2,4])$$$.In the second test case, we can show that $$$[3,1,2,4]$$$ is not the merge of two arrays of length $$$2$$$.In the third test case, $$$[3,2,6,1,5,7,8,4]=\mathrm{merge}([3,2,8,4],[6,1,5,7])$$$.In the fourth test case, $$$[1,2,3,4,5,6]=\mathrm{merge}([1,3,6],[2,4,5])$$$, for example.

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const t = Number(readLine())
    for (let _i = 0; _i < t; _i++) {
        const n = Number(readLine())
        const ps = readLine().split(/\s/).map(Number)
        let chunks = ps.map(value => ({ value, count: 1 }))
        while (true) {
          let chunkAdded = false
          chunks = chunks.reduce((acc, curr, i) => {
            if (i === 0) {
              acc[0] = curr
            } else if (acc[acc.length - 1].value > curr.value) {
              acc[acc.length - 1].count += 1
              chunkAdded = true
            } else {
              acc[acc.length] = curr
            }
            return acc
          }, [])
          if (!chunkAdded) {
            break
          }
        }
      chunks = chunks.map(({ count }) => count)
      let qs = []
      let yes = false
      for (const c of chunks) {
        if (c === n) {
          yes = true
          break
        }
        qs = qs.reduce((acc, curr, i) => {
          acc[i] = curr
          const v = i + c
          if (v <= n) {
            acc[v] = true
          }
          return acc
        }, [])
        if (qs[n]) {
          yes = true
          break
        }
        qs[c] = true
      }
      console.log(yes ? 'YES' : 'NO')
    }
}

const find_subset_v2 = (ls, target) => {
  const n = ls.length;
  const m = target + 1;
  const dp = new Uint8Array(n * m);
  const _ = (i, j) => i * m + j;

  dp[_(0, 0)] = 1;
  if (ls[0] < m) {
    dp[_(0, ls[0])] = 1;
  }

  for (let i = 1; i < n; i++) {
    for (let j = 0; j < m; j++) {
      let x = dp[_(i - 1, j)];
      if (ls[i] <= j) {
        x |= dp[_(i - 1, j - ls[i])];
      }
      dp[_(i, j)] = x;
    }
  }

  return dp[_(n - 1, target)];
};

const solve = (ls, debug = 0) => {
  const n = ls.length;

  // Make cumulative max and indices where cummax changes
  const cm = new Int32Array(n);
  const cm_id = [];
  // const cm_id_diff = [];
  let m = 0;
  for (let i = 0; i < n; i++) {
    if (ls[i] > m) {
      cm_id.push(i);
      m = ls[i];
    }
    cm[i] = m;
  }

  // Each region where cummax is same belong to same "unmerged" side
  const cm_id_diff = new Int32Array(cm_id.length);
  for (let i = 0; i < cm_id.length - 1; i++) {
    cm_id_diff[i] = cm_id[i + 1] - cm_id[i];
  }
  cm_id_diff[cm_id.length - 1] = n - cm_id.slice(-1)[0];

  if (debug) {
    console.log(ls, cm, cm_id, cm_id_diff);
  }

  // Find parition which makes "unmerged" pair same length
  const result = find_subset_v2(cm_id_diff, n / 2);
  return result ? 'YES' : 'NO';
};

const main = async (istr, ostr) => {
  const readline = require('readline');
  const it = readline.createInterface({input: istr})[Symbol.asyncIterator]();
  const next = async () => (await it.next()).value;
  const t = Number(await next());
  for (let i = 0; i < t; i++) {
    await next();
    const ls = new Int32Array((await next()).split(' ').map(Number));
    ostr.write(`${solve(ls)}\n`);
  }
};

if (require.main === module) {
  process.stdin.setEncoding('utf8');
  main(process.stdin, process.stdout);
}


Polycarp was gifted an array $$$a$$$ of length $$$n$$$. Polycarp considers an array beautiful if there exists a number $$$C$$$, such that each number in the array occurs either zero or $$$C$$$ times. Polycarp wants to remove some elements from the array $$$a$$$ to make it beautiful.For example, if $$$n=6$$$ and $$$a = [1, 3, 2, 1, 4, 2]$$$, then the following options are possible to make the array $$$a$$$ array beautiful:   Polycarp removes elements at positions $$$2$$$ and $$$5$$$, array $$$a$$$ becomes equal to $$$[1, 2, 1, 2]$$$;  Polycarp removes elements at positions $$$1$$$ and $$$6$$$, array $$$a$$$ becomes equal to $$$[3, 2, 1, 4]$$$;  Polycarp removes elements at positions $$$1, 2$$$ and $$$6$$$, array $$$a$$$ becomes equal to $$$[2, 1, 4]$$$; Help Polycarp determine the minimum number of elements to remove from the array $$$a$$$ to make it beautiful.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case consists of one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output one integer — the minimum number of elements that Polycarp has to remove from the array $$$a$$$ to make it beautiful.

let lines = require('fs').readFileSync(global.FILE_DESCRIPTOR || 0).toString().split('\n');
let index = 0;
const readline = () => lines[index++] || '';

let t = +readline();
while (t--) {
  let length = +readline();
  let arr = readline().split(' ').map(i => +i);
  let map = {};
  let counts = {};
  arr.forEach(num => {
    if (!map[num]) map[num] = 0;
    map[num]++;
  })
  for (let i in map) {
    let count = map[i];
    if (!counts[count]) counts[count] = 0
    counts[count] += 1;
  }
  let nums = Object.keys(counts).map(i => +i).sort((a, b) => a - b);
  let min = 10000000;
  for(let i in nums) {
    let num = nums[i];
    let remove = 0;
    for(let key in counts) {
      let kk = +key;
      let kkCount = counts[kk];
      if (kk < num) {
        remove += kkCount * kk
      } else if (kk > num) {
        remove += kkCount * (kk - num);
      }
    }
    if (remove < min) min = remove;
  }
  console.log(min)
}

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

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

const INF = 2e5 + 1;

function main () {
	let T = rn();
	while (T--) {
		let n = rn();
		let a = rna();

		const mp = new Map();
		for (const e of a) {
			mp.set(e, mp.has(e) ? mp.get(e) + 1 : 1);
		}

		const frq = Array.from(mp.values());
		frq.sort((x, y) => x - y);

		let ans = INF;
		for (let i = 0; i < frq.length; i++) {
			ans = Math.min(ans, n - (frq.length - i) * frq[i]);
		}

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

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        // var [n, k] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })
        // var s = new Array(n + 1).fill(0)

        //
        var count = {}
        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        for (let i = 0; i < n; i++) {
            if (!count[a[i]]) count[a[i]] = 0
            count[a[i]]++
        }
        var map2 = {}
        Object.keys(count).map(key => {
            if (!map2[count[key]]) map2[count[key]] = 0
            map2[count[key]]++

        })
        var keys = Object.keys(map2).map(x => parseInt(x)).sort((a, b) => map2[a] - map2[b])

        var sum = new Array(keys.length + 1).fill(0)

        var ans = n
        for (let i = 0; i < keys.length; i++) {
            sum = 0
            for (let j = 0; j < keys.length; j++) {
                if(keys[j]<keys[i]) sum+=map2[keys[j]]*keys[j]
                if(keys[j]>keys[i]) sum+=(keys[j] - keys[i])* map2[keys[j]]
            }
            ans = Math.min(ans, sum)
        }
        // console.log(keys)
        // console.log(map2)
        // console.log(sum)
        console.log(ans)

    })
}

let lines = require('fs').readFileSync(global.FILE_DESCRIPTOR || 0).toString().split('\n');
let index = 0;
const readline = () => lines[index++] || '';

let t = +readline();
while (t--) {
  let length = +readline();
  let arr = readline().split(' ').map(i => +i);
  let map = {};
  let counts = {};
  arr.forEach(num => {
    if (!map[num]) map[num] = 0;
    map[num]++;
  })
  for (let i in map) {
    let count = map[i];
    if (!counts[count]) counts[count] = 0
    counts[count] += count;
  }
  let nums = Object.keys(counts).map(i => +i).sort((a, b) => a - b);
  let min = 10000000;
  for(let i in nums) {
    let num = nums[i];
    let result = 0;
    for(let key in counts) {
      let kk = +key;
      let kkCount = counts[kk];
      if (kk < num) {
        result += kkCount
      } else if (kk > num) {
        result += kkCount - num;
      }
    }
    if (result < min) min = result;
  }
  //
  // console.log({nums, map, counts})
  // console.log('----------')
  console.log(min)
}

let lines = require('fs').readFileSync(global.FILE_DESCRIPTOR || 0).toString().split('\n');
let index = 0;
const readline = () => lines[index++] || '';

let t = +readline();
while (t--) {
  let length = +readline();
  let arr = readline().split(' ').map(i => +i);
  let map = {};
  let cc = {};
  arr.forEach(num => {
    if (!map[num]) map[num] = 0;
    map[num]++;
  })
  Object.keys(map).map(i => +i).forEach(num => {
    if (!cc[num]) cc[num] = 0;
    cc[num] += map[num];
  })
  let counts = {}
  Object.values(cc).map(i => +i).forEach(count => {
    if (!counts[count]) counts[count] = 0;
    counts[count] += count;
  })

  let max = -1
  let val = 0;
  Object.keys(counts).map(i => +i).forEach(key => {
    if (counts[key] > max) {
      max = counts[key]
      val = key;
    }
  })

  let add = 0;
  Object.keys(map).map(i => +i).forEach(num => {
    if (map[num] > val) {
      add += map[num] - val;
    } else if (map[num] < val){
      add += map[num]
    }
  })
  console.log(add)
}


A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large).Killjoy's account is already infected and has a rating equal to $$$x$$$. Its rating is constant. There are $$$n$$$ accounts except hers, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th account's initial rating is $$$a_i$$$. Any infected account (initially the only infected account is Killjoy's) instantly infects any uninfected account if their ratings are equal. This can happen at the beginning (before any rating changes) and after each contest. If an account is infected, it can not be healed.Contests are regularly held on Codeforces. In each contest, any of these $$$n$$$ accounts (including infected ones) can participate. Killjoy can't participate. After each contest ratings are changed this way: each participant's rating is changed by an integer, but the sum of all changes must be equal to zero. New ratings can be any integer.Find out the minimal number of contests needed to infect all accounts. You can choose which accounts will participate in each contest and how the ratings will change.It can be proven that all accounts can be infected in some finite number of contests.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. The next $$$2t$$$ lines contain the descriptions of all test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$2 \le n \le 10^3$$$, $$$-4000 \le x \le 4000$$$) — the number of accounts on Codeforces and the rating of Killjoy's account. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(-4000 \le a_i \le 4000)$$$ — the ratings of other accounts.

For each test case output the minimal number of contests needed to infect all accounts.

NoteIn the first test case it's possible to make all ratings equal to $$$69$$$. First account's rating will increase by $$$1$$$, and second account's rating will decrease by $$$1$$$, so the sum of all changes will be equal to zero.In the second test case all accounts will be instantly infected, because all ratings (including Killjoy's account's rating) are equal to $$$4$$$.

function mlt() { return readline().split(' ').map(x => parseInt(x)) }

function solv() {

    var inp = mlt()
    var x = inp[0]
    var y = inp[1]

    var s = mlt()

    var vis = {}
    for (var n = 0; n < x; n++)vis[s[n]] = (vis[s[n]] == null ? 1 : vis[s[n]] + 1)
    if (vis[y] == x) {
        print(0)
        return
    }
    else if (vis[y] >= 1) {
        print(1)
        return
    }
    var sm = 0;
    for (var n = 0; n < x; n++)sm += s[n] - y;
    if (sm == 0) {
        print(1);
    }
    else print(2)
}

var tc = 1;
tc = parseInt(readline());
while (tc--) solv()

"use strict";
var input = '';
var inputResolve;
var inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => {
    inputResolve();
});
(async () => {
    // var time = Date.now();
    await inputPromise;
    var inputs = input.split(/\r?\n/);
    var t = +inputs[0];
    for (let i = 0; i < t; i++) {
        var [n, x] = inputs[i * 2 + 1].split(' ').map(v => +v);
        var arr = inputs[i * 2 + 2].split(' ').map(v => +v);
        if (arr.every(v => v == x)) {
            console.log(0);
        }
        else if (arr.some(v => v == x) || arr.sum() == n * x) {
            console.log(1);
        }
        else {
            console.log(2);
        }
    }
    return;
    var p = [2];
    for (let i = 3; i < 1e5; i += 2) {
        let prime = true;
        for (let v of p) {
            if (v * v > i)
                break;
            if (i % v == 0) {
                prime = false;
                break;
            }
        }
        if (prime)
            p.push(i);
    }
    for (let i = 0; i < t; i++) {
        var x = +inputs[i + 1];
        var c = Array(p.length).fill(0);
        for (let j = 0;; j++) {
            if (p[j] > x)
                break;
            while (x % p[j] == 0) {
                x /= p[j];
                c[j]++;
            }
        }
        var cp = c.map((v, i) => v ? p[i] : 0).filter(v => v);
        c = c.filter(v => v);
        if (c.length == 1) {
            console.log(Array(c[0]).fill(0).map((v, i) => cp[0] ** (i + 1)).join(' '));
            console.log(0);
        }
        else {
            let mark = {};
            let arr = [];
            for (let i = 0; i < c.length; i++) {
                let bit = Array(c.length).fill(0);
                bit[i] = 1;
                arr.push(bit);
                mark[bit.join('')] = 1;
                bit = Array(c.length).fill(0);
                bit[i] = 1;
                bit[(i + 1) % c.length] = 1;
                arr.push(bit);
                mark[bit.join('')] = 1;
            }
            let c2 = 2 ** c.length;
            while (arr.length < c2 - 1) {
                for (let i = 1; i < c2; i++) {
                    let bit = Array(c.length).fill(0);
                    for (let j = 0; j < c.length; j++)
                        bit[j] = i & (1 << j) ? 1 : 0;
                    if (mark[bit.join('')])
                        continue;
                    if (bit.some((v, i) => arr[arr.length - 1][i] == v)) {
                        arr.push(bit);
                        mark[bit.join('')] = 1;
                    }
                }
            }
            console.log(arr);
            console.log(0);
        }
    }
})();
Object.defineProperty(Object.prototype, '$k', {
    value: function () { return Object.keys(this); }
});
Object.defineProperty(Object.prototype, '$v', {
    value: function () { return Object.values(this); }
});
Object.defineProperty(Object.prototype, '$kv', {
    value: function () { return Object.entries(this); }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0); };
Array.prototype.uniq = function (fn) {
    var set = new Set();
    return this.filter(v => {
        var newValue = !set.has(fn ? fn(v) : v);
        set.add(fn ? fn(v) : v);
        return newValue;
    });
};
Array.prototype.toObj = function (fn) {
    return this.map(v => fn(v)).reduce((p, v) => {
        p[v[0]] = v[1];
        return p;
    }, {});
};

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

    C();
});

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

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

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

    return a;
}

function C(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,x] = ti(readline().split(' '));
        let a = ti(readline().split(' '));

        let sum = 0;
        let f = true;
        let f2 = false;
        for(let i = 0; i < n; i++){
            if(a[i] !== x)
                f = false;

            if(a[i] === x)
                f2 = true;

            sum += a[i] - x;
        }

        if(f){
            console.log(0);
        }else if(sum === 0 || f2){
            console.log(1);
        }else{
            console.log(2);
        }
    }
}

function mlt() { return readline().split(' ').map(x => parseInt(x)) }

function solv() {

    var inp = mlt()
    var x = inp[0]
    var y = inp[1]

    var s = mlt()

    var vis = {}
    for (var n = 0; n < x; n++)vis[s[n]] = (vis[s[n]] == null ? 1 : vis[s[n]] + 1)
    if (vis[y] == x) {
        print(0)
        return
    }
    else if (vis[x] >= 1) {
        print(1)
        return
    }
    var sm = 0;
    for (var n = 0; n < x; n++)sm += s[n] - y;
    if (sm == 0) {
        print(1);
    }
    else print(2)
}

var tc = 1;
tc = parseInt(readline());
while (tc--) solv()

"use strict";
var input = '';
var inputResolve;
var inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => {
    inputResolve();
});
(async () => {
    // var time = Date.now();
    await inputPromise;
    var inputs = input.split(/\r?\n/);
    var t = +inputs[0];
    for (let i = 0; i < t; i++) {
        var [n, x] = inputs[i * 2 + 1].split(' ').map(v => +v);
        var arr = inputs[i * 2 + 2].split(' ').map(v => +v);
        if (arr.every(v => v == x)) {
            console.log(0);
        }
        else if (arr.sum() == n * x) {
            console.log(1);
        }
        else {
            console.log(2);
        }
    }
})();
Object.defineProperty(Object.prototype, '$k', {
    value: function () { return Object.keys(this); }
});
Object.defineProperty(Object.prototype, '$v', {
    value: function () { return Object.values(this); }
});
Object.defineProperty(Object.prototype, '$kv', {
    value: function () { return Object.entries(this); }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0); };
Array.prototype.uniq = function (fn) {
    var set = new Set();
    return this.filter(v => {
        var newValue = !set.has(fn ? fn(v) : v);
        set.add(fn ? fn(v) : v);
        return newValue;
    });
};
Array.prototype.toObj = function (fn) {
    return this.map(v => fn(v)).reduce((p, v) => {
        p[v[0]] = v[1];
        return p;
    }, {});
};

"use strict";
var input = '';
var inputResolve;
var inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => {
    inputResolve();
});
(async () => {
    // var time = Date.now();
    await inputPromise;
    var inputs = input.split(/\r?\n/);
    var t = +inputs[0];
    for (let i = 0; i < t; i++) {
        var [n, x] = inputs[i * 2 + 1].split(' ').map(v => +v);
        var arr = inputs[i * 2 + 2].split(' ').map(v => +v);
        if (arr.every(v => v == x)) {
            console.log(0);
        }
        else if (arr.some(v => v == n) || arr.sum() == n * x) {
            console.log(1);
        }
        else {
            console.log(2);
        }
    }
    return;
    var p = [2];
    for (let i = 3; i < 1e5; i += 2) {
        let prime = true;
        for (let v of p) {
            if (v * v > i)
                break;
            if (i % v == 0) {
                prime = false;
                break;
            }
        }
        if (prime)
            p.push(i);
    }
    for (let i = 0; i < t; i++) {
        var x = +inputs[i + 1];
        var c = Array(p.length).fill(0);
        for (let j = 0;; j++) {
            if (p[j] > x)
                break;
            while (x % p[j] == 0) {
                x /= p[j];
                c[j]++;
            }
        }
        var cp = c.map((v, i) => v ? p[i] : 0).filter(v => v);
        c = c.filter(v => v);
        if (c.length == 1) {
            console.log(Array(c[0]).fill(0).map((v, i) => cp[0] ** (i + 1)).join(' '));
            console.log(0);
        }
        else {
            let mark = {};
            let arr = [];
            for (let i = 0; i < c.length; i++) {
                let bit = Array(c.length).fill(0);
                bit[i] = 1;
                arr.push(bit);
                mark[bit.join('')] = 1;
                bit = Array(c.length).fill(0);
                bit[i] = 1;
                bit[(i + 1) % c.length] = 1;
                arr.push(bit);
                mark[bit.join('')] = 1;
            }
            let c2 = 2 ** c.length;
            while (arr.length < c2 - 1) {
                for (let i = 1; i < c2; i++) {
                    let bit = Array(c.length).fill(0);
                    for (let j = 0; j < c.length; j++)
                        bit[j] = i & (1 << j) ? 1 : 0;
                    if (mark[bit.join('')])
                        continue;
                    if (bit.some((v, i) => arr[arr.length - 1][i] == v)) {
                        arr.push(bit);
                        mark[bit.join('')] = 1;
                    }
                }
            }
            console.log(arr);
            console.log(0);
        }
    }
})();
Object.defineProperty(Object.prototype, '$k', {
    value: function () { return Object.keys(this); }
});
Object.defineProperty(Object.prototype, '$v', {
    value: function () { return Object.values(this); }
});
Object.defineProperty(Object.prototype, '$kv', {
    value: function () { return Object.entries(this); }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0); };
Array.prototype.uniq = function (fn) {
    var set = new Set();
    return this.filter(v => {
        var newValue = !set.has(fn ? fn(v) : v);
        set.add(fn ? fn(v) : v);
        return newValue;
    });
};
Array.prototype.toObj = function (fn) {
    return this.map(v => fn(v)).reduce((p, v) => {
        p[v[0]] = v[1];
        return p;
    }, {});
};

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

    C();
});

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

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

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

    return a;
}

function C(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,x] = ti(readline().split(' '));
        let a = ti(readline().split(' '));

        let sum = 0;
        let f = true;
        for(let i = 0; i < n; i++){
            if(a[i] !== x)
                f = false;

            sum += a[i] - x;
        }

        if(f){
            console.log(0);
        }else if(sum === 0){
            console.log(1);
        }else{
            console.log(2);
        }
    }
}