After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you).  You are given an array $$$h_1, h_2, \dots, h_n$$$, where $$$h_i$$$ is the height of the $$$i$$$-th mountain, and $$$k$$$ — the number of boulders you have.You will start throwing boulders from the top of the first mountain one by one and they will roll as follows (let's assume that the height of the current mountain is $$$h_i$$$):   if $$$h_i \ge h_{i + 1}$$$, the boulder will roll to the next mountain;  if $$$h_i < h_{i + 1}$$$, the boulder will stop rolling and increase the mountain height by $$$1$$$ ($$$h_i = h_i + 1$$$);  if the boulder reaches the last mountain it will fall to the waste collection system and disappear. You want to find the position of the $$$k$$$-th boulder or determine that it will fall into the waste collection system.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of two lines. The first line in each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$; $$$1 \le k \le 10^9$$$) — the number of mountains and the number of boulders. The second line contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 100$$$) — the height of the mountains. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case, print $$$-1$$$ if the $$$k$$$-th boulder will fall into the collection system. Otherwise, print the position of the $$$k$$$-th boulder.

NoteLet's simulate the first case:  The first boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ it rolls to $$$i = 2$$$ and stops there because $$$h_2 < h_3$$$.  The new heights are $$$[4,2,2,3]$$$.  The second boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ the boulder rolls to $$$i = 2$$$; since $$$h_2 \ge h_3$$$ the boulder rolls to $$$i = 3$$$ and stops there because $$$h_3 < h_4$$$.  The new heights are $$$[4,2,3,3]$$$.  The third boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ it rolls to $$$i = 2$$$ and stops there because $$$h_2 < h_3$$$.  The new heights are $$$[4,3,3,3]$$$. The positions where each boulder stopped are the following: $$$[2,3,2]$$$.In the second case, all $$$7$$$ boulders will stop right at the first mountain rising its height from $$$1$$$ to $$$8$$$.The third case is similar to the first one but now you'll throw $$$5$$$ boulders. The first three will roll in the same way as in the first test case. After that, mountain heights will be equal to $$$[4, 3, 3, 3]$$$, that's why the other two boulders will fall into the collection system.In the fourth case, the first and only boulders will fall straight into the collection system.

/*
 * File Created: Friday, 5th February 2021 3:53:54 pm
 * Author: Lukas Rimkus
 */
'use-strict'

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

let data = '';
let currentLine = 0;

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

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

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

    while(testCases--) {

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

        const h = readLine().split(' ').map(Number);

        const res = b(n,k,h);

        console.log(res)
    }
});

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

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

function a(px,py,s)
{
    // if px > 0 than search for R else L
    // if py > 0 than search for U else D
    let U = 0;
    let D = 0;
    let R = 0;
    let L = 0;
    for(let i = 0 ; i < s.length; i++){
        if(s[i] === 'U') U++;
        else if(s[i] === 'D') D++;
        else if(s[i] === 'R') R++;
        else if(s[i] === 'L') L++;
    }
    if(px > 0){
        if(px > R) return 'NO';
    }
    if(px < 0) {
        if(Math.abs(px) > L) return 'NO';
    }
    if(py > 0){
        if(py > U) return 'NO';
    }
    if(py < 0) {
        if(Math.abs(py) > D) return 'NO';
    }
   return 'YES';
}

function b(n,k,h){
    // find the last boulder's fail position or if it was waisted in the dump (-1)
    const boulders = new Array(k);
    let j = 0;
    while(k){
        for(let i = 0 ; i < h.length; i++){
            if(h[i] < h[i + 1]){
                h[i] = h[i] + 1;
                boulders[j++] = i+1;
                k--;
                break;
            }
            if(i === h.length - 1){
                boulders[j++] = -1;
                k--;
                return  -1;
            }
        }
    }
    return boulders[boulders.length - 1];
}

module.exports = b;

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (n === 1) {
      console.log(-1);
      continue;
    }
    let cnt = 0,
      i = 0;
    while (cnt < k) {
      for (i = 0; i < n - 1; i++) {
        if (arr[i] < arr[i + 1]) {
          arr[i]++;
          cnt++;
          break;
        }
      }
      if (i == n - 1) break;
    }
    if (cnt === k) console.log(i + 1);
    else console.log(-1);
  }
};
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 testCases = readline()
    while(testCases--)
        solve()
}

// function to solve problems
function solve (){
    let line = readline().split(' ').map(x => +x)
    let n = line[0]
    let k = line[1]
    let arr = readline().split(' ').map(x => +x)
    // ====== SOLUTION ======
    while(k--){
        // console.log('inside While k = ', k)
        let i = 0
        for(; i < n-1; i++){
            if(arr[i] < arr[i+1]){
                arr[i]++
                break
            }
        }
        if(k != 0 && i == n-1){
            console.log('-1')
            break
        }
        if(k == 0){
            if(i == n-1)
                console.log(-1)
            else
                console.log(i+1)
        }
        // console.log('k = ', k)
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

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

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, k] = readline().split(' ').map(x => Number(x));
        var array = readline().split(' ').map(x => Number(x));
        var last = array[n - 1]
        var answer = 0
        array.map((x, i) => {
            if (i === 0) return
            if (x < last) answer += last - x
        })
        var i = 0
        var answer = 0
        while (k > 0) {
            if (i === n) {
                answer = -1
                break
            }
            // console.log(array[i], array[i + 1], array[i] < array[i + 1])

            if (array[i] < array[i + 1]) {
                k--
                array[i]++
                if (k === 0) break
                i = 0
            } else {
                i++
            }
            // console.log(array)
        }
        console.log(answer ? answer : (i+1))
        // console.log(k)
    })

}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var K = nextInt();
		var list = nextIntArray(N);
		var last = -1;
		while(K > 0){
			var isOK = false;
			for(var j = 0; j < N - 1; j++){
				if(list[j] < list[j + 1]){
					list[j]++;
					isOK = true;
					last = j + 1;
					break;
				}
			}
			if(!isOK){
				last = -1;
				break;
			}
			K--;
		}
		myout(last);
	}
}

const T = parseInt(readline());

