Pak Chanek has $$$n$$$ blank heart-shaped cards. Card $$$1$$$ is attached directly to the wall while each of the other cards is hanging onto exactly one other card by a piece of string. Specifically, card $$$i$$$ ($$$i > 1$$$) is hanging onto card $$$p_i$$$ ($$$p_i < i$$$).In the very beginning, Pak Chanek must write one integer number on each card. He does this by choosing any permutation $$$a$$$ of $$$[1, 2, \dots, n]$$$. Then, the number written on card $$$i$$$ is $$$a_i$$$.After that, Pak Chanek must do the following operation $$$n$$$ times while maintaining a sequence $$$s$$$ (which is initially empty):  Choose a card $$$x$$$ such that no other cards are hanging onto it.  Append the number written on card $$$x$$$ to the end of $$$s$$$.  If $$$x \neq 1$$$ and the number on card $$$p_x$$$ is larger than the number on card $$$x$$$, replace the number on card $$$p_x$$$ with the number on card $$$x$$$.  Remove card $$$x$$$. After that, Pak Chanek will have a sequence $$$s$$$ with $$$n$$$ elements. What is the maximum length of the longest non-decreasing subsequence$$$^\dagger$$$ of $$$s$$$ at the end if Pak Chanek does all the steps optimally?$$$^\dagger$$$ A sequence $$$b$$$ is a subsequence of a sequence $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$, $$$[4,3,1]$$$ and $$$[3,1]$$$, but not $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of heart-shaped cards. The second line contains $$$n - 1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$) describing which card that each card hangs onto.

Print a single integer — the maximum length of the longest non-decreasing subsequence of $$$s$$$ at the end if Pak Chanek does all the steps optimally.

NoteThe following is the structure of the cards in the first example.Pak Chanek can choose the permutation $$$a = [1, 5, 4, 3, 2, 6]$$$.Let $$$w_i$$$ be the number written on card $$$i$$$. Initially, $$$w_i = a_i$$$. Pak Chanek can do the following operations in order:  Select card $$$5$$$. Append $$$w_5 = 2$$$ to the end of $$$s$$$. As $$$w_4 > w_5$$$, the value of $$$w_4$$$ becomes $$$2$$$. Remove card $$$5$$$. After this operation, $$$s = [2]$$$.  Select card $$$6$$$. Append $$$w_6 = 6$$$ to the end of $$$s$$$. As $$$w_2 \leq w_6$$$, the value of $$$w_2$$$ is left unchanged. Remove card $$$6$$$. After this operation, $$$s = [2, 6]$$$.  Select card $$$4$$$. Append $$$w_4 = 2$$$ to the end of $$$s$$$. As $$$w_1 \leq w_4$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$4$$$. After this operation, $$$s = [2, 6, 2]$$$.  Select card $$$3$$$. Append $$$w_3 = 4$$$ to the end of $$$s$$$. As $$$w_2 > w_3$$$, the value of $$$w_2$$$ becomes $$$4$$$. Remove card $$$3$$$. After this operation, $$$s = [2, 6, 2, 4]$$$.  Select card $$$2$$$. Append $$$w_2 = 4$$$ to the end of $$$s$$$. As $$$w_1 \leq w_2$$$, the value of $$$w_1$$$ is left unchanged. Remove card $$$2$$$. After this operation, $$$s = [2, 6, 2, 4, 4]$$$.  Select card $$$1$$$. Append $$$w_1 = 1$$$ to the end of $$$s$$$. Remove card $$$1$$$. After this operation, $$$s = [2, 6, 2, 4, 4, 1]$$$. One of the longest non-decreasing subsequences of $$$s = [2, 6, 2, 4, 4, 1]$$$ is $$$[2, 2, 4, 4]$$$. Thus, the length of the longest non-decreasing subsequence of $$$s$$$ is $$$4$$$. It can be proven that this is indeed the maximum possible length.

'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 [rn, rb, rns, re, rbs] = convertInput(read);
  let n = rn(),
      a = rns();
  const h = new Array(n).fill(-1),
        ne = [];
  const add = (i, j) => (ne.push(h[i]), h[i] = ne.length - 1);
  for (let i = 0; i < n - 1; i++) {
    add(a[i] - 1);
  }
  const dp = new Array(n).fill(0),
        cnt = new Array(n).fill(0);
  for (let i = n - 1; i >= 0; i--) {
    const j = a[i - 1] - 1;
    cnt[i]++;
    cnt[j] = Math.max(cnt[j], cnt[i]);
    dp[j] += Math.max(dp[i], cnt[i]);
  }
  return Math.max(dp[0], cnt[0]);
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } 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);
}();

'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 [rn, rb, rns, re, rbs] = convertInput(read);
  let n = rn(),
      a = rns();
  const h = new Array(n).fill(-1),
        e = [],
        ne = [];
  const add = (i, j) => (e.push(j), ne.push(h[i]), h[i] = ne.length - 1);
  for (let i = 0; i < n - 1; i++) {
    add(a[i] - 1, i + 1);
  }
  const dp = new Array(n).fill(0),
        cnt = new Array(n).fill(0);
  const dfs = u => {
    for (let i = h[u]; ~i; i = ne[i]) {
      const v = e[i];
      dfs(v);
      cnt[u] = Math.max(cnt[u], cnt[v]);
      dp[u] += Math.max(dp[v], cnt[v]);
    }
    cnt[u]++;
  };
  dfs(0);
  return dp[0];
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } 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);
}();

'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 [rn, rb, rns, re, rbs] = convertInput(read);
  let n = rn(),
      a = rns();
  const h = new Array(n).fill(-1),
        e = [],
        ne = [];
  const add = (i, j) => (e.push(j), ne.push(h[i]), h[i] = ne.length - 1);
  for (let i = 0; i < n - 1; i++) {
    add(a[i] - 1, i + 1);
  }
  let res = 0;
  const dfs = u => {
    let ans = 0;
    for (let i = h[u]; ~i; i = ne[i]) {
      const v = e[i];
      let tmp = dfs(v);
      ans = Math.max(ans, tmp);
      if (!u) {
        res += tmp;
      }
    }
    return ans + 1;
  };
  dfs(0);
  return res;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } 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);
}();


On Bertown's main street n trees are growing, the tree number i has the height of ai meters (1 ≤ i ≤ n). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the n-th one) should be equal to each other, the heights of the 2-nd and the (n - 1)-th tree must also be equal to each other, at that the height of the 2-nd tree should be larger than the height of the first tree by 1, and so on. In other words, the heights of the trees, standing at equal distance from the edge (of one end of the sequence) must be equal to each other, and with the increasing of the distance from the edge by 1 the tree height must also increase by 1. For example, the sequences "2 3 4 5 5 4 3 2" and "1 2 3 2 1" are beautiful, and '1 3 3 1" and "1 2 3 1" are not. Changing the height of a tree is a very expensive operation, using advanced technologies invented by Berland scientists. In one operation you can choose any tree and change its height to any number, either increase or decrease. Note that even after the change the height should remain a positive integer, i. e, it can't be less than or equal to zero. Identify the smallest number of changes of the trees' height needed for the sequence of their heights to become beautiful.

The first line contains integer n (1 ≤ n ≤ 105) which is the number of trees. The second line contains integers ai (1 ≤ ai ≤ 105) which are the heights of the trees.

