Initially Ildar has an empty array. He performs $$$n$$$ steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset $$$[0, 2, 3]$$$ is $$$1$$$, while the mex of the multiset $$$[1, 2, 1]$$$ is $$$0$$$.More formally, on the step $$$m$$$, when Ildar already has an array $$$a_1, a_2, \ldots, a_{m-1}$$$, he chooses some subset of indices $$$1 \leq i_1 < i_2 < \ldots < i_k < m$$$ (possibly, empty), where $$$0 \leq k < m$$$, and appends the $$$mex(a_{i_1}, a_{i_2}, \ldots a_{i_k})$$$ to the end of the array.After performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array $$$a_1, a_2, \ldots, a_n$$$ the minimum step $$$t$$$ such that he has definitely made a mistake on at least one of the steps $$$1, 2, \ldots, t$$$, or determine that he could have obtained this array without mistakes.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — the number of steps Ildar made. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array Ildar obtained.

If Ildar could have chosen the subsets on each step in such a way that the resulting array is $$$a_1, a_2, \ldots, a_n$$$, print $$$-1$$$. Otherwise print a single integer $$$t$$$ — the smallest index of a step such that a mistake was made on at least one step among steps $$$1, 2, \ldots, t$$$.

NoteIn the first example it is possible that Ildar made no mistakes. Here is the process he could have followed.  $$$1$$$-st step. The initial array is empty. He can choose an empty subset and obtain $$$0$$$, because the mex of an empty set is $$$0$$$. Appending this value to the end he gets the array $$$[0]$$$.  $$$2$$$-nd step. The current array is $$$[0]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1]$$$.  $$$3$$$-rd step. The current array is $$$[0,1]$$$. He can choose a subset $$$[0,1]$$$ and obtain an integer $$$2$$$, because $$$mex(0,1) = 2$$$. Appending this value to the end he gets the array $$$[0,1,2]$$$.  $$$4$$$-th step. The current array is $$$[0,1,2]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1,2,1]$$$. Thus, he can get the array without mistakes, so the answer is $$$-1$$$.In the second example he has definitely made a mistake on the very first step, because he could not have obtained anything different from $$$0$$$.In the third example he could have obtained $$$[0, 1, 2]$$$ without mistakes, but $$$239$$$ is definitely wrong.

const readline = require('readline');

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

const appnedMex = (length, result) => {
  let max = 0;
  for (let i = 0; i < length; i++) {
    if (result[i] > max) {
      return i + 1;
    }
    if ( max == result[i] )
      max += 1;
  }
  return -1;
}

let length, result;

rl.on('line', (line) => {
  if (!length) {
    length = line;
  } else {
    result = line.split(' ');
    console.log(appnedMex(length, result));
    rl.close();
    process.exit();
  }
});

var n=parseInt(readline())
var a=readline().split(" ").map(x=>parseInt(x))
var s=new Set()
s.add(0)
var chk=0
var cnt=1;
for(x of a){
    if(s.has(x) || s.has(x-1)){
        cnt+=1;
        s.add(x);
    }
    else{
        chk=1;
        break;
    }
}
if (a[0]!=0) print(1)
else if (chk==0) print(-1)
else print(cnt)

var m = readline(),
    arr = readline().split(' '),
    flag = 1,
    max = -1;
for(var i = 0; i < m; i++) {
    var newMax = Math.max(max, arr[i]);
    if(newMax - max > 1) {
        write(i + 1);
        flag = 0;
        break;
    }
    max = newMax;
}
if(flag) {
    write(-1);
}

const readline = require('readline');

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

const appnedMex = (length, result) => {
  for (let i = 0; i < length; i++) {
    if (result[i] >= i+1 ) {
      console.log(result[i]);
      return i + 1;
    }
  }
  return -1;
}

let length, result;

rl.on('line', (line) => {
  if (!length) {
    length = line;
  } else {
    result = line.split(' ');
    console.log(appnedMex(length, result));
    rl.close();
    process.exit();
  }
});

const readline = require('readline');

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

const appnedMex = (length, result) => {
  for (let i = 0; i < length; i++) {
    if (result[i] > i || result[i] > result[i-1] + 1) {
      return i + 1;
    }
  }
  return -1;
}

let length, result;

rl.on('line', (line) => {
  if (!length) {
    length = line;
  } else {
    result = line.split(' ');
    console.log(appnedMex(length, result));
    rl.close();
    process.exit();
  }
});

const readline = require('readline');

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

const appnedMex = (length, result) => {
  for (let i = 0; i < length; i++) {
    if (result[i] > i+1 ) {
      return i + 1;
    }
  }
  return -1;
}

let length, result;

rl.on('line', (line) => {
  if (!length) {
    length = line;
  } else {
    result = line.split(' ');
    console.log(appnedMex(length, result));
    rl.close();
    process.exit();
  }
});

const readline = require('readline');

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

const appnedMex = (length, result) => {
  for (let i = 0; i < length; i++) {
    if (result[i] >= i+1 ) {
      if ( i > 4000) {
        console.log(result[i]);
      }
      return i + 1;
    }
  }
  return -1;
}

let length, result;

rl.on('line', (line) => {
  if (!length) {
    length = line;
  } else {
    result = line.split(' ');
    console.log(appnedMex(length, result));
    rl.close();
    process.exit();
  }
});

const readline = require('readline');

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

const appnedMex = (length, result) => {
  for (let i = 0; i < length; i++) {
    if (result[i] >= i+2 ) {
      return i + 1;
    }
  }
  return -1;
}

let length, result;

rl.on('line', (line) => {
  if (!length) {
    length = line;
  } else {
    result = line.split(' ');
    console.log(appnedMex(length, result));
    rl.close();
    process.exit();
  }
});

const readline = require('readline');

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

const appnedMex = (length, result) => {
  let naj = 0;
  for (let i = 0; i < length; i++) {
    if (result[i] > naj ) {
      return i + 1;
    }
    naj = Math.max(naj, result[i] + 1);
  }
  return -1;
}

let length, result;

rl.on('line', (line) => {
  if (!length) {
    length = line;
  } else {
    result = line.trim();
    console.log(appnedMex(length, result));
    rl.close();
    process.exit();
  }
});

const readline = require('readline');

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

const appnedMex = (length, result) => {
  for (let i = 0; i < length; i++) {
    if ( i == 42230 || i == 42231 ) {
      console.log(result[i]);
    }
    if (result[i] >= i+1 ) {
      return i + 1;
    }
  }
  return -1;
}

let length, result;

rl.on('line', (line) => {
  if (!length) {
    length = line;
  } else {
    result = line.split(' ');
    console.log(appnedMex(length, result));
    rl.close();
    process.exit();
  }
});

const readline = require('readline');

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