for (t = 0; t < T; t++) {
	var nk = readline().split(" ").map(x => parseInt(x));
	var n = nk[0];
	var k = nk[1];
	var h = readline().split(" ").map(x => parseInt(x));

	var ans = 0;
	for (j = 0; j < k; j++) {
		ans = -1;
		for (i = 1; i < n; i++) {
			if (h[i - 1] < h[i]) {
				ans = i;
				h[i - 1]++;
				break;
			}
		}
		if (ans == -1) break;
	}
	print(ans);
}

/*
 * File Created: Friday, 5th February 2021 3:53:54 pm
 * Author: Lukas Rimkus
 */
'use-strict'

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

let data = '';
let currentLine = 0;

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

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

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

    while(testCases--) {

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

        const h = readLine().split(' ').map(Number);

        const res = a(n,k,h);

        console.log(res)
    }
});

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

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

function a(px,py,s)
{
    // if px > 0 than search for R else L
    // if py > 0 than search for U else D
    let U = 0;
    let D = 0;
    let R = 0;
    let L = 0;
    for(let i = 0 ; i < s.length; i++){
        if(s[i] === 'U') U++;
        else if(s[i] === 'D') D++;
        else if(s[i] === 'R') R++;
        else if(s[i] === 'L') L++;
    }
    if(px > 0){
        if(px > R) return 'NO';
    }
    if(px < 0) {
        if(Math.abs(px) > L) return 'NO';
    }
    if(py > 0){
        if(py > U) return 'NO';
    }
    if(py < 0) {
        if(Math.abs(py) > D) return 'NO';
    }
   return 'YES';
}

function b(n,k,h){
    // find the last boulder's fail position or if it was waisted in the dump (-1)
    const boulders = [];
    while(k){
        for(let i = 0 ; i < h.length; i++){
            if(h[i] < h[i + 1]){
                h[i] = h[i] + 1;
                boulders.push(i+1);
                k--;
                break;
            }
            if(i === h.length - 1){
                boulders.push(-1);
                k--;
            }
        }
    }
    return boulders[boulders.length - 1];
}

module.exports = b;

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


This is the easy version of this problem. The difference between easy and hard versions is only the constraints on $$$a_i$$$ and on $$$n$$$. You can make hacks only if both versions of the problem are solved.Burenka is the crown princess of Buryatia, and soon she will become the $$$n$$$-th queen of the country. There is an ancient tradition in Buryatia — before the coronation, the ruler must show their strength to the inhabitants. To determine the strength of the $$$n$$$-th ruler, the inhabitants of the country give them an array of $$$a$$$ of exactly $$$n$$$ numbers, after which the ruler must turn all the elements of the array into zeros in the shortest time. The ruler can do the following two-step operation any number of times:   select two indices $$$l$$$ and $$$r$$$, so that $$$1 \le l \le r \le n$$$ and a non-negative integer $$$x$$$, then  for all $$$l \leq i \leq r$$$ assign $$$a_i := a_i \oplus x$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. It takes $$$\left\lceil \frac{r-l+1}{2} \right\rceil$$$ seconds to do this operation, where $$$\lceil y \rceil$$$ denotes $$$y$$$ rounded up to the nearest integer. Help Burenka calculate how much time she will need.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 5000$$$) — elements of the array.  It is guaranteed that the sum of $$$n$$$ in all tests does not exceed $$$5000$$$.

For each test case, output a single number  — the minimum time that Burenka will need.

NoteIn the first test case, Burenka can choose segment $$$l = 1$$$, $$$r = 4$$$, and $$$x=5$$$. so it will fill the array with zeros in $$$2$$$ seconds.In the second test case, Burenka first selects segment $$$l = 1$$$, $$$r = 2$$$, and $$$x = 1$$$, after which $$$a = [0, 2, 2]$$$, and then the segment $$$l = 2$$$, $$$r = 3$$$, and $$$x=2$$$, which fills the array with zeros. In total, Burenka will spend $$$2$$$ seconds.

const readline = require('readline')

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

function solve(n, arr) {
    const dp = Array(n)
    const m = {}
    m[0] = -1
    let xor = 0
    for (let i = 0; i < n; i++) {
        dp[i] = (dp[i - 1] || 0) + (arr[i] ? 1 : 0)
        xor ^= arr[i]
        if (xor in m) {
            const j = m[xor]
            // [j + 1, i]
            dp[i] = Math.min(dp[i], (dp[j] || 0) + (i - j - 1))
            // console.log(j + 1, i)
        // } else {
        }
        m[xor] = i
    }
    // console.log(dp)
    return dp[n - 1]
}


Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:  The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:   given a row index i, flip all the values in the i-th row in A;  given a column index i, flip all the values in the i-th column in A;  find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?

The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:    1 i — flip the values of the i-th row;  2 i — flip the values of the i-th column;  3 — output the unusual square of A.  Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.

Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.

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

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

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

function main() {
	var n = parseInt(readline());
	var value = 0;
	for (var r = 0; r < n; ++r) {
		var row = readline();
		value ^= (row.charAt(2*r) == '0' ? 0 : 1);
	}

	var queryNum = parseInt(readline());
	var results = [];
	for (var q = 0; q < queryNum; ++q) {
		var data = tokenizeIntegers(readline());
		if (data[0] == 3) {
			results.push(value);
		}
		else {
			value ^= 1;
		}
	}
	print(results.join(""));
}

main();

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

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

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

function main() {
	var n = parseInt(readline());
	var value = 0;
	for (var r = 0; r < n; ++r) {
		var row = readline();
		value ^= (row.charAt(2*r) == '0' ? 0 : 1);
	}

	var queryNum = parseInt(readline());
	var results = [];
	for (var i = 0; i < queryNum; ++i) {
		var data = tokenizeIntegers(readline());
		if (data[0] == 3) {
			results.push(value);
		}
		else {
			value ^= 1;
		}
	}
	print(results.join(""));
}

main();