Print a single number which is the minimal number of trees whose heights will have to be changed for the sequence to become beautiful.

const readline = require('readline');

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

function f(n123, m) {
  const arr = m.split(' ');
  const n = arr.length;
  const n2 = Math.floor(n / 2);
  for(let i = 0; i < n2; i++) {
    arr[i] -= i;
    arr[n-i-1] -= i;
  }
  if(n % 2) {
    arr[n2] -= n2;
  }
  const obj = arr.reduce((obj, n) => {
    if(!obj[n]) {
      obj[n] = 0;
    }
    obj[n]++;
    return obj;
  }, {});
  const max = Math.max(...Object.entries(obj).filter(([e]) => e > 0).map(e => e[1]));
  return n - max;
}

rl.question('', n => {
  rl.question('', m => {
    console.log(f(n, m));

    rl.close();
    process.stdin.destroy();
  });
});

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

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

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

function main() {
	var n = parseInt(readline()),
		trees = tokenizeIntegers(readline()),
		counts = {}, max = 0,
		increment = 0,
		rise = Math.floor((n-1)/2), fall = Math.floor(n/2);
	for (var i = 0; i < n; ++i) {
		var value = trees[i]-increment;
		if (value > 0) {
			if (counts[value] === undefined) {
				counts[value] = 1;
			} else {
				counts[value] += 1;
			}
			max = Math.max(max, counts[value]);
		}
		if (i < rise) {
			++increment;
		} else if (i >= fall) {
			--increment;
		}
	}
	print(n - max);
}

main();

const readline = require('readline');

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

function f(n123, m) {
  const arr = m.split(' ');
  const n = arr.length;
  const n2 = Math.floor(n / 2);
  for(let i = 0; i < n2; i++) {
    arr[i] -= i;
    arr[n-i-1] -= i;
  }
  if(n % 2) {
    arr[n2] -= n2;
  }
  const obj = arr.reduce((obj, n) => {
    if(!obj[n]) {
      obj[n] = 0;
    }
    obj[n]++;
    return obj;
  }, {});
  const max = Math.max(...Object.values(obj));
  return n - max;
}

rl.question('', n => {
  rl.question('', m => {
    console.log(f(n, m));

    rl.close();
    process.stdin.destroy();
  });
});

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

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

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

function main() {
	var n = parseInt(readline()),
		trees = tokenizeIntegers(readline()),
		counts = {}, max = 0,
		increment = 0,
		rise = Math.floor((n-1)/2), fall = Math.floor(n/2);
	for (var i = 0; i < n; ++i) {
		var value = trees[i]-increment;
		if (counts[value] === undefined) {
			counts[value] = 1;
		} else {
			counts[value] += 1;
		}
		max = Math.max(max, counts[value]);
		if (i < rise) {
			++increment;
		} else if (i >= fall) {
			--increment;
		}
	}
	print(n - max);
}

main();


Hooray! Polycarp turned $$$n$$$ years old! The Technocup Team sincerely congratulates Polycarp!Polycarp celebrated all of his $$$n$$$ birthdays: from the $$$1$$$-th to the $$$n$$$-th. At the moment, he is wondering: how many times he turned beautiful number of years?According to Polycarp, a positive integer is beautiful if it consists of only one digit repeated one or more times. For example, the following numbers are beautiful: $$$1$$$, $$$77$$$, $$$777$$$, $$$44$$$ and $$$999999$$$. The following numbers are not beautiful: $$$12$$$, $$$11110$$$, $$$6969$$$ and $$$987654321$$$.Of course, Polycarpus uses the decimal numeral system (i.e. radix is 10).Help Polycarpus to find the number of numbers from $$$1$$$ to $$$n$$$ (inclusive) that are beautiful.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case consists of one line, which contains a positive integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — how many years Polycarp has turned.

Print $$$t$$$ integers — the answers to the given test cases in the order they are written in the test. Each answer is an integer: the number of beautiful years between $$$1$$$ and $$$n$$$, inclusive.

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

function Main() {
  var N = myconv(readline(),1);
  var output = [];
  for(var i = 0; i < N; i++){
      var year = myconv(readline(),0);
      if(parseInt(year) < 10){
          output.push(year);
      }else if(parseInt(year) == 10){
          output.push(9);
      }else{
          var counted = 9 * (year.length-1);
          var one = makeOne(year.length);
          output.push(counted + Math.floor(parseInt(year)/one));
      }
  }
  myout(output.join("\n"));
}

function makeOne(input){
    var ret = 0;
    for(var i = 1; i <= input; i++){
        ret = ret *10 + 1;
    }
    return ret;
}

Main();

'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 readALine() {
    return inputString[currentLine++];
}

function printALine(str) {
    console.log(str);
}

function stringArrayToNumbers(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( parseInt(array[i]) );
    }
    return result;
}

function stringArrayToBigInts(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( BigInt(array[i]) );
    }
    return result;
}

// ======================================================
// A. Happy Birthday, Polycarp!
// https://codeforces.com/problemset/problem/1277/A
// ======================================================

function doIt( num ) {

    var result = 0;
    if( num === 1 ) return 1;

    var divisor = 0;
    for( var i = 0; i < 10; i++ ) {

        divisor += Math.pow(10, i);

        var value = num / divisor;
        //printALine("num = " + num + " divisor=" + divisor + " value = " + value);
        if( value >= 10 ) {
            result += 9;
        } else {
            result += Math.floor( value );
            break;
        }

    }

    return result;

}

function main() {

    var numOfTests = parseInt(readALine());
    for( var i = 0; i < numOfTests; i++ ) {
        var num = parseInt(readALine());
        var result = doIt( num );
        printALine(result);
    }

}

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

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

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

  const t = parseInt(arr.shift())

  for(let j = 0; j < t; j++) {
    const n = parseInt(arr[j])
    let s = n.toString()
    let len = s.length
    let sum = 9 * (len - 1)

    let first = s[0]
    if(len == 1) {
      sum = n
      console.log(sum)
      continue
    }
    let i = 1
    for(i = 1; i < len; i++) {
      if(s[i] == s[i - 1]) continue
      else if(s[i] < s[i - 1]) {
        sum += parseInt(s[0]) - 1
        break
      }
      else if(s[i] > s[i - 1] && s[i] != 0) {
        sum += parseInt(s[0])
        break
      }
    }
    if(i == len) {
      sum += parseInt(s[0])
    }

    console.log(sum)

  }
})

'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 readALine() {
    return inputString[currentLine++];
}

function printALine(str) {
    console.log(str);
}

function stringArrayToNumbers(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( parseInt(array[i]) );
    }
    return result;
}

function stringArrayToBigInts(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( BigInt(array[i]) );
    }
    return result;
}

// ======================================================
// A. Happy Birthday, Polycarp!
// https://codeforces.com/problemset/problem/1277/A
// ======================================================

function doIt( num ) {

    var result = 0;
    if( num === 1 ) return 1;

    var divisor = 0;
    for( var i = 0; i < 10; i++ ) {

        divisor += Math.pow(10, i);

        var value = num / divisor;
        if( value > 10 ) {
            result += 9;
        } else {
            result += Math.floor( value );
            break;
        }

    }

    return result;

}

function main() {

    var numOfTests = parseInt(readALine());
    for( var i = 0; i < numOfTests; i++ ) {
        var num = parseInt(readALine());
        var result = doIt( num );
        printALine(result);
    }

}