const appnedMex = (length, result) => {
  let max = 0;
  for (let i = 0; i < length; i++) {
    if (result[i] > max) {
      return i + 1;
    }
    max = Math.max(max, result[i] + 1);
  }
  return -1;
}

let length, result;

rl.on('line', (line) => {
  if (!length) {
    length = line;
  } else {
    result = line.split(' ');
    console.log(appnedMex(length, result));
    rl.close();
    process.exit();
  }
});

const readline = require('readline');

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

const appnedMex = (length, result) => {
  for (let i = 0; i < length; i++) {
    if (result[i] > i && result[i] > result[i-1] + 1) {
      return i + 1;
    }
  }
  return -1;
}

let length, result;

rl.on('line', (line) => {
  if (!length) {
    length = line;
  } else {
    result = line.split(' ');
    console.log(appnedMex(length, result));
    rl.close();
    process.exit();
  }
});

const readline = require('readline');

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

const appnedMex = (length, result) => {
  for (let i = 0; i < length; i++) {
    if (result[i] >= i+1 ) {
      return i + 1;
    }
  }
  return -1;
}

let length, result;

rl.on('line', (line) => {
  if (!length) {
    length = line;
  } else {
    result = line.split(' ');
    console.log(appnedMex(length, result));
    rl.close();
    process.exit();
  }
});

var n=parseInt(readline())
var a=readline().split(" ").map(x=>parseInt(x))
var s=new Set()
s.add(0)
var chk=0
var cnt=1;
for(x of a){
    if(s.has(x) || s.has(x-1)){
        cnt+=1;
    }
    else{
        chk=1;
        break;
    }
}
if (a[0]!=0) print(1)
else if (chk==0) print(-1)
else print(cnt+1)

var m = readline(),
    arr = readline().split(' '),
    flag = 1;
for(var i = 0; i < m; i++) {
    if(arr[i] > i) {
        write(i + 1);
        flag = 0;
        break;
    }
}
if(flag) {
    write(-1);
}


Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.

6

logic

codeforces

bca

aaaaaaaaaaa

adbaadabad

to

NoteIn the first test case, the required path corresponds to the picture:  In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.

'use strict';

var fs = require('fs');

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

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const s = read();
  const n = s.length;
  const map = new Map();
  for (let i = 0; i < n; i++) {
    var _map$get;
    if (!map.has(s[i])) map.set(s[i], []);
    (_map$get = map.get(s[i])) === null || _map$get === void 0 ? void 0 : _map$get.push(i);
  }
  let flag = 1;
  if (s[0] > s[n - 1]) {
    flag = -1;
  }
  let res = [],
      d = 0,
      p = s.charCodeAt(0);
  for (let i = p; flag > 0 ? i <= s.charCodeAt(n - 1) : i >= s.charCodeAt(n - 1); i += flag) {
    const ch = String.fromCharCode(i);
    if (map.has(ch)) {
      d += Math.abs(i - p);
      p = i;
      for (let j of map.get(ch)) {
        res.push(j);
      }
    }
  }
  return `${d} ${res.length}\n${res.map(num => num + 1).join(' ')}`;
}

function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < 100) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= 100) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r\n?/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

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

function solve(str) {
    let a = str[0]
    let b = str[str.length - 1]
    let f = 0
    if (a > b) {
        [a, b] = [b, a]
        f = 1
    }
    const r = []
    for (let i = 1; i < str.length - 1; i++) {
        if (str[i] >= a && str[i] <= b) {
            r.push(i + 1)
        }
    }
    r.sort((p, q) => str.charCodeAt(p - 1) - str.charCodeAt(q - 1))
    if (f) r.reverse()
    r.unshift(1)
    r.push(str.length)
    const cost = b.charCodeAt(0) - a.charCodeAt(0)
    return cost + ' ' + r.length + '\n' + r.join(' ')
}

var t = +readline()

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

    var line = readline()

    var nums = []
    var pos = {}
    for (var j=1; j<line.length-1; j++) {

        var n = line.charCodeAt(j) - 96
        nums.push(n)
        if (pos[n] === undefined)
            pos[n] = [j+1]
        else
            pos[n].push(j+1)
    }

    var head = line.charCodeAt(0)-96
    var tail = line.charCodeAt(line.length-1)-96

    var min_cost = Math.abs(head-tail)

    nums = nums.sort((a, b) => { return a-b })

    var mode = 1
    if (head>tail) mode = 2

    var max_step = 0
    var ret = []
    //for (var k=0; k<nums.length; k++) {
    for (var k=1; k<=26; k++) {
        if (!pos[k]) continue
        if (k >= Math.min(head, tail) && k <= Math.max(head, tail)) {

            max_step = max_step + pos[k].length

            //var kk = pos[nums[k]].shift()
            //if (kk > 1 && kk < nums.length) ret.push(kk)
            ret = ret.concat(pos[k])
        }
    }

    if (mode == 2) {
        ret = ret.reverse()
    }
    max_step = max_step + 2
    print(min_cost + " " +max_step)
    ret.unshift(1)
    //ret.push(nums.length)
    ret.push(nums.length+2)
    print(ret.join(" "))

}

'use strict';

var fs = require('fs');

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

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const s = read();
  const n = s.length;
  const map = new Map();
  for (let i = 0; i < n; i++) {
    var _map$get;
    if (!map.has(s[i])) map.set(s[i], []);
    (_map$get = map.get(s[i])) === null || _map$get === void 0 ? void 0 : _map$get.push(i);
  }
  let flag = 1;
  if (s[0] > s[n - 1]) {
    flag = -1;
  }
  let res = [],
      d = 0,
      p = s.charCodeAt(0);
  for (let i = p; flag > 0 ? i <= s.charCodeAt(n - 1) : i >= s.charCodeAt(n - 1); i += flag) {
    const ch = String.fromCharCode(i);
    if (map.has(ch)) {
      d += Math.abs(i - p);
      p = i;
      for (let j of map.get(ch)) {
        res.push(j);
      }
    }
  }
  return `${d} ${res.length}\n${res.map(num => num + 1).join(' ')}`;
}

function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < 100) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= 100) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split('\n');
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

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

function solve(str) {
    let a = str[0]
    let b = str[str.length - 1]
    if (a > b) {
        [a, b] = [b, a]
    }
    const r = []
    for (let i = 1; i < str.length - 1; i++) {
        if (str[i] >= a && str[i] <= b) {
            r.push(i + 1)
        }
    }
    r.sort((p, q) => str.charCodeAt(p - 1) - str.charCodeAt(q - 1))
    r.unshift(1)
    r.push(str.length)
    const cost = b.charCodeAt(0) - a.charCodeAt(0)
    return cost + ' ' + r.length + '\n' + r.join(' ')
}