var n = +readline();
var s = [];
var A = 0;
var ans = '';
for (var i=0; i<n; i++) {
	s[i] = readline().split(' ').map(Number);
}
for (var i=0; i<n; i++) {
	for (var j=0; j<n; j++) {
	A += s[i][j]*s[j][i];
	}
}
A = A%2;
var q = +readline();
for (var i=0; i<q; i++) {
	var z = readline().split(' ').map(Number);
	if (z[0] == 3) ans += A;
	else A = (A + 1)%2;
}
print(ans);

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

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

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

function main() {
	var n = parseInt(readline());
	var d = n%2;
	var m = [];
	var f = 0;
	for (var r = 0; r < n; ++r) {
		var row = tokenizeIntegers(readline());
		for (var c = 0; c < n; ++c) {
			f ^= row[c];
		}
		m.push(row);
	}

	var queryNum = parseInt(readline());
	var results = [];
	for (var q = 0; q < queryNum; ++q) {
		var data = tokenizeIntegers(readline());
		if (data[0] == 1) {
			f ^= d;
		}
		else if (data[0] == 2) {
			f ^= d;
		}
		else {
			results.push(f);
		}
	}
	print(results.join(""));
}

main();

var n = +readline();
var s = [];
var A = 0;
var ans = '';
for (var i=0; i<n; i++) {
	s[i] = readline().split(' ').map(Number);
}
for (var i=0; i<n; i++) {
	for (var j=0; j<n; j++) {
	A += s[i][j]*s[j][i];
	}
}
A = A%2;
var q = +readline();
for (var i=0; i<q; i++) {
	var z = readline().split(' ').map(Number);
	if (z[0] == 3) ans += A;
	else if (n%2 == 1) A = (A + 1)%2;
}
print(ans);


Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:  If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.  Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.

The first line of the input contains integers n, h and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ h ≤ 109) — the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively. The second line contains n integers ai (1 ≤ ai ≤ h) — the heights of the pieces.

Print a single integer — the number of seconds required to smash all the potatoes following the process described in the problem statement.

NoteConsider the first sample.   First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.  Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.  Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.  Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.  During this second processor finally smashes all the remaining potato and the process finishes. In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2·5 = 10 seconds.In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.

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

var n = input[0];
var h = input[1];
var k = input[2];

var potatoes = readline().split(' ').map(Number);
var t = 0;

for (var i = 0; i < n; i++) {
	t += Math.floor(potatoes[i] / k);
	if ((potatoes[i] % k + potatoes[i + 1] > h) || (i == n - 1 && potatoes[i] % k > 0)) {
		t += 1;
	} else {
		potatoes[i + 1] += (potatoes[i] % k);
	}
}

print(t);


Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds.Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot be held without Div2) in all other cases the rounds don't overlap in time. Each round has a unique identifier — a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the Div1 round is always greater.Sereja is a beginner coder, so he can take part only in rounds of Div2 type. At the moment he is taking part in a Div2 round, its identifier equals to x. Sereja remembers very well that he has taken part in exactly k rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed.Sereja is wondering: what minimum and what maximum number of Div2 rounds could he have missed? Help him find these two numbers.

The first line contains two integers: x (1 ≤ x ≤ 4000) — the round Sereja is taking part in today, and k (0 ≤ k < 4000) — the number of rounds he took part in. Next k lines contain the descriptions of the rounds that Sereja took part in before. If Sereja took part in one of two simultaneous rounds, the corresponding line looks like: "1 num2 num1" (where num2 is the identifier of this Div2 round, num1 is the identifier of the Div1 round). It is guaranteed that num1 - num2 = 1. If Sereja took part in a usual Div2 round, then the corresponding line looks like: "2 num" (where num is the identifier of this Div2 round). It is guaranteed that the identifiers of all given rounds are less than x.

Print in a single line two integers — the minimum and the maximum number of rounds that Sereja could have missed.

NoteIn the second sample we have unused identifiers of rounds 1, 6, 7. The minimum number of rounds Sereja could have missed equals to 2. In this case, the round with the identifier 1 will be a usual Div2 round and the round with identifier 6 will be synchronous with the Div1 round. The maximum number of rounds equals 3. In this case all unused identifiers belong to usual Div2 rounds.

print(function(x, k) {
	var a = [x, 0];
	for (var i = 0; i < k; i++) {
		(function(type, div2, div1) {
			if (type === 1) {
				a.push(div2, div1);
			} else {
				a.push(div2);
			}
		}).apply(0, readline().split(' ').map(Number));
	}
	a.sort(function(a, b) {
		return a - b
	});

	var min = 0;
	var max = 0;
	for (var i = 1; i < a.length; i++) {
		var j = a[i] - a[i - 1];
		if (j > 1) {
			j--;
			min += Math.ceil(j / 2);
			max += j;
		}
	}

	return min + ' ' + max;

}.apply(0, readline().split(' ').map(Number)));

;(function () {
	print(function () {
		var l = readline().split(' ').map(Number),
			x = l[0], k = l[1];

		var t = [];
		for (var i = 0; i < x - 1; i++) {
			t.push(false);
		}

		for (var i = 0; i < k; i++) {
			var q = readline().split(' ').map(Number);
			t[q[1] - 1] = true;
			if (q[0] === 1) {
				t[q[2] - 1] = true;
			}
		}

		t = t.map(function(e, i) {
			return e === false ? i + 1 : e;
		}).filter(function (e) {
			return e === parseInt(e);
		});

		var max = t.length;
		var no_max = 0;
		for (var i = 0, _i = max - 1; i < _i; i++) {
			if (t[i] === t[i + 1] - 1) {
				i++;
				no_max++;
			}
		}

		return [max - no_max, max].join(' ');
	}());
}).call(this);

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var today = integers[0], missedCount = integers[1];

	var seen = new Array(today+1);
	for (var i = 0; i < missedCount; ++i) {
		var missed = tokenizeIntegers(readline());
		for (var j = 1; j < missed.length; ++j) {
			seen[missed[j]] = true;
		}
	}
	seen[today] = true;

	var min = 0, max = 0;
	var pos = 1;
	while (pos < today) {
		var span = 0;
		while (seen[pos] != true) {
			span += 1;
			pos += 1;
		}
		max += span;
		min += span%2 + Math.floor(span/2);
		while (seen[pos] == true && pos < today) {
			pos += 1;
		}
	}

	print(min+" "+max);
}

main();