Polycarp is wondering about buying a new computer, which costs $$$c$$$ tugriks. To do this, he wants to get a job as a programmer in a big company.There are $$$n$$$ positions in Polycarp's company, numbered starting from one. An employee in position $$$i$$$ earns $$$a[i]$$$ tugriks every day. The higher the position number, the more tugriks the employee receives. Initially, Polycarp gets a position with the number $$$1$$$ and has $$$0$$$ tugriks.Each day Polycarp can do one of two things:   If Polycarp is in the position of $$$x$$$, then he can earn $$$a[x]$$$ tugriks.  If Polycarp is in the position of $$$x$$$ ($$$x < n$$$) and has at least $$$b[x]$$$ tugriks, then he can spend $$$b[x]$$$ tugriks on an online course and move to the position $$$x+1$$$. For example, if $$$n=4$$$, $$$c=15$$$, $$$a=[1, 3, 10, 11]$$$, $$$b=[1, 2, 7]$$$, then Polycarp can act like this:   On the first day, Polycarp is in the $$$1$$$-st position and earns $$$1$$$ tugrik. Now he has $$$1$$$ tugrik;  On the second day, Polycarp is in the $$$1$$$-st position and move to the $$$2$$$-nd position. Now he has $$$0$$$ tugriks;  On the third day, Polycarp is in the $$$2$$$-nd position and earns $$$3$$$ tugriks. Now he has $$$3$$$ tugriks;  On the fourth day, Polycarp is in the $$$2$$$-nd position and is transferred to the $$$3$$$-rd position. Now he has $$$1$$$ tugriks;  On the fifth day, Polycarp is in the $$$3$$$-rd position and earns $$$10$$$ tugriks. Now he has $$$11$$$ tugriks;  On the sixth day, Polycarp is in the $$$3$$$-rd position and earns $$$10$$$ tugriks. Now he has $$$21$$$ tugriks;  Six days later, Polycarp can buy himself a new computer. Find the minimum number of days after which Polycarp will be able to buy himself a new computer.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le c \le 10^9$$$) — the number of positions in the company and the cost of a new computer. The second line of each test case contains $$$n$$$ integers $$$a_1 \le a_2 \le \ldots \le a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line of each test case contains $$$n - 1$$$ integer $$$b_1, b_2, \ldots, b_{n-1}$$$ ($$$1 \le b_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output the minimum number of days after which Polycarp will be able to buy a new computer.

var t = parseInt(readline());

for (var test = 0; test < t; test++) {
    var inp = readline().split(' ');
    var n = parseInt(inp[0]);
    var c = parseInt(inp[1]);
    var a = readline().split(' ');
    var b = readline().split(' ');

    var days = 0;
    var coins = 0;
    var ans = Infinity;

    for (var i = 0; i < n; i++) {
        ans = Math.min(ans, days + Math.ceil((c - coins) / a[i]));
        var day = Math.ceil((b[i] - coins) / a[i]);
        days += day + 1;
        coins = coins + day * a[i] - b[i];
    }

    print(ans);
}

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var [n, c] = lines[l++].split(' ').map(Number)
        var a = lines[l++].split(' ').map(Number)
        var b = lines[l++].split(' ').map(Number)
        console.log(solve(n, c, a, b))
    }
});

function solve(n, c, a, b) {
    let min = Infinity
    let cur = 0
    let days = 0
    for (let i = 0; i < n; i++) {
        const d1 = days + Math.ceil((c - cur) / a[i])
        min = Math.min(min, d1)
        if (i === n - 1) break

        // console.log(cur, days)
        const update = Math.ceil(Math.max(0, b[i] - cur) / a[i])
        days += update + 1
        cur += update * a[i] - b[i]
        // console.log('->', cur, days)
    }
    return min
}

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

var maxN = 21
var mod = 1000000007

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

function main() {
  const xx = readline();

  Array(Number(xx)).fill(1).map((t, i) => {
    // var n = parseInt(readline());
    var [n, c] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    });
    var a = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    });
    var b = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })
    var ans = c
    var day = 0
    var addDays = 0
    var money = 0

    for (let j = 0; j < n; j++) {
      ans = Math.min(ans, day + Math.ceil((c - money) / a[j]))
      if (j < n - 1) {
        if (money < b[j]) {
          addDays = Math.ceil((b[j] - money) / a[j])
          day = day + addDays
          money = money + addDays * a[j]
        }
        // console.log(addDays)
        day++
        money -= b[j]
      }
      // console.log(day, money, ans)
    }

    console.log(ans)
  })
}


Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters.The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let's assume that the point $$$x = 0$$$ is where these parts meet.The right part of the corridor is filled with $$$n$$$ monsters — for each monster, its initial coordinate $$$x_i$$$ is given (and since all monsters are in the right part, every $$$x_i$$$ is positive).The left part of the corridor is filled with crusher traps. If some monster enters the left part of the corridor or the origin (so, its current coordinate becomes less than or equal to $$$0$$$), it gets instantly killed by a trap.The main weapon Ivan uses to kill the monsters is the Phoenix Rod. It can launch a missile that explodes upon impact, obliterating every monster caught in the explosion and throwing all other monsters away from the epicenter. Formally, suppose that Ivan launches a missile so that it explodes in the point $$$c$$$. Then every monster is either killed by explosion or pushed away. Let some monster's current coordinate be $$$y$$$, then:  if $$$c = y$$$, then the monster is killed;  if $$$y < c$$$, then the monster is pushed $$$r$$$ units to the left, so its current coordinate becomes $$$y - r$$$;  if $$$y > c$$$, then the monster is pushed $$$r$$$ units to the right, so its current coordinate becomes $$$y + r$$$. Ivan is going to kill the monsters as follows: choose some integer point $$$d$$$ and launch a missile into that point, then wait until it explodes and all the monsters which are pushed to the left part of the corridor are killed by crusher traps, then, if at least one monster is still alive, choose another integer point (probably the one that was already used) and launch a missile there, and so on.What is the minimum number of missiles Ivan has to launch in order to kill all of the monsters? You may assume that every time Ivan fires the Phoenix Rod, he chooses the impact point optimally.You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. The first line of each query contains two integers $$$n$$$ and $$$r$$$ ($$$1 \le n, r \le 10^5$$$) — the number of enemies and the distance that the enemies are thrown away from the epicenter of the explosion. The second line of each query contains $$$n$$$ integers $$$x_i$$$ ($$$1 \le x_i \le 10^5$$$) — the initial positions of the monsters. It is guaranteed that sum of all $$$n$$$ over all queries does not exceed $$$10^5$$$.

For each query print one integer — the minimum number of shots from the Phoenix Rod required to kill all monsters.