var t = +readline()

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

    var line = readline()

    var nums = []
    var pos = {}
    for (var j=1; j<line.length-1; j++) {

        var n = line.charCodeAt(j) - 96
        nums.push(n)
        if (pos[n] === undefined)
            pos[n] = [j+1]
        else
            pos[n].push(j+1)
    }

    var head = line.charCodeAt(0)-96
    var tail = line.charCodeAt(line.length-1)-96

    var min_cost = Math.abs(head-tail)

    nums = nums.sort((a, b) => { return a-b })

    var mode = 1
    if (head>tail) mode = 2

    var max_step = 0
    var ret = []
    //for (var k=0; k<nums.length; k++) {
    for (var k=1; k<=26; k++) {
        if (!pos[k]) continue
        if (k >= Math.min(head, tail) && k <= Math.max(head, tail)) {

            max_step++

            //var kk = pos[nums[k]].shift()
            //if (kk > 1 && kk < nums.length) ret.push(kk)
            ret = ret.concat(pos[k])
        }
    }

    if (mode == 2) {
        ret = ret.reverse()
    }
    max_step = max_step + 2
    print(min_cost + " " +max_step)
    ret.unshift(1)
    //ret.push(nums.length)
    ret.push(nums.length+2)
    print(ret.join(" "))

}

var t = +readline()

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

    var line = readline()

    var nums = []
    var pos = {}
    for (var j=1; j<line.length-1; j++) {

        var n = line.charCodeAt(j) - 96
        nums.push(n)
        if (pos[n] === undefined)
            pos[n] = [j+1]
        else
            pos[n].push(j+1)
    }

    var head = line.charCodeAt(0)-96
    var tail = line.charCodeAt(line.length-1)-96

    var min_cost = Math.abs(head-tail)

    nums = nums.sort((a, b) => { return a-b })

    var mode = 1
    if (head>tail) mode = 2

    var max_step = 0
    var ret = []
    for (var k=0; k<nums.length; k++) {
        if (nums[k] >= Math.min(head, tail) && nums[k] <= Math.max(head, tail)) {

            max_step++

            //var kk = pos[nums[k]].shift()
            //if (kk > 1 && kk < nums.length) ret.push(kk)
            ret = ret.concat(pos[nums[k]])
        }
    }

    if (mode == 2) {
        ret = ret.reverse()
    }
    max_step = max_step + 2
    print(min_cost + " " +max_step)
    ret.unshift(1)
    //ret.push(nums.length)
    ret.push(nums.length+2)
    print(ret.join(" "))

}

var t = +readline()

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

    var line = readline()

    var nums = []
    var pos = {}
    for (var j=0; j<line.length; j++) {
        var n = line.charCodeAt(j) - 96
        nums.push(n)
        if (pos[n] === undefined)
            pos[n] = [j+1]
        else
            pos[n].push(j+1)
    }

    //for (var p in pos) {
        //print("p="+p)
        //print("pos[p]=" + pos[p])
    //}

    var head = nums[0]
    var tail = nums[nums.length - 1]
    var min_cost = Math.abs(head-tail)

    nums = nums.sort((a, b) => { return a-b })
    //print(head)
    //print(tail)

    var mode = 1
    if (head>tail) mode = 2

    var max_step = 0
    var ret = []
    for (var k=0; k<nums.length; k++) {
        //print(nums[k])
        if (nums[k] >= Math.min(head, tail) && nums[k] <= Math.max(head, tail)) {

            max_step++
            //print("max_step="+max_step )

            //print("seq = " + pos[nums[k]].shift())
            ret.push(pos[nums[k]].shift())
        }
    }

    //reverse ret
    if (mode == 2) {
        ret = ret.reverse()
    }

    //print ("min=" + min_cost)
    //print ("max=" + max_step)
    //print ("ret = "+ ret)

    print(min_cost + " " + max_step)
    print(ret.join(" "))
}

var t = +readline()

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

    var line = readline()

    var nums = []
    for (var j=0; j<line.length; j++) {
        var n = line.charCodeAt(j) - 97
        nums.push(n)
    }

    nums = nums.sort((a, b) => { return b-a })
    print (nums)
    //print("answer")
}


As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.Elections are coming. You know the number of voters and the number of parties — $$$n$$$ and $$$m$$$ respectively. For each voter you know the party he is going to vote for. However, he can easily change his vote given a certain amount of money. In particular, if you give $$$i$$$-th voter $$$c_i$$$ bytecoins you can ask him to vote for any other party you choose.The United Party of Berland has decided to perform a statistical study — you need to calculate the minimum number of bytecoins the Party needs to spend to ensure its victory. In order for a party to win the elections, it needs to receive strictly more votes than any other party.

The first line of input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 3000$$$) — the number of voters and the number of parties respectively. Each of the following $$$n$$$ lines contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le m$$$, $$$1 \le c_i \le 10^9$$$) — the index of this voter's preferred party and the number of bytecoins needed for him to reconsider his decision. The United Party of Berland has the index $$$1$$$.

Print a single number — the minimum number of bytecoins needed for The United Party of Berland to win the elections.