The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:  If x = 1, exit the function.  Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.

A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation.

In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  const len = +readLine();
  const result = [];

  result.push(len);
  for (let i = 1; i < len; i++) {
    result.push(i);
  }

  console.log(result.join(" "));
}

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

  readline.question("", (n) => {
    //console.log(`Hi ${name}!`)
    console.log(n);
    for(i=1 ; i <= n-1 ;i++){
        console.log(i);}
        readline.close()
  })
}

read_input()

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function main() {
	let n = readLine() >> 0;
	let a = [n];
	for (let i = 1; i < n; ++i) {
		a.push(i);
	}
	console.log(a.join(' '));
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', (inputStd) => {
    inputString += inputStd;
});
process.stdin.on('end', function () {
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => {
            return str.trim();
        });
    main();
});
function readLine() {
    return inputString[currentLine++];
}
function main() {
    let n = parseInt(readLine());
    let numbers = [];
    for (let i = 1; i < n; i++) {
        numbers.push(i);
    }
    console.log(n, ...numbers);
}

var n = +readline();

var a = [ n ];

for ( var i = 1; i < n; i++ )
	a.push( i );

print( a.join( ' ' ) );

function f (x) {
	if (x === 1)return;
	else f(x-1);

	swap(a[x-1], a[x]);
}

;(function () {

	var n = +readline();

	var a = [];
	for (var i = 1; i <= n; i++) a.push(i);
	a.unshift(a.pop());
	print(a.join(' '));

}).call(this);

var n = Number(readline());
var a = [n];
for (var i = 1; i < n; i++) a.push(i);
print(a.join(' '));

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function main() {
	let n = readLine() >> 0;
	let a = [];
	for (let i = n; i >= 1; --i) {
		a.push(i);
	}
	console.log(a.join(' '));
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', (inputStd) => {
    inputString += inputStd;
});
process.stdin.on('end', function () {
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => {
            return str.trim();
        });
    main();
});
function readLine() {
    return inputString[currentLine++];
}
function main() {
    let n = parseInt(readLine());
    let numbers = [];
    for (let i = n; i >= 1; i--) {
        numbers.push(i);
    }
    console.log(...numbers);
}

function f (x) {
	if (x === 1)return;
	else f(x-1);

	swap(a[x-1], a[x]);
}

;(function () {

	var n = +readline();

	if (n === 1) {
		print(1);
		return;
	}

	var a = [2, 1];

	for (var i = 3; i <=n; i++) a.push(i);

	print(a.join(' '));

}).call(this);

function f (x) {
	if (x === 1)return;
	else f(x-1);

	swap(a[x-1], a[x]);
}

;(function () {

	var n = +readline();

	if (n === 1) {
		print(1);
		return;
	}

	var a = [2, 1];

	for (var i = 3; i <=n; i++) a.unshift(i);

	print(a.join(' '));

}).call(this);

var n = Number(readline());
var a = [];
for (var i = 2; i <= n; i++) a.push(i);
a.push(1);
print(a.join(' '));


This is the easy version of the problem. The only difference is that in this version $$$n \leq 2000$$$. You can make hacks only if both versions of the problem are solved.There are $$$n$$$ potions in a line, with potion $$$1$$$ on the far left and potion $$$n$$$ on the far right. Each potion will increase your health by $$$a_i$$$ when drunk. $$$a_i$$$ can be negative, meaning that potion will decrease will health.You start with $$$0$$$ health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink?

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2000$$$) — the number of potions.  The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ... ,$$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) which represent the change in health after drinking that potion.

Output a single integer, the maximum number of potions you can drink without your health becoming negative.

NoteFor the sample, you can drink $$$5$$$ potions by taking potions $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$ and $$$6$$$. It is not possible to drink all $$$6$$$ potions because your health will go negative at some point

'use strict';

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

  return obj;
}

function solve(n, a) {
  let t = -1;
  for (let i = 0; i < n; i++) {
    if (a[i] >= 0) {
      t = i;
      break;
    }
  }
  if (t === -1) return 0;
  const dp = new Array(n).fill(0);
  const heap = new Heap((a, b) => a - b);
  let sum = 0;
  for (let i = t; i < n; i++) {
    var _dp;
    if (a[i] < 0) heap.push(a[i]);
    sum += a[i];
    dp[i] = ((_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;
    while (sum < 0) {
      sum -= heap.pop();
      dp[i]--;
    }
  }
  let res = 0;
  for (let i = 0; i < n; i++) {
    res = Math.max(res, dp[i]);
  }
  return res;
}
class Heap {
  constructor(_comparator, arr) {
    _defineProperty(this, "_heap", []);
    this._comparator = _comparator;
    if (arr) {
      this._heap = [...arr];
      for (let i = arr.length >> 1; i; i--) this.down(i);
    }
  }
  swap(i, j) {
    [this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
  }
  _has(i) {
    return Object.prototype.hasOwnProperty.call(this._heap, i);
  }
  comparator(i, j) {
    return this._comparator(this._heap[i], this._heap[j]) < 0;
  }
  parent(i) {
    return i - 1 >> 1;
  }
  children(i) {
    return [2 * i + 1, 2 * i + 2];
  }
  up(i) {
    let parent = this.parent(i);
    while (i > 0 && this.comparator(i, parent)) {
      this.swap(i, parent);
      [i, parent] = [parent, parent - 1 >> 1];
    }
  }
  down(i) {
    let [left, right] = this.children(i);
    while (left < this._heap.length) {
      if (!this._has(right)) right = left;
      if (this.comparator(right, left)) [left, right] = [right, left];
      if (this.comparator(i, left)) break;
      this.swap(i, left);
      i = left;
      [left, right] = [2 * i + 1, 2 * i + 2];
    }
  }
  push(node) {
    this._heap.push(node);
    this.up(this._heap.length - 1);
  }
  pop() {
    if (this.size() === 0) return null;
    let res = this._heap[0];
    this.swap(0, this._heap.length - 1);
    this._heap.pop();
    this.down(0);
    return res;
  }
  remove(i) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this.swap(i, this._heap.length - 1);
    this._heap.pop();
    this.down(i);
    this.up(i);
    return res;
  }
  modify(i, val) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this._heap[i] = val;
    this.down(i);
    this.up(i);
    return res;
  }
  top() {
    if (this.size() === 0) return null;
    return this._heap[0];
  }
  size() {
    return this._heap.length;
  }
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    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);
});

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 05/28/21 night