NoteIn the first test case, Ivan acts as follows:   choose the point $$$3$$$, the first monster dies from a crusher trap at the point $$$-1$$$, the second monster dies from the explosion, the third monster is pushed to the point $$$7$$$;  choose the point $$$7$$$, the third monster dies from the explosion. In the second test case, Ivan acts as follows:   choose the point $$$5$$$, the first and fourth monsters die from the explosion, the second monster is pushed to the point $$$1$$$, the third monster is pushed to the point $$$2$$$;  choose the point $$$2$$$, the first monster dies from a crusher trap at the point $$$0$$$, the second monster dies from the explosion.

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (count, distance, positions) {
        const hashMap = {};

        positions.forEach((pos) => {
            hashMap[pos] = true;
        });

        let kills = 0;
        let doKill = true;
        let keys = Object.keys(hashMap);

        while(doKill) {
            kills++;
            let max = keys[keys.length - kills];
            delete hashMap[max];
            max = keys[keys.length - kills - 1];
            doKill = max - kills * distance > 0;
        }
        return kills;
    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let positions = lines[testCount * 2].split(" ").map(Number);
        let row1 = lines[testCount * 2 - 1].split(" ").map(Number);
        let result = foo(row1[0], row1[1], positions);
        answer += result +"\n";
        testCount++;
    }
    console.log(answer);

})

'use strict'

const q = parseInt(readline());

const fn = (n, r, x) => {
    let i = 0;
    while (x[i] - i * r > 0) i++;
    return i;
}

for(let i = 0; i < q; i++) {
    const nr = readline().split(' ');
    const x = [ ...(new Set(readline().split(' ')))].sort((A, B) => B - A);
    print(fn(nr[0], nr[1], x));
}

function merge(leftArr, rightArr) {
  var sortedArr = [];
  while (leftArr.length && rightArr.length) {
    if (leftArr[0] <= rightArr[0]) {
      sortedArr.push(leftArr[0]);
      leftArr = leftArr.slice(1)
   } else {
      sortedArr.push(rightArr[0]);
      rightArr = rightArr.slice(1)
     }
   }
  while (leftArr.length)
    sortedArr.push(leftArr.shift());
  while (rightArr.length)
    sortedArr.push(rightArr.shift());
  return sortedArr;
}

function mergeSort(arr) {
  if (arr.length < 2) {
    return arr; }
  else {
    var midpoint = parseInt(arr.length / 2);
    var leftArr   = arr.slice(0, midpoint);
    var rightArr  = arr.slice(midpoint, arr.length);
    return merge(mergeSort(leftArr), mergeSort(rightArr));
  }
}

var queriesCount = parseInt(readline());

var queries = [];

for (var i = 0; i < queriesCount; i++) {
  queries.push([]);
  queries[i].push(readline().split(' ').map(function(num) {
    return parseInt(num);
  }))
  queries[i].push(readline().split(' ').map(function(num) {
    return parseInt(num);
  }))
}

// var queries = [[[4, 2], [1, 6, 6, 6, 6, 2]], [[3, 2], [1, 3, 5]]];
// var queriesCount = 2

function main(positions, queryParams) {
  var prevNum = undefined;
  positions = positions.sort(function(a, b) {
    return (a < b) ? -1 : 1;
  });
  var numOfShots = 0;
  var r = queryParams[1];
  var accum = 0;
  for (var j = positions.length - 1; j > -1 ; j--) {
    if (positions[j] === prevNum) {
      continue;
    }
    else if (positions[j] - accum <= 0) {
      return write('' + numOfShots + '\n');
    }
    else {
      prevNum = positions[j];
      accum += r;
      numOfShots++;
    }
  }
  return write('' + numOfShots + '\n');
}

for (var i = 0; i < queriesCount; i++) {
  var positions = queries[i][1]
  var queryParams = queries[i][0]
  main(positions, queryParams);
}

const readline = require("readline").createInterface(process.stdin, process.stdout);

const solution = (function* (){
  let result = '',
      lines = yield;
  while (lines--){
    let [n, r] = (yield).split(' '),
        coordinates = [...(new Set((yield).split(' ').sort((a,b) => a - b)))],
        i = 0;

    while ((coordinates.pop() - r * i) > 0)
      i++;

    result += i + '\n';
  }
  console.log(result);
  process.exit(0);
})()
solution.next();