NoteIn the first sample, The United Party wins the elections even without buying extra votes.In the second sample, The United Party can buy the votes of the first and the fourth voter. This way The Party gets two votes, while parties $$$3$$$, $$$4$$$ and $$$5$$$ get one vote and party number $$$2$$$ gets no votes.In the third sample, The United Party can buy the votes of the first three voters and win, getting three votes against two votes of the fifth party.

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        if (voter.intention !== 1) voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    voters = voters.sort((v1, v2) => v1.price - v2.price)

    let l = 0, r = n, minBudget = Infinity, count = 300;
    while (count--) {
        const mid1 = parseInt(l + (r - l) / 3)
        const mid2 = parseInt(r - (r - l) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = partiesVotes[1], currentVotes = [...partiesVotes], bought = []

            voters.forEach((voter, idx) => {
                if (currentVotes[voter.intention] >= requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                    bought[idx] = true
                }
            })

            voters.forEach((voter, idx) => {
                if (!bought[idx] && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                }
            })

            return currentVotes.length <= 2 || myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        const b1 = compute(mid1), b2 = compute(mid2)
        if (b1 > b2) {
            l = mid1
        } else {
            r = mid2
        }

        minBudget = Math.min(b1, b2, minBudget)
    }
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else if (numLines <= n + 1) {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        if (voter.intention !== 1) voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    voters.sort((v1, v2) => v1.price > v2.price)

    let minBudget = Infinity, compute = requiredVotes => {
        let budget = 0, myVotes = partiesVotes[1], currentVotes = [...partiesVotes], bought = []

        console.log('=======')
        voters.forEach((voter, idx) => {
            console.log(voter.price)
            if (currentVotes[voter.intention] >= requiredVotes) {
                budget += voter.price
                currentVotes[voter.intention]--
                ++myVotes
                bought[idx] = true
            }
        })
        console.log('=======')

        voters.forEach((voter, idx) => {
            if (!bought[idx] && myVotes < requiredVotes) {
                budget += voter.price
                currentVotes[voter.intention]--
                ++myVotes
            }
        })
        return myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
    }

    for (let i = 0; i <= n; ++i) {
        minBudget = Math.min(compute(i), minBudget)
    }

    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    let l = 0, r = n + 1, minBudget = Infinity, count = 206;
    while (count--) {
        const mid1 = parseInt((l * 2 + r) / 3)
        const mid2 = parseInt((l + 2 * r) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = voters.filter(v => v.intention == 1).length, currentVotes = [...partiesVotes]

            const votesToBuyFrom = currentVotes.map(votes => Math.max(1 + votes - requiredVotes, 0))

            const above = voters.filter(v => v.intention != 1 && partiesVotes[v.intention] >= requiredVotes)
            const below = voters.filter(v => v.intention != 1 && partiesVotes[v.intention] < requiredVotes)
            above.sort((a, b) => a.price > b.price).forEach(voter => {
                const party = voter.intention
                if (myVotes < requiredVotes && votesToBuyFrom[party] > 0) {
                    budget += voter.price
                    votesToBuyFrom[party]--
                    currentVotes[party]--
                    myVotes++
                } else {
                    below.push(voter)
                }
            })

            below.sort((a, b) => a.price > b.price).forEach(voter => {
                const party = voter.intention
                if (myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[party]--
                    myVotes++
                }
            })

            return budget <= minBudget && myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        const b1 = compute(mid1), b2 = compute(mid2)
        if (b1 > b2) {
            l = mid1
        } else {
            r = mid2
        }

        minBudget = Math.min(b1, b2, minBudget)
    }
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    let l = 0, r = n, minBudget = Infinity, count = 60;
    while (count--) {
        const mid1 = parseInt((l * 2 + r) / 3)
        const mid2 = parseInt((l + 2 * r) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = voters.filter(v => v.intention == 1).length, currentVotes = [...partiesVotes]

            const votesToBuyFrom = currentVotes.map(votes => Math.max(1 + votes - requiredVotes, 0))

            const above = voters.filter(v => v.intention != 1 && partiesVotes[v.intention] >= requiredVotes)
            const below = voters.filter(v => v.intention != 1 && partiesVotes[v.intention] < requiredVotes)
            above.sort((a, b) => a.price > b.price).forEach(voter => {
                const party = voter.intention
                if (myVotes < requiredVotes && votesToBuyFrom[party] > 0) {
                    budget += voter.price
                    votesToBuyFrom[party]--
                    currentVotes[party]--
                    myVotes++
                } else {
                    below.push(voter)
                }
            })

            below.sort((a, b) => a.price > b.price).forEach(voter => {
                const party = voter.intention
                if (myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[party]--
                    myVotes++
                }
            })

            return budget <= minBudget && myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        const b1 = compute(mid1), b2 = compute(mid2)
        if (b1 > b2) {
            l = mid1
        } else {
            r = mid2
        }

        minBudget = Math.min(b1, b2, minBudget)
    }
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        if (voter.intention !== 1) voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    voters.sort((v1, v2) => v1.price > v2.price)

    let l = 0, r = n, minBudget = Infinity, count = 208;
    while (count--) {
        const mid1 = parseInt((l * 2 + r) / 3)
        const mid2 = parseInt((l + 2 * r) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = partiesVotes[1], currentVotes = [...partiesVotes], bought = []

            voters.forEach((voter, idx) => {
                if (currentVotes[voter.intention] >= requiredVotes && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                    bought[idx] = true
                }
            })

            voters.forEach((voter, idx) => {
                if (!bought[idx] && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                }
            })
            return myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        const b1 = compute(mid1), b2 = compute(mid2)
        if (b1 > b2) {
            l = mid1
        } else {
            r = mid2
        }

        minBudget = Math.min(b1, b2, minBudget)
    }
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    let l = 0, r = n + 1, minBudget = Infinity, count = 200;
    while (count--) {
        const mid1 = parseInt((l * 2 + r) / 3)
        const mid2 = parseInt((l + 2 * r) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = voters.filter(v => v.intention == 1).length, currentVotes = [...partiesVotes]

            const votesToBuyFrom = currentVotes.map(votes => Math.max(1 + votes - requiredVotes, 0))

            const above = voters.filter(v => v.intention != 1 && partiesVotes[v.intention] >= requiredVotes)
            const below = voters.filter(v => v.intention != 1 && partiesVotes[v.intention] < requiredVotes)
            above.sort((a, b) => a.price > b.price).forEach(voter => {
                const party = voter.intention
                if (myVotes < requiredVotes && votesToBuyFrom[party] > 0) {
                    budget += voter.price
                    votesToBuyFrom[party]--
                    currentVotes[party]--
                    myVotes++
                } else {
                    below.push(voter)
                }
            })

            below.sort((a, b) => a.price > b.price).forEach(voter => {
                const party = voter.intention
                if (myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[party]--
                    myVotes++
                }
            })

            return budget <= minBudget && myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        const b1 = compute(mid1), b2 = compute(mid2)
        if (b1 > b2) {
            l = mid1
        } else {
            r = mid2
        }

        minBudget = Math.min(b1, b2, minBudget)
    }
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    let minBudget = Infinity;
    [...Array(1 + (n + 1) / 2).keys()].forEach(requiredVotes => {
        let budget = 0, myVotes = voters.filter(v => v.intention == 1).length, currentVotes = [...partiesVotes]

        const votesToBuyFrom = currentVotes.map(votes => Math.max(1 + votes - requiredVotes, 0))

        const above = voters.filter(v => v.intention != 1 && partiesVotes[v.intention] >= requiredVotes)
        above.sort((a, b) => a.price > b.price).forEach(voter => {
            const party = voter.intention
            if (myVotes < requiredVotes && votesToBuyFrom[party] > 0) {
                budget += voter.price
                votesToBuyFrom[party]--
                currentVotes[party]--
                myVotes++
            }
        })

        const below = voters.filter(v => v.intention != 1 && partiesVotes[v.intention] < requiredVotes)
        below.sort((a, b) => a.price > b.price).forEach(voter => {
            const party = voter.intention
            if (myVotes < requiredVotes) {
                budget += voter.price
                currentVotes[party]--
                myVotes++
            }
        })

        if (budget <= minBudget && myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x))) {
            minBudget = budget
        }
    })
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        if (voter.intention !== 1) voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    voters.sort((v1, v2) => v1.price > v2.price)

    let l = 0, r = n, minBudget = Infinity, count = 300;
    while (count--) {
        const mid1 = parseInt(l + (r - l) / 3)
        const mid2 = parseInt(r - (r - l) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = partiesVotes[1], currentVotes = [...partiesVotes], bought = []

            voters.forEach((voter, idx) => {
                if (currentVotes[voter.intention] >= requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                    bought[idx] = true
                }
            })

            voters.forEach((voter, idx) => {
                if (!bought[idx] && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                }
            })
            return myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        const b1 = compute(mid1), b2 = compute(mid2)
        if (b1 > b2) {
            l = mid1
        } else {
            r = mid2
        }

        minBudget = Math.min(b1, b2, minBudget)
    }
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else if (numLines <= n + 1) {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        if (voter.intention !== 1) voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    voters.sort((v1, v2) => v1.price > v2.price)

    let l = 0, r = n, minBudget = Infinity, count = 500;
    while (count--) {
        const mid1 = parseInt(l + (r - l) / 3)
        const mid2 = parseInt(r - (r - l) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = partiesVotes[1], currentVotes = [...partiesVotes], bought = []

            voters.forEach((voter, idx) => {
                if (currentVotes[voter.intention] >= requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                    bought[idx] = true
                }
            })

            voters.forEach((voter, idx) => {
                if (!bought[idx] && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                }
            })
            return myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        const b1 = compute(mid1), b2 = compute(mid2)
        if (b1 > b2) {
            l = mid1
        } else {
            r = mid2
        }

        minBudget = Math.min(b1, b2, minBudget)
    }
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        if (voter.intention !== 1) voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    voters.sort((v1, v2) => v1.price > v2.price)

    let l = 0, r = n, minBudget = Infinity, count = 500;
    while (count--) {
        const mid1 = parseInt(l + (r - l) / 3)
        const mid2 = parseInt(r - (r - l) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = partiesVotes[1], currentVotes = [...partiesVotes], bought = []

            voters.forEach((voter, idx) => {
                if (currentVotes[voter.intention] >= requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                    bought[idx] = true
                }
            })

            voters.forEach((voter, idx) => {
                if (!bought[idx] && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                }
            })
            return myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        const b1 = compute(mid1), b2 = compute(mid2)
        if (b1 > b2) {
            l = mid1
        } else {
            r = mid2
        }

        minBudget = Math.min(b1, b2, minBudget)
    }
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        if (voter.intention !== 1) voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    voters.sort((v1, v2) => v1.price > v2.price)

    let l = 0, r = n, minBudget = Infinity, count = 300;
    while (count--) {
        const mid1 = parseInt((l * 2 + r) / 3)
        const mid2 = parseInt((l + 2 * r) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = partiesVotes[1], currentVotes = [...partiesVotes], bought = []

            voters.forEach((voter, idx) => {
                if (currentVotes[voter.intention] >= requiredVotes && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                    bought[idx] = true
                }
            })

            voters.forEach((voter, idx) => {
                if (!bought[idx] && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                }
            })
            return myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        const b1 = compute(mid1), b2 = compute(mid2)
        if (b1 > b2) {
            l = mid1
        } else {
            r = mid2
        }

        minBudget = Math.min(b1, b2, minBudget)
    }
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        if (voter.intention !== 1) voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    voters = voters.sort((v1, v2) => v1.price > v2.price)

    let l = 0, r = n, minBudget = Infinity, count = 300;
    while (count--) {
        const mid1 = parseInt(l + (r - l) / 3)
        const mid2 = parseInt(r - (r - l) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = partiesVotes[1], currentVotes = [...partiesVotes], bought = []

            voters.forEach((voter, idx) => {
                if (currentVotes[voter.intention] >= requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                    bought[idx] = true
                }
            })

            voters.forEach((voter, idx) => {
                if (!bought[idx] && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                }
            })
            return myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        const b1 = compute(mid1), b2 = compute(mid2)
        if (b1 > b2) {
            l = mid1
        } else {
            r = mid2
        }

        minBudget = Math.min(b1, b2, minBudget)
    }
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else if (numLines <= n + 1) {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        if (voter.intention !== 1) voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    voters.sort((v1, v2) => v1.price > v2.price)

    let minBudget = Infinity, compute = requiredVotes => {
        let budget = 0, myVotes = partiesVotes[1], currentVotes = [...partiesVotes], bought = []

        voters.forEach((voter, idx) => {
            if (currentVotes[voter.intention] >= requiredVotes) {
                budget += voter.price
                currentVotes[voter.intention]--
                ++myVotes
                bought[idx] = true
            }
        })

        voters.forEach((voter, idx) => {
            if (!bought[idx] && myVotes < requiredVotes) {
                budget += voter.price
                currentVotes[voter.intention]--
                ++myVotes
            }
        })
        return myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
    }

    for (let i = 0; i <= n; ++i) {
        minBudget = Math.min(compute(i), minBudget)
    }

    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else if (numLines <= n + 1) {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        if (voter.intention !== 1) voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    voters.sort((v1, v2) => v1.price > v2.price)

    let l = 0, r = n, minBudget = Infinity, count = 500;
    //    while (count--) {
    for (let i = n == 3000 ? 0 : 0; i <= (n == 3000 ? 400 : 400); ++i) {
        const mid1 = parseInt(l + (r - l) / 3)
        const mid2 = parseInt(r - (r - l) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = partiesVotes[1], currentVotes = [...partiesVotes], bought = []

            voters.forEach((voter, idx) => {
                if (currentVotes[voter.intention] >= requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                    bought[idx] = true
                }
            })

            voters.forEach((voter, idx) => {
                if (!bought[idx] && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                }
            })
            return myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        //        const b1 = compute(mid1), b2 = compute(mid2)
        //if (b1 > b2) {
        //    l = mid1
        //} else {
        //     r = mid2
        //}

        minBudget = Math.min(compute(i), minBudget)
    }
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        if (voter.intention !== 1) voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    voters.sort((v1, v2) => v1.price > v2.price)

    let l = 0, r = n, minBudget = Infinity, count = 400;
    while (count--) {
        const mid1 = parseInt((l * 2 + r) / 3)
        const mid2 = parseInt((l + 2 * r) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = partiesVotes[1], currentVotes = [...partiesVotes], bought = []

            voters.forEach((voter, idx) => {
                if (currentVotes[voter.intention] >= requiredVotes && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                    bought[idx] = true
                }
            })

            voters.forEach((voter, idx) => {
                if (!bought[idx] && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                }
            })
            return myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        const b1 = compute(mid1), b2 = compute(mid2)
        if (b1 > b2) {
            l = mid1
        } else {
            r = mid2
        }

        minBudget = Math.min(b1, b2, minBudget)
    }
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        if (voter.intention !== 1) voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    voters.sort((v1, v2) => v1.price > v2.price)

    let l = 0, r = n, minBudget = Infinity, count = 300;
    while (count--) {
        const mid1 = parseInt((l * 2 + r) / 3)
        const mid2 = parseInt((l + 2 * r) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = partiesVotes[1], currentVotes = [...partiesVotes], bought = []

            voters.forEach((voter, idx) => {
                if (currentVotes[voter.intention] >= requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                    bought[idx] = true
                }
            })

            voters.forEach((voter, idx) => {
                if (!bought[idx] && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                }
            })
            return myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        const b1 = compute(mid1), b2 = compute(mid2)
        if (b1 > b2) {
            l = mid1
        } else {
            r = mid2
        }

        minBudget = Math.min(b1, b2, minBudget)
    }
    process.stdout.write(`${minBudget}`)
})

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

let n, m, voters = [], parties, partiesVotes, numLines = 0
rl.on('line', line => {
    if (++numLines == 1) {
        [n, m] = line.split(' ').map(x => parseInt(x))
        parties = [...Array(m + 1).keys()].slice(1)
        partiesVotes = Array(m + 1).fill(0)
    } else {
        let voter = {};
        [voter.intention, voter.price] = line.split(' ').map(x => parseInt(x))
        if (voter.intention !== 1) voters.push(voter)
        partiesVotes[voter.intention]++
    }
}).on('close', () => {
    voters.sort((v1, v2) => v1.price > v2.price)

    let l = 0, r = n, minBudget = Infinity, count = 500;
    while (count--) {
        const mid1 = parseInt(l + (r - l) / 3)
        const mid2 = parseInt(r - (r - l) / 3)

        let compute = requiredVotes => {
            let budget = 0, myVotes = partiesVotes[1], currentVotes = [...partiesVotes], bought = []

            voters.forEach((voter, idx) => {
                if (currentVotes[voter.intention] >= requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                    bought[idx] = true
                }
            })

            voters.forEach((voter, idx) => {
                if (!bought[idx] && myVotes < requiredVotes) {
                    budget += voter.price
                    currentVotes[voter.intention]--
                    ++myVotes
                }
            })
            return myVotes > currentVotes.slice(2).reduce((a, x) => Math.max(a, x)) ? budget : Infinity
        }

        const b1 = compute(mid1), b2 = compute(mid2)
        if (b1 >= b2) {
            l = mid1
        } else {
            r = mid2
        }

        minBudget = Math.min(b1, b2, minBudget)
    }
    process.stdout.write(`${minBudget}`)
})


There is a $$$n \times m$$$ grid. You are standing at cell $$$(1, 1)$$$ and your goal is to finish at cell $$$(n, m)$$$.You can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell $$$(x, y)$$$. You can:   move right to the cell $$$(x, y + 1)$$$ — it costs $$$x$$$ burles;  move down to the cell $$$(x + 1, y)$$$ — it costs $$$y$$$ burles. Can you reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first and only line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n, m \le 100$$$; $$$0 \le k \le 10^4$$$) — the sizes of grid and the exact amount of money you need to spend.

For each test case, if you can reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first test case, you are already in the final cell, so you spend $$$0$$$ burles.In the second, third and fourth test cases, there are two paths from $$$(1, 1)$$$ to $$$(2, 2)$$$: $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(1, 2)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ or $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$. Both costs $$$1 + 2 = 3$$$ burles, so it's the only amount of money you can spend.In the fifth test case, there is the only way from $$$(1, 1)$$$ to $$$(1, 4)$$$ and it costs $$$1 + 1 + 1 = 3$$$ burles.

    var t = readline();
    for(var i = 0 ; i < t ; i++){
        var inputs = readline().split(' '),
            n = inputs[0],
            m = inputs[1],
            k = inputs[2] ;
            if((n*m) - 1 == k){
                print("YES");
            }
            else{
                print("NO");
            }

    }

(function () {
    const count = readline();
    const n = Number(count);

    var i;
    for (i = 0; i < n; i++) {
        var line = readline();
        var items = line.split(' ');
        var x = Number(items[0]) - 1;
        var y = Number(items[1]) - 1;
        var j;
        var k;
        var c = 0;
        var result = 'No';
        for (j = 1; j <= x; j++) {
            c += 1;
        }
        for (k = 1; k <= y; k++) {
            c += Number(items[0]);
        }
        if (c === Number(items[2])) {
            result = 'Yes';
        }

        print(result);
    }
})();

/* Common Template Starts */
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++];
}
/* Common Template Ends */

function main() {
    const length = Number(readline());
    for (let i = 0; i < length; i++) {
        const [x, y, budget] = readline().split(' ').map(e => Number(e));
        if(x * y - 1 === budget) {
            console.log('YES')
        }
        else {
            console.log('NO')
        }
    }
    return;
}

'use strict';

function solve(n, m, k) {
  let res = 0;
  for (let i = 1; i < n; i++) res += 1;
  for (let i = 1; i < m; i++) res += n;
  return res === k ? 'YES' : 'NO';
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m, k] = (await read()).split(' ').map(Number);
      res[i] = solve(n, m, k);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

function solve(n, m, k) {
  const dp = Array.from({
    length: n
  }, () => new Array(m).fill(Infinity));
  dp[0][0] = 0;
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if (i === 0 && j === 0) continue;
      if (i > 0) dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + j + 1);
      if (j > 0) dp[i][j] = Math.min(dp[i][j], dp[i][j - 1] + i + 1);
    }
  }
  return dp[n - 1][m - 1] === k ? 'YES' : 'NO';
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m, k] = (await read()).split(' ').map(Number);
      res[i] = solve(n, m, k);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
var __webpack_exports__ = {};

;// CONCATENATED MODULE: ./src/io.js
var interact = function interact(main) {
  process.stdin.resume();
  process.stdin.setEncoding('utf-8');
  var inputString = '';
  var currentLine = 0;

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

  var print = function print() {
    for (var _len = arguments.length, any = new Array(_len), _key = 0; _key < _len; _key++) {
      any[_key] = arguments[_key];
    }

    process.stdout.write(any.join(' '));
  };

  var println = function println() {
    for (var _len2 = arguments.length, any = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      any[_key2] = arguments[_key2];
    }

    any.length > 0 && print(any);
    print('\n');
  };

  var obj = {
    print: print,
    println: println,
    readline: readline
  };
  process.stdin.on('data', function (inputStdin) {
    inputString += inputStdin;
  });
  process.stdin.on('end', function () {
    inputString = inputString.trim().split('\n').map(function (string) {
      return string.trim();
    });
    main(obj);
  });
};

/* harmony default export */ const io = (interact);
;// CONCATENATED MODULE: ./src/index.js
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var main = function main(io) {
  var tc = parseInt(io.readline());

  var _loop = function _loop() {
    var _io$readline$split$ma = io.readline().split(' ').map(function (x) {
      return parseInt(x);
    }),
        _io$readline$split$ma2 = _slicedToArray(_io$readline$split$ma, 3),
        n = _io$readline$split$ma2[0],
        m = _io$readline$split$ma2[1],
        k = _io$readline$split$ma2[2];

    var dp = Array.from(Array(1 + n), function () {
      return Array.from(Array(1 + m), function () {
        return Infinity;
      });
    }); // from (1,1) it is possible to use exactly
    // 0 burles to reach (1,1)

    dp[1][1] = 0;

    for (var i = 1; i <= n; i++) {
      for (var j = 1; j <= m; j++) {
        dp[i][j] = Math.min(dp[i][j], j + dp[i - 1][j], i + dp[i][j - 1]);
      }
    }

    io.println(dp[n][m] === k ? 'YES' : 'NO');
  };

  while (tc--) {
    _loop();
  }
};

io(main);
/******/ })()
;

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(var j = 1; j <= n; j++){
        var k = lines[j].split(' ').map(Number);
        var a = k[0];
        var b = k[1];
        var c = k[2];
        if(c == a * b - 1){
            console.log('YES');
        }else{
            console.log('NO');
        }
    }
});

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

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let i = 0; i < t; i++){
		let [n, m, k] = nl.nums();
		ans.push((n * m - 1) === k);
	}
	console.log(ans.map(e => e?"YES":"NO").join('\n'));
};

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

//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 getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------

function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var H = nextInt();
		var W = nextInt();
		var K = nextInt();
		if(H * W - 1 == K){
			myout("YES");
		}else{
			myout("NO");
		}
	}
}