const solve = (n, a) => {
    let pq = new MinPriorityQueue({ priority: x => x });
    let res = sum = 0;
    for (const e of a) {
        sum += e;
        res++;
        if (e < 0) {
            pq.enqueue(e);
            while (sum < 0) {
                sum -= pq.dequeue().element;
                res--;
            }
        }
    }
    pr(res);
};

class HeapNode {
    constructor(key, value) {
        this._key = key;
        this._value = value;
    }

    getKey() {
        return this._key;
    }

    getValue() {
        return this._value;
    }
}

const isNumber = (n) => typeof n === 'number';
const isNoneEmptyString = (s) => typeof s === 'string' && s.length;
const isNoneNullObject = (o) => typeof o === 'object' && o !== null;
const isNoneEmptyArray = (a) => Array.isArray(a) && a.length > 0;

class Heap {
    constructor(nodes) {
        this._nodes = Array.isArray(nodes) ? nodes : [];
        this._leaf = null;
    }

    _getLeftChildIndex(parentIndex) {
        return (parentIndex * 2) + 1;
    }

    _getRightChildIndex(parentIndex) {
        return (parentIndex * 2) + 2;
    }

    _getParentIndex(childIndex) {
        return Math.floor((childIndex - 1) / 2);
    }

    _getLastIndex() {
        return this._nodes.length - 1;
    }

    _swap(i, j) {
        const temp = this._nodes[i];
        this._nodes[i] = this._nodes[j];
        this._nodes[j] = temp;
    }

    _compareChildrenOf(parentIndex) {
        const leftChildIndex = this._getLeftChildIndex(parentIndex);
        const rightChildIndex = this._getRightChildIndex(parentIndex);
        const size = this.size();
        if (leftChildIndex >= size && rightChildIndex >= size) return -1;
        if (leftChildIndex >= size) return rightChildIndex;
        if (rightChildIndex >= size) return leftChildIndex;
        return this._compareChildren(leftChildIndex, rightChildIndex);
    }

    _heapifyUp() {
        let childIndex = this._getLastIndex();
        let parentIndex = this._getParentIndex(childIndex);
        while (this._shouldSwap(childIndex, parentIndex)) {
            this._swap(childIndex, parentIndex);
            childIndex = parentIndex;
            parentIndex = this._getParentIndex(childIndex);
        }
    }

    _heapifyDown() {
        let parentIndex = 0;
        let childIndex = this._compareChildrenOf(parentIndex);
        while (this._shouldSwap(childIndex, parentIndex)) {
            this._swap(childIndex, parentIndex);
            parentIndex = childIndex;
            childIndex = this._compareChildrenOf(parentIndex);
        }
    }

    _heapifyDownUntil(index) {
        let parentIndex = 0;
        let leftChildIndex = 1;
        let rightChildIndex = 2;
        let childIndex;
        while (leftChildIndex < index) {
            childIndex = this._compareChildrenBefore(
                index,
                leftChildIndex,
                rightChildIndex
            );
            if (this._shouldSwap(childIndex, parentIndex)) {
                this._swap(childIndex, parentIndex);
            }
            parentIndex = childIndex;
            leftChildIndex = this._getLeftChildIndex(parentIndex);
            rightChildIndex = this._getRightChildIndex(parentIndex);
        }
    }

    _clone(HeapType) {
        return new HeapType(this._nodes.slice());
    }

    sort() {
        for (let i = this._getLastIndex(); i > 0; i -= 1) {
            this._swap(0, i);
            this._heapifyDownUntil(i);
        }
        return this._nodes;
    }

    insert(key, value) {
        const newNode = new HeapNode(key, value);
        this._nodes.push(newNode);
        this._heapifyUp();
        return newNode;
    }

    root() {
        if (this.isEmpty()) return null;
        return this._nodes[0];
    }

    leaf() {
        return this._leaf;
    }

    extractRoot() {
        if (this.isEmpty()) return null;
        const root = this.root();
        this._nodes[0] = this._nodes[this._getLastIndex()];
        this._nodes.pop();
        this._heapifyDown();
        if (root === this._leaf) {
            if (this.isEmpty()) {
                this._leaf = null;
            } else {
                this._leaf = this.root();
            }
        }
        return root;
    }

    size() {
        return this._nodes.length;
    }

    isEmpty() {
        return this.size() === 0;
    }

    clear() {
        this._nodes = [];
        this._leaf = null;
    }

    static _heapify(items, HeapType) {
        if (!isNoneEmptyArray(items)) return null;
        const heap = new HeapType();
        items.forEach((item) => {
            if (isNumber(item) || isNoneEmptyString(item)) {
                heap.insert(item);
            } else if (isNoneNullObject(item) &&
                (isNumber(item.key) || isNoneEmptyString(item.key))) {
                heap.insert(item.key, item.value);
            }
        });
        return heap;
    }
}

class MinHeap extends Heap {
    _getMinChildIndex(leftChildIndex, rightChildIndex) {
        const leftChild = this._nodes[leftChildIndex];
        const rightChild = this._nodes[rightChildIndex];
        if (leftChild.getKey() < rightChild.getKey()) {
            return leftChildIndex;
        }
        return rightChildIndex;
    }

    _getMinChildIndexBefore(index, leftChildIndex, rightChildIndex) {
        const leftChild = this._nodes[leftChildIndex];
        const rightChild = this._nodes[rightChildIndex];
        if (rightChild.getKey() < leftChild.getKey() && rightChildIndex < index) {
            return rightChildIndex;
        }
        return leftChildIndex;
    }

    _shouldSwap(childIndex, parentIndex) {
        if (childIndex < 0 || childIndex >= this.size()) return false;
        if (parentIndex < 0 || parentIndex >= this.size()) return false;
        const child = this._nodes[childIndex];
        const parent = this._nodes[parentIndex];
        return child.getKey() < parent.getKey();
    }