readline.on("line", line => solution.next(line));

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (count, distance, positions) {

        positions = positions.sort((a, b) => a - b);

        let kills = 0;
        function doKill() {
            kills++;
            positions.pop();
            positions.forEach((pos) => pos - distance);
            positions.filter((pos) => pos > 0);
            if (positions.length) doKill();
        }
        doKill();
        return kills;
    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let row1 = lines[testCount * 2].split(" ").map(Number);
        let positions = lines[testCount * 2 - 1].split(" ").map(Number);

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

'use strict'

const q = parseInt(readline());

const fn = (n, r, x) => {
    let i = 0;
    while (x[i] - i * r > 0) i++;
    return i;
}

for(let i = 0; i < q; i++) {
    const nr = readline().split(' ');
    const x = readline().split(' ').sort((A, B) => B - A);
    print(fn(nr[0], nr[1], x));
}

function merge(leftArr, rightArr) {
  var sortedArr = [];
  while (leftArr.length && rightArr.length) {
    if (leftArr[0] <= rightArr[0]) {
      sortedArr.push(leftArr[0]);
      leftArr = leftArr.slice(1)
   } else {
      sortedArr.push(rightArr[0]);
      rightArr = rightArr.slice(1)
     }
   }
  while (leftArr.length)
    sortedArr.push(leftArr.shift());
  while (rightArr.length)
    sortedArr.push(rightArr.shift());
  return sortedArr;
}

function mergeSort(arr) {
  if (arr.length < 2) {
    return arr; }
  else {
    var midpoint = parseInt(arr.length / 2);
    var leftArr   = arr.slice(0, midpoint);
    var rightArr  = arr.slice(midpoint, arr.length);
    return merge(mergeSort(leftArr), mergeSort(rightArr));
  }
}

var queriesCount = parseInt(readline());

var queries = [];

for (var i = 0; i < queriesCount; i++) {
  queries.push([]);
  queries[i].push(readline().split(' ').map(function(num) {
    return parseInt(num);
  }))
  queries[i].push(readline().split(' ').map(function(num) {
    return parseInt(num);
  }))
}

// var queries = [[[4, 1], [5, 2, 3, 5, 6]]];
// var queriesCount = 1

function main(positions, queryParams) {
  var prevNum = undefined;
  mergeSort(positions);
  var numOfShots = 0;
  var r = queryParams[1];
  var accum = 0;
  for (var j = positions.length - 1; j > -1 ; j--) {
    if (positions[j] === prevNum) {
      accum -= r;
      continue;
    }
    else if (positions[j] - accum <= 0) {
      return write('' + numOfShots);
    }
    else {
      prevNum = positions[j];
      accum += r;
      numOfShots++;
    }
  }
  return write('' + numOfShots)
}

for (var i = 0; i < queriesCount; i++) {
  var positions = queries[i][1]
  var queryParams = queries[i][0]
  main(positions, queryParams);
}

function merge(leftArr, rightArr) {
  var sortedArr = [];
  while (leftArr.length && rightArr.length) {
    if (leftArr[0] <= rightArr[0]) {
      sortedArr.push(leftArr[0]);
      leftArr = leftArr.slice(1)
   } else {
      sortedArr.push(rightArr[0]);
      rightArr = rightArr.slice(1)
     }
   }
  while (leftArr.length)
    sortedArr.push(leftArr.shift());
  while (rightArr.length)
    sortedArr.push(rightArr.shift());
  return sortedArr;
}

function mergeSort(arr) {
  if (arr.length < 2) {
    return arr; }
  else {
    var midpoint = parseInt(arr.length / 2);
    var leftArr   = arr.slice(0, midpoint);
    var rightArr  = arr.slice(midpoint, arr.length);
    return merge(mergeSort(leftArr), mergeSort(rightArr));
  }
}

var queriesCount = parseInt(readline());

var queries = [];

for (var i = 0; i < queriesCount; i++) {
  queries.push([]);
  queries[i].push(readline().split(' ').map(function(num) {
    return parseInt(num);
  }))
  queries[i].push(readline().split(' ').map(function(num) {
    return parseInt(num);
  }))
}

// var queries = [[[4, 1], [1, 6, 6, 6, 6]], [[3, 2], [1, 3, 5]]];
// var queriesCount = 2

function main(positions, queryParams) {
  var prevNum = undefined;
  mergeSort(positions);
  var numOfShots = 0;
  var r = queryParams[1];
  var accum = 0;
  for (var j = positions.length - 1; j > -1 ; j--) {
    if (positions[j] === prevNum) {
      continue;
    }
    else if (positions[j] - accum <= 0) {
      return write('' + numOfShots + '\n');
    }
    else {
      prevNum = positions[j];
      accum += r;
      numOfShots++;
    }
  }
  return write('' + numOfShots + '\n');
}

for (var i = 0; i < queriesCount; i++) {
  var positions = queries[i][1]
  var queryParams = queries[i][0]
  main(positions, queryParams);
}

function merge(leftArr, rightArr) {
  var sortedArr = [];
  while (leftArr.length && rightArr.length) {
    if (leftArr[0] <= rightArr[0]) {
      sortedArr.push(leftArr[0]);
      leftArr = leftArr.slice(1)
   } else {
      sortedArr.push(rightArr[0]);
      rightArr = rightArr.slice(1)
     }
   }
  while (leftArr.length)
    sortedArr.push(leftArr.shift());
  while (rightArr.length)
    sortedArr.push(rightArr.shift());
  return sortedArr;
}

function mergeSort(arr) {
  if (arr.length < 2) {
    return arr; }
  else {
    var midpoint = parseInt(arr.length / 2);
    var leftArr   = arr.slice(0, midpoint);
    var rightArr  = arr.slice(midpoint, arr.length);
    return merge(mergeSort(leftArr), mergeSort(rightArr));
  }
}

var queriesCount = parseInt(readline());

var queries = [];

for (var i = 0; i < queriesCount; i++) {
  queries.push([]);
  queries[i].push(readline().split(' ').map(function(num) {
    return parseInt(num);
  }))
  queries[i].push(readline().split(' ').map(function(num) {
    return parseInt(num);
  }))
}

// var queries = [[[4, 1], [5, 2, 3, 5, 6]], [[3, 2], [1, 3, 5]]];
// var queriesCount = 2

function main(positions, queryParams) {
  var prevNum = undefined;
  mergeSort(positions);
  var numOfShots = 0;
  var r = queryParams[1];
  var accum = 0;
  for (var j = positions.length - 1; j > -1 ; j--) {
    if (positions[j] === prevNum) {
      accum -= r;
      continue;
    }
    else if (positions[j] - accum <= 0) {
      return write('' + numOfShots + '\n');
    }
    else {
      prevNum = positions[j];
      accum += r;
      numOfShots++;
    }
  }
  return write('' + numOfShots + '\n')
}

for (var i = 0; i < queriesCount; i++) {
  var positions = queries[i][1]
  var queryParams = queries[i][0]
  main(positions, queryParams);
}

function merge(leftArr, rightArr) {
  var sortedArr = [];
  while (leftArr.length && rightArr.length) {
    if (leftArr[0] <= rightArr[0]) {
      sortedArr.push(leftArr[0]);
      leftArr = leftArr.slice(1)
   } else {
      sortedArr.push(rightArr[0]);
      rightArr = rightArr.slice(1)
     }
   }
  while (leftArr.length)
    sortedArr.push(leftArr.shift());
  while (rightArr.length)
    sortedArr.push(rightArr.shift());
  return sortedArr;
}

function mergeSort(arr) {
  if (arr.length < 2) {
    return arr; }
  else {
    var midpoint = parseInt(arr.length / 2);
    var leftArr   = arr.slice(0, midpoint);
    var rightArr  = arr.slice(midpoint, arr.length);
    return merge(mergeSort(leftArr), mergeSort(rightArr));
  }
}

var queriesCount = parseInt(readline());

var queries = [];

for (var i = 0; i < queriesCount; i++) {
  queries.push([]);
  queries[i].push(readline().split(' ').map(function(num) {
    return parseInt(num);
  }))
  queries[i].push(readline().split(' ').map(function(num) {
    return parseInt(num);
  }))
}

// var queries = [[[4, 1], [5, 2, 3, 5, 6]], [[3, 2], [1, 3, 5]]];
// var queriesCount = 2

function main(positions, queryParams) {
  var prevNum = undefined;
  mergeSort(positions);
  var numOfShots = 0;
  var r = queryParams[1];
  var accum = 0;
  for (var j = positions.length - 1; j > -1 ; j--) {
    if (positions[j] === prevNum) {
      accum -= r;
      continue;
    }
    else if (positions[j] - accum <= 0) {
      return write(numOfShots);
    }
    else {
      prevNum = positions[j];
      accum += r;
      numOfShots++;
    }
  }
  return write(numOfShots)
}

for (var i = 0; i < queriesCount; i++) {
  var positions = queries[i][1]
  var queryParams = queries[i][0]
  main(positions, queryParams);
}


Theofanis has a riddle for you and if you manage to solve it, he will give you a Cypriot snack halloumi for free (Cypriot cheese).You are given an integer $$$n$$$. You need to find two integers $$$l$$$ and $$$r$$$ such that $$$-10^{18} \le l < r \le 10^{18}$$$ and $$$l + (l + 1) + \ldots + (r - 1) + r = n$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first and only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^{18}$$$).

For each test case, print the two integers $$$l$$$ and $$$r$$$ such that $$$-10^{18} \le l < r \le 10^{18}$$$ and $$$l + (l + 1) + \ldots + (r - 1) + r = n$$$.  It can be proven that an answer always exists. If there are multiple answers, print any.

// dist/FinalCode/Common/InputOutputClass.js
var Input = function() {
  function Input2(inputData) {
    var _this = this;
    this.SettleStream = function() {
      var re = /\s+/;
      _this.inputWords = _this.inputStream.split(re);
      _this.inputWordsLength = _this.inputWords.length;
    };
    this.getLength = function() {
      return _this.inputWordsLength;
    };
    this.getEveryWord = function() {
      return _this.inputWords;
    };
    this.getNextWord = function() {
      _this.inputWordsCount++;
      if (_this.inputWordsLength < _this.inputWordsCount) {
        return "";
      }
      return _this.inputWords[_this.inputWordsCount - 1];
    };
    this.getNextString = function() {
      return _this.getNextWord();
    };
    this.getNextBigInt = function() {
      return BigInt(_this.getNextWord());
    };
    this.getNextNumber = function() {
      return Number(_this.getNextWord());
    };
    this.getNextInt = function() {
      return parseInt(_this.getNextWord(), 10);
    };
    this.getNextFloat = function() {
      return parseFloat(_this.getNextWord());
    };
    this.inputWordsCount = 0;
    this.inputStream = inputData;
  }
  Input2.prototype.SetStream = function(chunk) {
    this.inputStream += chunk;
  };
  return Input2;
}();
var InputOutputClass_default = Input;
var writeLine = function(outputElement) {
  var _internalWrite = function(_internalOutputElement) {
    process.stdout.write(_internalOutputElement);
  };
  _internalWrite(String(outputElement) + "\n");
};