'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(readLine());

    while(testCases--)
    {
        let [n,m,k] = get_ints();
        let [x,y] = [1,1];
        let burles = 0;
        while(x < n)
        {
            burles += y;
            x++;
        }
        while(y < m)
        {
            burles += x;
            y++;
        }
        burles === k ? print('YES') : print('NO');
    }
});

function print(c){
    return console.log(c);
}

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

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

process.stdin.setEncoding('utf-8')
const readline = require('readline')

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

let count = -1
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data
    } else if (count !== 0) {
        inputArr.push(data.trim())
        count--
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        inputArr = inputArr.map(i => i.split(' ').map(j => +j))
        main()
        process.exit(0)
    }
})

function solve([n, m, k]) {
    let a = n - 1 + (n * (m - 1));
    (a === k) ? console.log('YES') : console.log('NO')
}

function main() {
    for (let i = 0; i < inputArr.length; i++) solve(inputArr[i])
}

/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ 747:
/***/ ((module) => {

module.exports = require("fs");;

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {

// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(747);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
;// CONCATENATED MODULE: external "readline"
const external_readline_namespaceObject = require("readline");;
;// CONCATENATED MODULE: ./src/lib/io.ts

class InteractiveIO {
  constructor() {
    this.rl = void 0;
    this.lines = [];
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    this.rl.on('line', line => {
      this.lines.push(line);
    });
  }

  nextLine() {
    return new Promise((resolve, reject) => {
      if (this.lines.length) {
        resolve(this.lines.shift());
        return;
      }

      let waitId = null;
      let timeoutId = null;
      waitId = setInterval(() => {
        if (this.lines.length) {
          resolve(this.lines.shift());
          clearTimeout(timeoutId);
          clearInterval(waitId);
          return;
        }
      }, 1);
      timeoutId = setTimeout(() => {
        clearInterval(waitId);
        reject(new Error('timeout')); // resolve(null);
      }, 500);
    });
  }

  close() {
    this.rl.close();
  }

}
class IO {
  constructor() {
    this.i = 0;
    this.text = '';
    this.out = '';
    this.readInput();
  }

  readInput() {
    this.text = __webpack_require__(747).readFileSync(0, 'utf8');
  }

  nextToken() {
    let ret = '';

    while (this.text[this.i].charCodeAt(0) <= 32) {
      this.i++;
    }

    while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
      ret += this.text[this.i];
      this.i++;
    }

    return ret;
  }

  nextNum() {
    return Number(this.nextToken());
  }

  nextBigInt() {
    return BigInt(this.nextToken());
  }

  nextNumArray(n) {
    let ret = [];

    while (n--) {
      ret.push(this.nextNum());
    }

    return ret;
  }

  _write(x) {
    this.out += x;
  }

  write(x) {
    this._write(x + ' ');
  }

  writeLine(x) {
    this._write(x + '\n');
  }

  flush() {
    external_fs_default().writeFileSync(1, this.out);
    this.out = '';
  }

}
;// CONCATENATED MODULE: ./src/cf-1519/1519-b.ts

const io = new IO();

function solve(n, m, k) {
  let s = n - 1 + (m - 1) * n;

  if (k === s) {
    io.writeLine('YES');
  } else {
    io.writeLine('NO');
  }
}

function main() {
  try {
    let t = io.nextNum();

    while (t--) {
      let n = io.nextNum();
      let m = io.nextNum();
      let k = io.nextNum();
      solve(n, m, k);
    }

    io.flush();
  } catch (e) {
    console.log(e.stack);
  }
}

main();

})();