    _compareChildren(leftChildIndex, rightChildIndex) {
        return this._getMinChildIndex(leftChildIndex, rightChildIndex);
    }

    _compareChildrenBefore(index, leftChildIndex, rightChildIndex) {
        return this._getMinChildIndexBefore(index, leftChildIndex, rightChildIndex);
    }

    insert(key, value) {
        const newNode = super.insert(key, value);
        if (this._leaf === null || key > this._leaf.getKey()) {
            this._leaf = newNode;
        }
        return newNode;
    }

    clone() {
        return super._clone(MinHeap);
    }

    static heapify(items) {
        return super._heapify(items, MinHeap);
    }
}

class PriorityQueue {
    constructor(options = {}) {
        const {
            priority
        } = options;
        if (priority !== undefined && typeof priority !== 'function') {
            throw new Error('invalid priority callback');
        }
        this._getPriority = typeof priority === 'function' ? priority : null;
    }

    size() {
        return this._heap.size();
    }

    isEmpty() {
        return this._heap.isEmpty();
    }

    front() {
        if (this.isEmpty()) return null;
        const first = this._heap.root();
        return {
            priority: first.getKey(),
            element: first.getValue()
        };
    }

    back() {
        if (this.isEmpty()) return null;
        const last = this._heap.leaf();
        return {
            priority: last.getKey(),
            element: last.getValue()
        };
    }

    enqueue(element, p) {
        if (p && Number.isNaN(+p)) {
            throw new Error('invalid priority number');
        }
        if (Number.isNaN(+p) && this._getPriority === null) {
            throw new Error('missing priority number or constructor callback');
        }
        const priority = !Number.isNaN(+p) ? p : this._getPriority(element);
        this._heap.insert(priority, element);
    }

    dequeue() {
        if (this.isEmpty()) return null;
        const first = this._heap.extractRoot();
        return {
            priority: first.getKey(),
            element: first.getValue()
        };
    }

    toArray() {
        return this._heap
            .clone()
            .sort()
            .map((n) => ({
                priority: n.getKey(),
                element: n.getValue()
            }))
            .reverse();
    }

    clear() {
        this._heap.clear();
    }
}

class MinPriorityQueue extends PriorityQueue {
    constructor(options) {
        super(options);
        this._heap = new MinHeap();
    }
}

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

// PriorityQueue implementated using array based binary heap
// PriorityQueue methods
//  push(...values)
// 	peek()
//  pop()
//  size()
//  replace(value)

class PriorityQueue {

	constructor(comparator = (a, b) => a > b) {
		this.top = 0;
		this._heap = [];
		this._comparator = comparator;
	}
	size() {
		return this._heap.length;
	}
	isEmpty() {
		return this.size() == 0;
	}
	peek() {
		return this._heap[this.top];
	}
	push(...values) {
		values.forEach(value => {
				this._heap.push(value);
				this._siftUp();
				});
		return this.size();
	}
	pop() {
		const poppedValue = this.peek();
		const bottom = this.size() - 1;
		if (bottom > this.top) {
			this._swap(this.top, bottom);
		}
		this._heap.pop();
		this._siftDown();
		return poppedValue;
	}
	replace(value) {
		const replacedValue = this.peek();
		this._heap[this.top] = value;
		this._siftDown();
		return replacedValue;
	}
	_greater(i, j) {
		return this._comparator(this._heap[i], this._heap[j]);
	}
	_swap(i, j) {
		[this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
	}
	_siftUp() {
		const parent = i => ((i + 1) >>> 1) - 1;
		let node = this.size() - 1;
		while (node > this.top && this._greater(node, parent(node))) {
			this._swap(node, parent(node));
			node = parent(node);
		}
	}
	_siftDown() {
		const left = i => (i << 1) + 1;
		const right = i => (i + 1) << 1;
		let node = this.top;
		while (
				(left(node) < this.size() && this._greater(left(node), node)) ||
				(right(node) < this.size() && this._greater(right(node), node))
			  ) {
			let maxChild = (right(node) < this.size() && this._greater(right(node), left(node))) ? right(node) : left(node);
			this._swap(node, maxChild);
			node = maxChild;
		}
	}
}

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 () {
	const n = rn();
	const a = rna();

	let health = 0, used = 0;
	const q = new PriorityQueue((a, b) => a > b);
	for (let i = 0; i < n; i++) {
		if (a[i] >= 0) {
			health += a[i];
			used++;
		} else {
			a[i] = -a[i];
			if (health - a[i] >= 0) {
				health -= a[i];
				q.push(a[i]);
				used++;
			} else {
				if (a[i] < q.peek()) {
					health += q.pop() - a[i];
					q.push(a[i]);
				}
			}
		}
	}

	console.log(used);
}

'use strict';

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

  return obj;
}