// dist/main.js
var rw = new InputOutputClass_default("");
process.stdin.resume();
process.stdin.setEncoding("utf-8");
process.stdin.on("data", function(chunk) {
  rw.SetStream(chunk);
});
process.stdin.on("end", function() {
  rw.SettleStream();
  mainFunc();
});
var mainFunc = function() {
  testCases();
};
var testCases = function() {
  var test = rw.getNextInt();
  for (var i = 0; i < test; i++) {
    solveCase();
  }
};
var solveCase = function() {
  var num = rw.getNextString();
  writeLine(-BigInt(num) + BigInt(1) + " " + num);
};

var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};

// dist/FinalCode/Common/InputOutputClass.js
var require_InputOutputClass = __commonJS({
  "dist/FinalCode/Common/InputOutputClass.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.IOThings = exports2.writeLine = void 0;
    var Input = class {
      constructor(inputData) {
        this.SettleStream = () => {
          const re = /\s+/;
          this.inputWords = this.inputStream.split(re);
          this.inputWordsLength = this.inputWords.length;
        };
        this.getLength = () => {
          return this.inputWordsLength;
        };
        this.getEveryWord = () => {
          return this.inputWords;
        };
        this.getNextWord = () => {
          this.inputWordsCount++;
          if (this.inputWordsLength < this.inputWordsCount) {
            return "";
          }
          return this.inputWords[this.inputWordsCount - 1];
        };
        this.getNextString = () => {
          return this.getNextWord();
        };
        this.getNextBigInt = () => {
          return BigInt(this.getNextWord());
        };
        this.getNextNumber = () => {
          return Number(this.getNextWord());
        };
        this.getNextInt = () => {
          return parseInt(this.getNextWord(), 10);
        };
        this.getNextFloat = () => {
          return parseFloat(this.getNextWord());
        };
        this.inputWordsCount = 0;
        this.inputStream = inputData;
      }
      SetStream(chunk) {
        this.inputStream += chunk;
      }
    };
    exports2.default = Input;
    var writeLine = (outputElement) => {
      const _internalWrite = (_internalOutputElement) => {
        process.stdout.write(_internalOutputElement);
      };
      _internalWrite(String(outputElement) + "\n");
    };
    exports2.writeLine = writeLine;
    var IOThings = () => {
      const rw2 = new Input("");
      process.stdin.resume();
      process.stdin.setEncoding("utf-8");
      process.stdin.on("data", (chunk) => {
        rw2.SetStream(chunk);
      });
      process.stdin.on("end", () => {
        rw2.SettleStream();
      });
      return rw2;
    };
    exports2.IOThings = IOThings;
  }
});

// dist/main.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var InputOutputClass_1 = require_InputOutputClass();
var rw = new InputOutputClass_1.default("");
process.stdin.resume();
process.stdin.setEncoding("utf-8");
process.stdin.on("data", (chunk) => {
  rw.SetStream(chunk);
});
process.stdin.on("end", () => {
  rw.SettleStream();
  mainFunc();
});
var mainFunc = () => {
  testCases();
};
var testCases = () => {
  const test = rw.getNextInt();
  for (let i = 0; i < test; i++) {
    solveCase();
  }
};
var solveCase = () => {
  const num = rw.getNextString();
  (0, InputOutputClass_1.writeLine)(`${-BigInt(num) + BigInt(1)} ${num}`);
};

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 => BigInt(i))
        main()
        process.exit(0)
    }
})

function solve(num) {
    console.log((-num + 1n).toString() + ' ' + num.toString())
}

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

'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++];
}
/**
7
1
2
3
6
100
25
3000000000000

**/

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

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

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

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

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

}

function solve() {
    let n = BigInt(readline());

    let a = n;
    let b = -(n-BigInt(1));

    console.log(`${b} ${a}`);

}

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 = nl.elem(BigInt);
		if (n > 0) {
			ans.push([-n + 1n, n]);
		} else {
			ans.push([n, -n - 1n]);
		}
	}
	console.log(ans.map(e => e.join(' ')).join('\n'));
};

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

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++]
    for (let i = 0; i < t; i++) {
        const n = BigInt(lines[l++])
        console.log(solve(n).join(' '))
    }
// })()
})

function solve(n) {
    if (isOdd(n)) {
        return [(n - 1n) / 2n, (n + 1n) / 2n]
    } else {
        // const count = 2n * n
        return [-n + 1n, n]
        // let k = n / 2n
        // while (!isOdd(k)) k /= 2n

        // const count = k
        // const sum = 2n * n / count
        // // 2 * l + count - 1 = sum
        // const l = sum + 1n - count
        // return [l, l + count - 1n]
    }
}
function isOdd(n) {
    return n / 2n === (n - 1n) / 2n
}

var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};

// dist/FinalCode/Common/InputOutputClass.js
var require_InputOutputClass = __commonJS({
  "dist/FinalCode/Common/InputOutputClass.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.IOThings = exports2.writeLine = void 0;
    var Input = class {
      constructor(inputData) {
        this.SettleStream = () => {
          const re = /\s+/;
          this.inputWords = this.inputStream.split(re);
          this.inputWordsLength = this.inputWords.length;
        };
        this.getLength = () => {
          return this.inputWordsLength;
        };
        this.getEveryWord = () => {
          return this.inputWords;
        };
        this.getNextWord = () => {
          this.inputWordsCount++;
          if (this.inputWordsLength < this.inputWordsCount) {
            return "";
          }
          return this.inputWords[this.inputWordsCount - 1];
        };
        this.getNextString = () => {
          return this.getNextWord();
        };
        this.getNextBigInt = () => {
          return BigInt(this.getNextWord());
        };
        this.getNextNumber = () => {
          return Number(this.getNextWord());
        };
        this.getNextInt = () => {
          return parseInt(this.getNextWord(), 10);
        };
        this.getNextFloat = () => {
          return parseFloat(this.getNextWord());
        };
        this.inputWordsCount = 0;
        this.inputStream = inputData;
      }
      SetStream(chunk) {
        this.inputStream += chunk;
      }
    };
    exports2.default = Input;
    var writeLine = (outputElement) => {
      const _internalWrite = (_internalOutputElement) => {
        process.stdout.write(_internalOutputElement);
      };
      _internalWrite(String(outputElement) + "\n");
    };
    exports2.writeLine = writeLine;
    var IOThings = () => {
      const rw2 = new Input("");
      process.stdin.resume();
      process.stdin.setEncoding("utf-8");
      process.stdin.on("data", (chunk) => {
        rw2.SetStream(chunk);
      });
      process.stdin.on("end", () => {
        rw2.SettleStream();
      });
      return rw2;
    };
    exports2.IOThings = IOThings;
  }
});