/******/ })()
;


There is a grid with $$$n$$$ rows and $$$m$$$ columns, and three types of cells:   An empty cell, denoted with '.'.  A stone, denoted with '*'.  An obstacle, denoted with the lowercase Latin letter 'o'. All stones fall down until they meet the floor (the bottom row), an obstacle, or other stone which is already immovable. (In other words, all the stones just fall down as long as they can fall.)Simulate the process. What does the resulting grid look like?

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 50$$$) — the number of rows and the number of columns in the grid, respectively. Then $$$n$$$ lines follow, each containing $$$m$$$ characters. Each of these characters is either '.', '*', or 'o' — an empty cell, a stone, or an obstacle, respectively.

For each test case, output a grid with $$$n$$$ rows and $$$m$$$ columns, showing the result of the process. You don't need to output a new line after each test, it is in the samples just for clarity.

'use strict';

const { domainToASCII } = require('url');

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

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

const to_s = (i, j)=>i*1000+j;
const calc = (n, m, G)=>{
  let iterate = ()=>{
    let NG = [];
    let flag;
    let dots = new Set();
    for (let i=n-1; i>=0; i--){
      let s = '';
      for (let j=0; j<m; j++){
        if ((G[i][j]=='.' || dots.has(to_s(i, j))) && i>0 && G[i-1][j]=='*'){
          dots.add(to_s(i-1, j));
          flag = true;
          s += '*';
        } else {
          s += dots.has(to_s(i, j)) ? '.' : G[i][j];
        }
      }
      NG.push(s);
    }
    //L('\nstart:'); L(NG.join('\n')); L('\nend:');
    G = NG.reverse();
    return flag
  };
  while (iterate());
  return G.join('\n');
  L({n, m, G})
};