function solve(n, a) {
  let t = -1;
  for (let i = 0; i < n; i++) {
    if (a[i] >= 0) {
      t = i;
      break;
    }
  }
  if (t === -1) return -1;
  const dp = new Array(n).fill(0);
  const heap = new Heap((a, b) => a - b);
  let sum = 0;
  for (let i = t; i < n; i++) {
    var _dp;
    if (a[i] < 0) heap.push(a[i]);
    sum += a[i];
    dp[i] = ((_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;
    while (sum < 0) {
      sum -= heap.pop();
      dp[i]--;
    }
  }
  let res = 0;
  for (let i = 0; i < n; i++) {
    res = Math.max(res, dp[i]);
  }
  return res;
}
class Heap {
  constructor(_comparator, arr) {
    _defineProperty(this, "_heap", []);
    this._comparator = _comparator;
    if (arr) {
      this._heap = [...arr];
      for (let i = arr.length >> 1; i; i--) this.down(i);
    }
  }
  swap(i, j) {
    [this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
  }
  _has(i) {
    return Object.prototype.hasOwnProperty.call(this._heap, i);
  }
  comparator(i, j) {
    return this._comparator(this._heap[i], this._heap[j]) < 0;
  }
  parent(i) {
    return i - 1 >> 1;
  }
  children(i) {
    return [2 * i + 1, 2 * i + 2];
  }
  up(i) {
    let parent = this.parent(i);
    while (i > 0 && this.comparator(i, parent)) {
      this.swap(i, parent);
      [i, parent] = [parent, parent - 1 >> 1];
    }
  }
  down(i) {
    let [left, right] = this.children(i);
    while (left < this._heap.length) {
      if (!this._has(right)) right = left;
      if (this.comparator(right, left)) [left, right] = [right, left];
      if (this.comparator(i, left)) break;
      this.swap(i, left);
      i = left;
      [left, right] = [2 * i + 1, 2 * i + 2];
    }
  }
  push(node) {
    this._heap.push(node);
    this.up(this._heap.length - 1);
  }
  pop() {
    if (this.size() === 0) return null;
    let res = this._heap[0];
    this.swap(0, this._heap.length - 1);
    this._heap.pop();
    this.down(0);
    return res;
  }
  remove(i) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this.swap(i, this._heap.length - 1);
    this._heap.pop();
    this.down(i);
    this.up(i);
    return res;
  }
  modify(i, val) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this._heap[i] = val;
    this.down(i);
    this.up(i);
    return res;
  }
  top() {
    if (this.size() === 0) return null;
    return this._heap[0];
  }
  size() {
    return this._heap.length;
  }
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    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, a) {
  let sum = a.reduce((a, b) => a + b, 0);
  if (sum >= 0) return n;
  let t = -1;
  for (let i = 0; i < n; i++) {
    if (a[i] >= 0) {
      t = i;
      break;
    }
  }
  if (t === -1) return 0;
  a = a.slice(t).sort((a, b) => a - b);
  sum = a.reduce((a, b) => a + b, 0);
  if (sum >= 0) return a.length;
  for (let i = 0; i < a.length; i++) {
    sum -= a[i];
    if (sum >= 0) return a.length - i - 1;
  }
  return 0;
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    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, a) {
  let sum = a.reduce((a, b) => a + b, 0);
  if (sum >= 0) return n;
  a.sort((a, b) => a - b);
  for (let i = 0; i < n; i++) {
    sum -= a[i];
    if (sum >= 0) return n - i - 1;
  }
  return 0;
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    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);
});

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * 05/28/21 morning
 * https://codeforces.com/contest/1526/problem/C
 */

// let a, n;
let res, a, n;
const solve = (N, A) => {
    n = N;
    a = A;
    // pr(n, a);
    res = 0;
    // let res = mx(dfs(0, 0, 0, 'skip'), dfs(0, 0, 0, 'take'));
    dfs(0, 0, 0, 'skip');
    dfs(0, 0, 0, 'take');
    pr(res);
};

const dfs = (cnt, idx, cur, action) => {
    // pr(cnt, idx, cur, action);
    if (action == 'take') cur += a[idx];
    if (cur < 0) {
        // pr(cnt, idx, cur, action);
        res = mx(res, cnt - 1);
        return;
    }
    for (let i = idx + 1; i < n; i++) {
        dfs(cnt + 1, i, cur, 'skip');
        dfs(cnt + 1, i, cur, 'take');
    }
    res = mx(res, cnt);
    // return cnt;
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

// pr(2000 * 10 ** 9 < Number.MAX_SAFE_INTEGER);

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * 05/28/21 morning
 * https://codeforces.com/contest/1526/problem/C
 */

// let a, n;
let res, a, n;
const solve = (N, A) => {
    n = N;
    a = A;
    pr(n, a);
    res = 0;
    // let res = mx(dfs(0, 0, 0, 'skip'), dfs(0, 0, 0, 'take'));
    dfs(0, 0, 0, 'skip');
    dfs(0, 0, 0, 'take');
    pr(res);
};

const dfs = (cnt, idx, cur, action) => {
    // pr(cnt, idx, cur, action);
    if (action == 'take') cur += a[idx];
    if (cur < 0) {
        // pr(cnt, idx, cur, action);
        res = mx(res, cnt - 1);
        return;
    }
    for (let i = idx + 1; i < n; i++) {
        dfs(cnt + 1, i, cur, 'skip');
        dfs(cnt + 1, i, cur, 'take');
    }
    res = mx(res, cnt);
    // return cnt;
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()

// pr(2000 * 10 ** 9 < Number.MAX_SAFE_INTEGER);


You are given a string $$$s$$$ of length $$$n$$$ consisting only of the characters 0 and 1.You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For example, if you erase the substring 111 from the string 111110, you will get the string 110. When you delete a substring of length $$$l$$$, you get $$$a \cdot l + b$$$ points.Your task is to calculate the maximum number of points that you can score in total, if you have to make the given string empty.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of testcases. The first line of each testcase contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 100; -100 \le a, b \le 100$$$) — the length of the string $$$s$$$ and the parameters $$$a$$$ and $$$b$$$. The second line contains the string $$$s$$$. The string $$$s$$$ consists only of the characters 0 and 1.

For each testcase, print a single integer — the maximum number of points that you can score.

NoteIn the first example, it is enough to delete the entire string, then we will get $$$2 \cdot 3 + 0 = 6$$$ points.In the second example, if we delete characters one by one, then for each deleted character we will get $$$(-2) \cdot 1 + 5 = 3$$$ points, i. e. $$$15$$$ points in total.In the third example, we can delete the substring 00 from the string 100111, we get $$$1 \cdot 2 + (-4) = -2$$$ points, and the string will be equal to 1111, removing it entirely we get $$$1 \cdot 4 + (-4) = 0$$$ points. In total, we got $$$-2$$$ points for $$$2$$$ operations.

"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, a, b] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split("")
      .map((cur) => parseInt(cur));
    if (b >= 0) {
      console.log(a * n + b * n);
      continue;
    } else {
      let str = [];
      str.push(arr[0]);
      for (let i = 1; i < n; i++) {
        if (str[str.length - 1] !== arr[i]) str.push(arr[i]);
      }
      if (str.length <= 2) console.log(a * n + b * str.length);
      else {
        let k = Math.ceil((str.length + 1) / 2);
        console.log(a * n + b * k);
      }
    }
  }
};
solve();

const stdin = process.openStdin();
let content = '';