// dist/main.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var InputOutputClass_1 = require_InputOutputClass();
var rw = new InputOutputClass_1.default("");
process.stdin.resume();
process.stdin.setEncoding("utf-8");
process.stdin.on("data", (chunk) => {
  rw.SetStream(chunk);
});
process.stdin.on("end", () => {
  rw.SettleStream();
  mainFunc();
});
var mainFunc = () => {
  testCases();
};
var testCases = () => {
  const test = rw.getNextInt();
  for (let i = 0; i < test; i++) {
    solveCase();
  }
};
var solveCase = () => {
  const num = rw.getNextString();
  (0, InputOutputClass_1.writeLine)(`-${BigInt(num) - BigInt(1)} ${num}`);
};

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 => BigInt(i))
        main()
        process.exit(0)
    }
})

function solve(num) {
    const a1 = num / 2n
    const a2 = num % 2n === 0n ? num / 2n : num / 2n + 1n
    console.log(a1.toString() + ' ' + a2.toString())
}

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

'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++];
}
/**
7
1
2
3
6
100
25
3000000000000

**/

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

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

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

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

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

}

function solve() {
    let n = Number(readline());
    if(n === 1) {
        console.log("0 1");
        return;
    }

    let a = n;
    let b = -(n-1);

    console.log(`${b} ${a}`);

}


A Pythagorean triple is a triple of integer numbers $$$(a, b, c)$$$ such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to $$$a$$$, $$$b$$$ and $$$c$$$, respectively. An example of the Pythagorean triple is $$$(3, 4, 5)$$$.Vasya studies the properties of right triangles, and he uses a formula that determines if some triple of integers is Pythagorean. Unfortunately, he has forgotten the exact formula; he remembers only that the formula was some equation with squares. So, he came up with the following formula: $$$c = a^2 - b$$$.Obviously, this is not the right formula to check if a triple of numbers is Pythagorean. But, to Vasya's surprise, it actually worked on the triple $$$(3, 4, 5)$$$: $$$5 = 3^2 - 4$$$, so, according to Vasya's formula, it is a Pythagorean triple.When Vasya found the right formula (and understood that his formula is wrong), he wondered: how many are there triples of integers $$$(a, b, c)$$$ with $$$1 \le a \le b \le c \le n$$$ such that they are Pythagorean both according to his formula and the real definition? He asked you to count these triples.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, print one integer — the number of triples of integers $$$(a, b, c)$$$ with $$$1 \le a \le b \le c \le n$$$ such that they are Pythagorean according both to the real definition and to the formula Vasya came up with.

NoteThe only Pythagorean triple satisfying $$$c = a^2 - b$$$ with $$$1 \le a \le b \le c \le 9$$$ is $$$(3, 4, 5)$$$; that's why the answer for $$$n = 3$$$ is $$$0$$$, and the answer for $$$n = 6$$$ (and for $$$n = 9$$$) is $$$1$$$.

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

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

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

		cmx = n;
		bmx = cmx - 1;
		amx = Math.floor(Math.sqrt(2*bmx + 1));

		ans = Math.ceil(amx/2) - 1;

		console.log(ans);
	}
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

function main() {
    var x = Number(readline())
    Array(Number(x)).fill(1).map((t, i) => {
        var n = parseInt(readline())
        var sqrt = Math.floor(Math.sqrt(n))

        // for (var i = 1; i <= 100; i++) {
        //     var ss = Math.floor(Math.sqrt(2 * i + 1))
            //
            // if (ss * ss === 2 * i + 1 && ss * ss + i * i === (i + 1) * (i + 1)) {
            //     console.log(ss, i, i + 1)
            //     count++
            // }
        // }

        var i = sqrt
        var b = Math.ceil(i-1/2)

        while (b<=n){
            i++
            b = Math.ceil((i*i-1)/2)+1
        }
        console.log(Math.floor(i /2)-1)

        // for (var i = 3; i*i <= n*4; i=i+2) {
        //     var b = Math.floor((i*i-1)/2)
// console.log(i*i, b,b+1)
//         if(b*2+1===i*i && b*2+1 <= n && b>0) {
//             console.log(i,b,b+1 )
//             count++
//         }
//         }
        // var mid = Math.fl/oor(n/2)
        // var res = Math.floor((k-1) / mid)

    })

}

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

    return gcd(b, a % b);
}


Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:Given two binary numbers $$$a$$$ and $$$b$$$ of length $$$n$$$. How many different ways of swapping two digits in $$$a$$$ (only in $$$a$$$, not $$$b$$$) so that bitwise OR of these two numbers will be changed? In other words, let $$$c$$$ be the bitwise OR of $$$a$$$ and $$$b$$$, you need to find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will not be equal to $$$c$$$.Note that binary numbers can contain leading zeros so that length of each number is exactly $$$n$$$.Bitwise OR is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, $$$01010_2$$$ OR $$$10011_2$$$ = $$$11011_2$$$.Well, to your surprise, you are not Rudolf, and you don't need to help him$$$\ldots$$$ You are the security staff! Please find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will be changed.

The first line contains one integer $$$n$$$ ($$$2\leq n\leq 10^5$$$) — the number of bits in each number. The second line contains a binary number $$$a$$$ of length $$$n$$$. The third line contains a binary number $$$b$$$ of length $$$n$$$.

Print the number of ways to swap two bits in $$$a$$$ so that bitwise OR will be changed.

function main() {
  const is = new Scanner();
  const n = is.nextInt();
  const a = is.nextLine();
  const b = is.nextLine();
  let answer = 0, aux = 0;
  let zerosA = 0, onesA = 0;
  let zerosB = 0, onesB = 0;
  for (let i = 0; i < n; i += 1) {
    if (a[i] === '0' && b[i] === '0' || a[i] === '1' && b[i] === '0') {
      if (a[i] === '0')
        zerosB++;
      if (a[i] === '1')
        onesB++;
    }
    else {
      if (a[i] === '0')
        zerosA++;
      if (a[i] === '1')
        onesA++;
    }
      answer += 1;
  }
  answer = zerosB * onesB;
  answer += onesA * zerosB;
  answer += onesB * zerosA;

  console.log(answer);
}

/*
 *  Api Scanner
 */