function main() {
    let T = +readline()
    while (T--){
      let [n, m] = ra();
      let G = [];
      for (let i=0; i<n; i++){
        G.push(readline())
      }
      L('Ans:')
      print(calc(n, m, G));
    }
}

E.calc = calc;

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

let input = [];
let ans = [];

readline.on('line', line => {
    input.push(line);
}).on('close', () => {
    for (let i = 1; i < input.length; i++) {
        let [rows, cols] = input[i].split(' ').map(Number);

        let grid = input.slice(i+1, i+rows+1).map(v=>v.split(''));

        for (let col = 0; col < cols; col++) {
            for (let row = rows-2; row >= 0; row--) {
                if (grid[row][col] === '*') {
                    while (grid[row+1][col] === '.') {
                        [grid[row][col], grid[row+1][col]] = [grid[row+1][col], grid[row][col]];
                        if (row+1 < rows-1) row++;
                    }
                }
            }
        }
        ans.push(grid.map(v=>v.join('')).join('\n'));

        i+=rows;
    }
    console.log(ans.join('\n'));
});

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, m] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = [];
    for (let i = 0; i < n; i++) {
      arr.push(readline().trim().split(""));
    }
    for (let i = 0; i < m; i++) {
      let s = 0,
        j;
      for (j = 0; j < n; j++) {
        if (arr[j][i] === "*") {
          s++;
          arr[j][i] = ".";
        } else if (arr[j][i] === "o" && s != 0) {
          let k = j - 1;
          while (s--) arr[k--][i] = "*";
          s = 0;
        }
      }
      let k = j - 1;
      while (s--) arr[k--][i] = "*";
    }
    for (let i = 0; i < n; i++) console.log(arr[i].join(""));
  }
};
solve();