stdin.addListener('data', (data) => {
          content += data;
})

stdin.addListener('end', () => {
          content = content.split('\n');
          content.shift();
          content = content.map((string) => string.substring(0, string.length - 1));
          content.pop();
          for (let i = 0; i < content.length; i += 2) {
                    const [n, a, b] = content[i].split(' ').map(string => parseInt(string));
                    console.log(maximumCostDeletion(a, b, content[i + 1]));
          }
})

const maximumCostDeletion = (a, b, str) => {
          let bContribution = str.length;
          if (b < 0) {
                    let changes = 1;
                    bContribution = 1;
                   for (let i = 1; i < str.length; i++) {
                             if (str[i] !== str[i - 1]) {
                                   changes++;
                             }
                   }
                   bContribution += Math.floor(changes / 2);
          }
          return (a * str.length) + (b * bContribution);
}

const readline = require('readline');

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

let input = [],
    numTestCases;

rl.on('line', (line) => {
    input.push(line);

    if (input.length === (2 * (+input[0]) + 1)) {
        rl.close();
        numTestCases = +input[0];
        input.shift();
        main();
    }
});

function main() {
    for (let i = 0; i < numTestCases * 2; ++i) {
        let currCaseConsts = input[i].split(' '),
            currCaseString = input[++i],
            n = +currCaseConsts[0],
            a = +currCaseConsts[1],
            b = +currCaseConsts[2];

        console.log(getMaxPoints(currCaseString, n, a, b));
    }
}

function getMaxPoints(currCaseString, n, a, b) {
    let numConsecGroups = 1;

    for (let i = 1; i < n; ++i) {
        if (currCaseString.charAt(i - 1) !== currCaseString.charAt(i)) {
            ++numConsecGroups;
        }
    }

    return (b >= 0) ? n * (a + b) : (n * a) + ((Math.floor(numConsecGroups/2) + 1) * b);
}

var x = parseInt(readline());

for(i = 0; i < x; i++)
{
    var n = readline().split(" ");
    var a = parseInt(n[1]);
    var b = parseInt(n[2]);
    n = parseInt(n[0]);
    var string = readline();

    if(b > 0) print(n * (a + b));
    else if(b === 0) print(n * a);
    else if(n === 1) print(a + b);
    else {
        var substring = [], sum = 0;
        for(j = 0; j < n; j++) {
            var k = j + 1;
            while(string[k] === string[j]) { k++; }
            substring[substring.length] = k - j;
            j = k - 1;
        }
        while(substring !== []) {
            if(substring.length === 1) {
                sum += a * substring[0] + b;
                break;
            }
            sum += a * substring[substring.length - 2] + b;
            if(substring.length === 2) {
                sum += a * substring[1] + b;
                break;
            }
            else {
                substring[substring.length - 3] += substring[substring.length - 1];
                substring = substring.slice(0, substring.length - 2);
            }
        }
        print(sum);
    }
}

"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, a, b] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split("")
      .map((cur) => parseInt(cur));
    if (b >= 0) {
      console.log((a + b) * n);
      continue;
    } else {
      let str = [];
      str.push(arr[0]);
      for (let i = 1; i < n; i++) {
        if (str[str.length - 1] !== arr[i]) str.push(arr[i]);
      }
      if (str.length <= 2) console.log(a * n + b * str.length);
      else {
        let k = Math.floor((str.length + 1) / 2);
        console.log(a * n + b * k);
      }
    }
  }
};
solve();

"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, a, b] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split("")
      .map((cur) => parseInt(cur));
    if (a + b >= 0) {
      console.log((a + b) * n);
      continue;
    } else {
      let cnt1 = 0,
        cnt2 = 0;
      for (let i = 0; i < n; i++) {
        if (arr[i] === 0) cnt1++;
        else cnt2++;
      }
      let i = 0;
      let res = a * cnt2 + b;
      while (i < n) {
        if (arr[i] === 1) {
          let s = i;
          while (i < n) {
            if (arr[i] === 1) {
              if (i - s - 1 > 0) {
                res += a * (i - s - 1) + b;
                cnt1 -= i - s - 1;
              }
              s = i;
            }
            i++;
          }
        }
        i++;
      }
      if (cnt1 !== 0) res += a * cnt1 + b;
      console.log(res);
    }
  }
};
solve();

const stdin = process.openStdin();
let content = '';

stdin.addListener('data', (data) => {
          content += data;
})

stdin.addListener('end', () => {
          content = content.split('\n');
          content.shift();
          content = content.map((string) => string.substring(0, string.length - 1));
          content.pop();
          for (let i = 0; i < content.length; i += 2) {
                    const [n, a, b] = content[i].split(' ').map(string => parseInt(string));
                    console.log(maximumCostDeletion(a, b, content[i + 1]));
          }
})

const maximumCostDeletion = (a, b, str) => {
          let bContribution = str.length;
          if (b < 0) {
                    const startingString = str[0];
                    bContribution = 1;
                   for (let i = 1; i < str.length; i++) {
                             if (str[i] !== str[i - 1] && str[i] === startingString) {
                                   bContribution++;
                             }
                   }
          }
          return (a * str.length) + (b * bContribution);
}

const readline = require('readline');

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

let input = [],
    numTestCases;

rl.on('line', (line) => {
    input.push(line);

    if (input.length === (2 * (+input[0]) + 1)) {
        rl.close();
        numTestCases = +input[0];
        input.shift();
        main();
    }
});

function main() {
    for (let i = 0; i < numTestCases; ++i) {
        let currCaseConsts = input[i].split(' '),
            currCaseString = input[++i],
            n = +currCaseConsts[0],
            a = +currCaseConsts[1],
            b = +currCaseConsts[2];

        console.log(getMaxPoints(currCaseString, n, a, b));
    }
}

function getMaxPoints(currCaseString, n, a, b) {
    let numConsecGroups = 1;

    for (let i = 1; i < n; ++i) {
        if (currCaseString.charAt(i - 1) !== currCaseString.charAt(i)) {
            ++numConsecGroups;
        }
    }

    return (b >= 0) ? n * (a + b) : (n * a) + ((Math.floor(numConsecGroups/2) + 1) * b);
}