class Scanner {
  constructor() {
    this.index = -1;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    this.index += 1;
    return this.lines[this.index].trim();
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray(fn) {
    const array = this.nextLine().split(' ');
    return fn === String ? array : array.map(fn);
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

const vIn = [];
let itIn = 0;
const getNext = () => vIn[itIn++];
const getInt = () => parseInt(getNext(), 10);
const forEachN = (n, cb, flagInt = false) => {
  const nextItIn = itIn + n;
  const fn = flagInt ? getInt : getNext;
  while (itIn !== nextItIn) cb(fn());
};

class SolveProblemClass {
  constructor() {
  }

  solveAll() {
    const n = getInt();
    const a = getNext();
    const b = getNext();
    let aOnes = 0;
    for (let i = 0; i < n ; i++) if (a[i] === '1') aOnes++;
    const aCero = n - aOnes;
    let old = [0, 0];
    let total = 0;
    for (let i = 0; i < n ; i++) {
      if (b[i] === '0') {
        if (a[i] === '1') {
          total += aCero - old[0];
        } else {
          total += aOnes - old[1];
        }
        old[a[i]]++;
      }
    }
    console.log(total);
  }
}

const processData = (input) => {
  input.split('\n').forEach(line => {
    // vIn.push(line);
    line.split(' ').forEach(item => { vIn.push(item); });
  });
};

const solveP = new SolveProblemClass();
process.stdin.resume();
process.stdin.setEncoding("ascii");
let _input = "";
process.stdin.on("data", (input) => {
  _input += input;
});
process.stdin.on("end", () => {
  processData(_input);
  solveP.solveAll();
});

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

function magic(n) { return n <= 1 ? 0 : magic(n - 1) + n - 1 }

let a, b, numWays, numLines = 0
rl.on('line', (line) => {
    ++numLines
    if (numLines == 2) a = line.split('').map(x => parseInt(x))
    if (numLines == 3) b = line.split('').map(x => parseInt(x))
}).on('close', () => {
    let t = [[0, 0], [0, 0]]
    a.forEach((bit, idx) => {
        t[bit][b[idx]]++
    })
    process.stdout.write(`${t[0][0] * t[1][0] + t[1][0] * t[0][1] + t[0][0] * t[1][1]}`)
})

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

let a, b, numLines = 0
rl.on('line', (line) => {
    ++numLines
    if (numLines == 2) a = line.split('').map(x => parseInt(x))
    if (numLines == 3) b = line.split('').map(x => parseInt(x))
}).on('close', () => {
    let t = [[0, 0], [0, 0]]
    a.forEach((bit, idx) => t[bit][b[idx]]++)
    process.stdout.write(`${t[0][0] * t[1][0] + t[1][0] * t[0][1] + t[0][0] * t[1][1]}`)
})

function main() {
  const is = new Scanner();
  const n = is.nextInt();
  const a = is.nextLine();
  const b = is.nextLine();
  let answer = 0, aux = 0;
  for (let i = 0; i < n; i += 1) {
    if (a[i] === '0' && b[i] === '0' || a[i] === '1' && b[i] === '0')
      aux += 1;
    else
      answer += 1;
  }
  answer += (aux * (aux - 1)) / 2;
  console.log(answer);
}

/*
 *  Api Scanner
 */
class Scanner {
  constructor() {
    this.index = -1;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    this.index += 1;
    return this.lines[this.index].trim();
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray(fn) {
    const array = this.nextLine().split(' ');
    return fn === String ? array : array.map(fn);
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const n = is.nextInt();
  const a = is.nextLine();
  const b = is.nextLine();
  let answer = 0, aux = 0;
  for (let i = 0; i < n; i += 1) {
    if (a[i] === '0' && b[i] === '0' || a[i] === '1' && b[i] === '0')
      aux += 1;
    else
      answer += 1;
  }
  if (aux === 0)
    answer = 0;
  else
    answer += (aux * (aux - 1)) / 2;

  console.log(answer);
}

/*
 *  Api Scanner
 */
class Scanner {
  constructor() {
    this.index = -1;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    this.index += 1;
    return this.lines[this.index].trim();
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray(fn) {
    const array = this.nextLine().split(' ');
    return fn === String ? array : array.map(fn);
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const n = is.nextInt();
  const a = is.nextLine();
  const b = is.nextLine();
  let answer = 0, aux = 0;
  for (let i = 0; i < n; i += 1) {
    if (a[i] === '0' && b[i] === '0' || a[i] === '1' && b[i] === '0')
      aux += 1;
    else
      answer += 1;
  }
  if (aux === 0)
    answer = 0;
  else
    answer += Math.max(1, (aux * (aux - 1)) / 2);

  console.log(answer);
}

/*
 *  Api Scanner
 */
class Scanner {
  constructor() {
    this.index = -1;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    this.index += 1;
    return this.lines[this.index].trim();
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray(fn) {
    const array = this.nextLine().split(' ');
    return fn === String ? array : array.map(fn);
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const n = is.nextInt();
  const a = is.nextLine();
  const b = is.nextLine();
  let answer = 0, aux = 0;
  for (let i = 0; i < n; i += 1) {
    if (a[i] === '0' && b[i] === '0' || a[i] === '1' && b[i] === '0')
      aux += 1;
    else
      answer += 1;
  }
  if (aux === 0)
    answer = 0;
  else
    answer += Math.round((aux * (aux - 1)) / 2);

  console.log(answer);
}

/*
 *  Api Scanner
 */
class Scanner {
  constructor() {
    this.index = -1;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    this.index += 1;
    return this.lines[this.index].trim();
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray(fn) {
    const array = this.nextLine().split(' ');
    return fn === String ? array : array.map(fn);
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

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

function magic(n) { return n <= 1 ? 0 : magic(n - 1) + n - 1 }

let a, b, numWays, numLines = 0
rl.on('line', (line) => {
    ++numLines
    if (numLines == 2) a = line.split('')
    if (numLines == 3) b = line.split('')
}).on('close', () => {
    let sum = 0, ones = a.filter(x => x == 1).length, zeros = a.length - ones
    a.forEach((bit, idx) => {
        if (b[idx] == 0) {
            if (bit == 0) {
                sum += ones
            } else {
                sum += zeros
            }
        }
    })
    process.stdout.write(`${sum - b.filter(x => x == 0).length + 1}`)
})


The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$).

For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...".

NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG".

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {"use strict";
    // TODO
    var q = rdN();
    var foo = function(arr, k) {
        var sum = 0;
        for(var i = 0; i < k; ++i) {
            sum += arr[i];
        }
        var max = sum;
        for (var i = 0, j = k; j < arr.length; ++i, ++j) {
            //pr('sum=', sum, 'i=', arr[i], 'j=', arr[j])
            sum -= arr[i];
            sum += arr[j];
            if (max < sum) {
                max = sum;
            }

        }
        //pr()
        return k - max;
    };
    while (q --> 0) {
        var input = rdArN();
        var n = input[0];
        var k = input[1];
        var s = rdS();
        var R = [];
        var G = [];
        var B = [];
        var rgb = ['R', 'G', 'B'];
        for (var i = 0; i < n; ++i) {
            R.push(+(s[i] === rgb[(i+0)%3]));
            G.push(+(s[i] === rgb[(i+1)%3]));
            B.push(+(s[i] === rgb[(i+2)%3]));
        }
        //prAr(R);
        //prAr(G);
        //prAr(B);

        var fooR = foo(R, k);
        var fooG = foo(G, k);
        var fooB = foo(B, k);

        //prAr([fooR,fooG,fooB]);
        pr(Math.min(...[fooR,fooG,fooB]));
    }
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const rdS=readline;
const rdN=()=>+rdS();
const rdArS=()=>rdS().split(' ');
const rdArN=()=>rdArS().map(v=>+v);
const wr=write;
const pr=print;
const prAr=(a)=>pr(...a);
const prOb=(o)=>pr(JSON.stringify(o,null,4));
const cmpLt=(a,b)=>a-b;
const cmpGt=(a,b)=>b-a;
const crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);};
const getPrimes=function(n){var sieve=crAr(n+1,true);for(var i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}var primes=[];for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;};
const defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{configurable:true,enumerable:false,value:v});
defineProperty(Array.prototype,'sortLt',function(){return this.sort(cmpLt);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort(cmpGt);});
defineProperty(Set.prototype,'union',function(s){return new Set([...this,...s]);});
defineProperty(Set.prototype,'intersection',function(s){return new Set([...this].filter((v)=>s.has(v)));});
defineProperty(Set.prototype,'difference',function(s){return new Set([...this].filter((v)=>!s.has(v)));});

main();
return OUTPUT;
})();