'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 _t = parseInt(readline());
  let a = [];
  while (_t) {
    _t -= 1;
    let nm = readline()
      .split(' ')
      .map((e) => parseInt(e));

    let n = nm[0];
    let m = nm[1];
    for (let i = 0; i < n; i++) {
      a[i] = readline();
    }
    let d = [];
    for (let j = 0; j < m; j++) {
      d[j] = [];
      let cur = 0;
      for (let i = 0; i < n; i++) {
        if (a[i][j] === '*') cur++;
        if (a[i][j] === 'o') {
          d[j].push(cur);
          cur = 0;
        }
      }
      d[j].push(cur);
    }

    let b = [];
    for (let i = 0; i < n; i++) b[i] = [];

    for (let j = 0; j < m; j++) {
      let cur = d[j].pop();
      for (let i = n - 1; i >= 0; i--) {
        b[i][j] = a[i][j];
        if (a[i][j] === 'o') {
          cur = d[j].pop();
          continue;
        }
        if (a[i][j] === '*') b[i][j] = '.';
        if (cur) {
          cur--;
          b[i][j] = '*';
        }
      }
    }
    for (let i = 0; i < n; i++) {
      console.log(b[i].join(''));
    }
  }
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const [n, m] = rna();
		const a = [];

		for (let i = 0; i < n; i++) {
			a[i] = rl().split('');
		}

		for (let j = 0; j < m; j++) {
			for (let i = 0; i < n; i++) {
				if (a[i][j] == '*') {
					for (let k = i + 1; k < n; k++) {
						if (a[k][j] == 'o') break;
						if (a[k][j] == '.') {
							a[k][j] = '*';
							a[i][j] = '.';
							break;
						}
					}
				}
			}
		}

		for (let i = 0; i < n; i++) {
			console.log(a[i].join(''));
		}
	}
}

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

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

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

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    // console.log(`DEBUG res`, res);
    return Math.round(res + 0.01);
}

const calc = (n, m, grid)=>{
    let result = new Array(n + 1).fill(0).map(() => new Array(m).fill('.'));
    for (let j = 0; j < m; j++) {
        result[n][j] = 'o';
    }
    grid.push(new Array(m).fill('o'));

    let stonesAbove = new Array(n + 1).fill(0).map(() => new Array(m).fill(0));

    for (let j = 0; j < m; j++) {
        let lasto = n;
        let count = 0;
        for (let i = n - 1; i >= 0; i--) {
            if (grid[i][j] === 'o') {
                stonesAbove[lasto][j] = count;
                count = 0;
                lasto = i;
            }
            if (grid[i][j] === '*') {
                count++;
            }
        }
        if (count > 0) {
            stonesAbove[lasto][j] = count;
        }
    }

    for (let j = 0; j < m; j++) {
        for (let i = n; i >= 0; i--) {
            if (grid[i][j] === 'o') result[i][j] = 'o';
            if (stonesAbove[i][j] > 0) {
                let count = stonesAbove[i][j];
                while(count--) {
                    i--;
                    result[i][j] = '*';
                }
            }
        }
    }

    result.pop();

    return result.map((s) => s.join('')).join('\n');
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let [n, m] = ra();
        let grid = [];
        for (let i = 0; i < n; i++) {
            grid.push(readline());
        }
        console.log(`${calc(n, m, grid)}`);
    }
}

'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 solve(n, m, a) {
  const res = Array.from({
    length: n
  }, () => new Array(m).fill('.'));
  const floors = new Array(m).fill(n - 1);
  for (let i = n - 1; i >= 0; i--) {
    for (let j = 0; j < m; j++) {
      if (a[i][j] === 'o') {
        res[i][j] = 'o';
        floors[j] = i - 1;
      } else if (a[i][j] === '*') {
        res[floors[j]][j] = '*';
        floors[j]--;
      }
    }
  }
  console.log(res.map(a => a.join('')).join('\n'));
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    let [n, m] = (await read()).split(' ').map(Number),
        a = [];
    let tmp = n;
    while (tmp--) {
      a.push(await read());
    }
    solve(n, m, a);
  }
}

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

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var M = nextInt();
		var map = new Array(N);
		for(var i = 0; i < N; i++){
			map[i] = nextCharArray();
		}
		map.push(new Array(M).fill("*"));
		for(var i = N - 1; i >= 0; i--){
			for(var j = 0; j < M; j++){
				if(map[i][j] == "*"){
					for(var k = i + 1; k <= N; k++){
						if(map[k][j] == "o" || map[k][j] == "*"){
							map[i][j] = ".";
							map[k - 1][j] = "*";
							break;
						}
					}
				}
			}
		}
		for(var i = 0; i < N; i++){
			myout(myconv(map[i], 0));
		}

	}
}

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

function solve(n, m, grid) {
    const ans = []
    for (let i = 0; i < n; i++) {
        ans[i] = []
        for (let j = 0; j < m; j++) {
            if (grid[i][j] === 'o') {
                ans[i][j] = 'o'
            } else {
                ans[i][j] = '.'
            }
        }
    }
    for (let i = n - 1; i >= 0; i--) {
        for (let j = 0; j < m; j++) {
            if (grid[i][j] === '*') {
                let k = i
                while (k + 1 < n && ans[k + 1][j] === '.') k++
                ans[k][j] = '*'
            }
        }
    }
    return ans.map(r => r.join('')).join('\n')
}