DZY loves chessboard, and he enjoys playing with it.He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.You task is to find any suitable placement of chessmen on the given chessboard.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100). Each of the next n lines contains a string of m characters: the j-th character of the i-th string is either "." or "-". A "." means that the corresponding cell (in the i-th row and the j-th column) is good, while a "-" means it is bad.

Output must contain n lines, each line must contain a string of m characters. The j-th character of the i-th string should be either "W", "B" or "-". Character "W" means the chessman on the cell is white, "B" means it is black, "-" means the cell is a bad cell. If multiple answers exist, print any of them. It is guaranteed that at least one answer exists.

NoteIn the first sample, DZY puts a single black chessman. Of course putting a white one is also OK.In the second sample, all 4 cells are good. No two same chessmen share an edge in the sample output.In the third sample, no good cells are adjacent. So you can just put 3 chessmen, no matter what their colors are.

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

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

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

function main() {
	var data = tokenizeIntegers(readline()),
		rowNum = data[0], colNum = data[1],
		rows = [];
	for (var r = 0; r < rowNum; ++r) {
		var line = trim(readline()),
			chars = new Array(colNum);
		for (var c = 0; c < colNum; ++c) {
			if (line.charAt(c) == '.') {
				chars.push((r+c)%2 == 0 ? 'W' : 'B');
			} else {
				chars.push('-');
			}
		}
		rows.push(chars.join(''));
	}
	print(rows.join('\n'));
}

main();

{
    var num = readline(), arr = [];
    num = num.split(' ');
    for (var i = 1; i <= +num[0]; i++)
    {
        var input = readline();
        arr.push(input.split(''));
    }
    var result = function(arr)
    {
        for (var i = 0; i <= arr.length - 1; i++)
        {
            for (var count = 0; count <= arr[i].length - 1; count++)
            {
                if ( i % 2 === 0)
                {
                    if ( (arr[i][count] === '.') && (count % 2 === 0) )
                    {
                        arr[i].splice(count, 1, 'B');
                    }
                    else if (arr[i][count] === '.') arr[i].splice(count, 1, 'W');
                }
                else
                {
                    if ( (arr[i][count] === '.') && (count % 2 === 0) )
                    {
                        arr[i].splice(count, 1, 'W');
                    }
                    else if (arr[i][count] === '.') arr[i].splice(count, 1, 'B');
                }
            }
        }
        return arr;
    }
    var x = result(arr);
	for (var count = 0; count <= x.length - 1; count++)
	{
		print(x[count].join(''));
	}
}

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});
let n, m;
const cells = [];
let numberOfGoodCell = 0;

// listCount = new Array(1001).fill(0);
function solve() {

}

function check() {
    for (let i = 0; i < cells.length; i++) {
        for (let j = 0; j < cells[i].length; j++) {
            if ((cells[i][j] !== '.' || cells[i][j] !== '-') && !checkCellAdjustable(i, j, cells[i][j])) {
                return false;
            }
        }
    }
    return true;
}

function checkCellAdjustable(i, j, char) {
    return !(cells[i][j + 1] === char || cells[i][j - 1] === char || cells[i + 1][j] === char || cells[i - 1][j] === char);
}

rl.on('line', (line) => {
    if (!n && !m) {
        [n, m] = line.split(' ').map(Number);
        return;
    }
    const list = line.split('');
    cells.push(list);
    if (cells.length === n) {
        let charI = 'B';
        for (let i = 0; i < cells.length; i++) {
            let charJ = charI;
            let output = '';
            for (let j = 0; j < cells[i].length; j++) {
                if (cells[i][j] === '.') {
                    cells[i][j] = charJ;
                }
                if (charJ === 'B') {
                    charJ = 'W';
                } else {
                    charJ = 'B';
                }
                output += cells[i][j];
            }
            console.log(output);

            if (charI === 'B') {
                charI = 'W';
            } else {
                charI = 'B';
            }
        }
    }
});

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 [r, c] = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  const board = [];
  const result = [...Array(r).fill(0)].map((_) => Array(c).fill(0));

  for (let i = 0; i < r; i++) {
    const _row = readLine().split("");
    board.push(_row);
  }

  for (let row = 0; row < r; row++) {
    for (let col = 0; col < c; col++) {
      if (board[row][col] === ".") {
        if (row % 2 === 0) {
          if (col % 2 === 0) result[row][col] = "W";
          else result[row][col] = "B";
        } else {
          if (col % 2 !== 0) result[row][col] = "W";
          else result[row][col] = "B";
        }
      } else {
        result[row][col] = board[row][col];
      }
    }
  }

  for (let row = 0; row < r; row++) {
    console.log(result[row].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, m] = readLine()
		.split(' ')
		.map(x => x >> 0);
	let brd = [];
	for (let i = 0; i < n; i++) {
		brd[i] = readLine().split('');
	}

	for (let i = 0; i < n; i++) {
		for (let j = 0; j < m; j++) {
			let ci = i + j;
			if (brd[i][j] !== '-') {
				if (ci & 1) {
					brd[i][j] = 'W';
				} else {
					brd[i][j] = 'B';
				}
			}
		}
	}

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

// Generated by CoffeeScript 1.10.0
(function() {
  var a, i, j, l, line, m, n, o, ref, ref1, ref2, results;

  ref = readline().split(' '), n = ref[0], m = ref[1];

  a = [];

  for (i = j = 0, ref1 = n; 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) {
    a.push(readline());
  }

  for (i = l = 0, ref2 = n; 0 <= ref2 ? l < ref2 : l > ref2; i = 0 <= ref2 ? ++l : --l) {
    line = (function() {
      results = [];
      for (var o = 0; 0 <= m ? o < m : o > m; 0 <= m ? o++ : o--){ results.push(o); }
      return results;
    }).apply(this).map(function(k) {
      if (a[i][k] === '-') {
        return '-';
      } else if ((i + k) % 2 === 0) {
        return 'B';
      } else {
        return 'W';
      }
    });
    print(line.join(''));
  }

}).call(this);

// Generated by CoffeeScript 1.10.0
(function() {
  var j, m, n, ref, results;

  print(((ref = readline().split(' '), n = ref[0], m = ref[1], ref), (function() {
    results = [];
    for (var j = 0; 0 <= n ? j < n : j > n; 0 <= n ? j++ : j--){ results.push(j); }
    return results;
  }).apply(this).map(function(i) {
    var a, j, results;
    a = readline();
    return (function() {
      results = [];
      for (var j = 0; 0 <= m ? j < m : j > m; 0 <= m ? j++ : j--){ results.push(j); }
      return results;
    }).apply(this).map(function(k) {
      if (a[k] === '-') {
        return '-';
      } else if ((i + k) % 2 === 0) {
        return 'B';
      } else {
        return 'W';
      }
    });
  })).join('\n').split(',').join(''));

}).call(this);

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});
let n, m;
const cells = [];
let numberOfGoodCell = 0;

// listCount = new Array(1001).fill(0);
function solve() {

}

function check() {
    for (let i = 0; i < cells.length; i++) {
        for (let j = 0; j < cells[i].length; j++) {
            if ((cells[i][j] !== '.' || cells[i][j] !== '-') && !checkCellAdjustable(i, j, cells[i][j])) {
                return false;
            }
        }
    }
    return true;
}

function checkCellAdjustable(i, j, char) {
    return !(cells[i][j + 1] === char || cells[i][j - 1] === char || cells[i + 1][j] === char || cells[i - 1][j] === char);
}

rl.on('line', (line) => {
    if (!n && !m) {
        [n, m] = line.split(' ').map(Number);
        return;
    }
    const list = line.split('');
    cells.push(list);
    if (cells.length === n) {
        let charI = 'B';
        for (let i = 0; i < cells.length; i++) {
            let charJ = charI;
            let output = '';
            for (let j = 0; j < cells[i].length; j++) {
                if (cells[i][j] === '.') {
                    cells[i][j] = charJ;
                }
                if (charJ === 'B') {
                    charJ = 'A';
                } else {
                    charJ = 'B';
                }
                output += cells[i][j];
            }
            console.log(output);

            if (charI === 'B') {
                charI = 'A';
            } else {
                charI = 'B';
            }
        }
    }
});

{
    var num = readline(), arr = [];
    num = num.split(' ');
    for (var i = 1; i <= +num[0]; i++)
    {
        var input = readline();
        arr.push(input.split(''));
    }
    var result = function(arr)
    {
        for (var i = 0; i <= arr.length - 1; i++)
        {
            for (var count = 0; count <= arr[i].length - 1; count++)
            {
                if ( i % 2 === 0)
                {
                    if ( (arr[i][count] === '.') && (count % 2 === 0) )
                    {
                        arr[i].splice(count, 1, 'B');
                    }
                    else if (arr[i][count] === '.') arr[i].splice(count, 1, 'W');
                }
                else
                {
                    if ( (arr[i][count] === '.') && (count % 2 === 0) )
                    {
                        arr[i].splice(count, 1, 'W');
                    }
                    else if (arr[i][count] === '.') arr[i].splice(count, 1, 'B');
                }
            }
        }
        return arr;
    }
    print(result(arr));
}

{
    var num = readline(), arr = [];
    num = num.split(' ');
    for (var i = 1; i <= +num[0]; i++)
    {
        var input = readline();
        arr.push(input.split(''));
    }
    var result = function(arr)
    {
        for (var i = 0; i <= arr.length - 1; i++)
        {
            for (var count = 0; count <= arr[i].length - 1; count++)
            {
                if ( i % 2 === 0)
                {
                    if ( (arr[i][count] === '.') && (count % 2 === 0) )
                    {
                        arr[i].splice(count, 1, 'B');
                    }
                    else if (arr[i][count] === '.') arr[i].splice(count, 1, 'W');
                }
                else
                {
                    if ( (arr[i][count] === '.') && (count % 2 === 0) )
                    {
                        arr[i].splice(count, 1, 'W');
                    }
                    else if (arr[i][count] === '.') arr[i].splice(count, 1, 'B');
                }
            }
        }
        return arr;
    }
    var x = result(arr);
	for (var count = 0; count <= x.length - 1; count++)
	{
		print(x[count]);
	}
}


Petya has recently learned data structure named "Binary heap".The heap he is now operating with allows the following operations:   put the given number into the heap;  get the value of the minimum element in the heap;  extract the minimum element from the heap; Thus, at any moment of time the heap contains several integers (possibly none), some of them might be equal.In order to better learn this data structure Petya took an empty heap and applied some operations above to it. Also, he carefully wrote down all the operations and their results to his event log, following the format:   insert x — put the element with value x in the heap;  getMin x — the value of the minimum element contained in the heap was equal to x;  removeMin — the minimum element was extracted from the heap (only one instance, if there were many). All the operations were correct, i.e. there was at least one element in the heap each time getMin or removeMin operations were applied.While Petya was away for a lunch, his little brother Vova came to the room, took away some of the pages from Petya's log and used them to make paper boats.Now Vova is worried, if he made Petya's sequence of operations inconsistent. For example, if one apply operations one-by-one in the order they are written in the event log, results of getMin operations might differ from the results recorded by Petya, and some of getMin or removeMin operations may be incorrect, as the heap is empty at the moment they are applied.Now Vova wants to add some new operation records to the event log in order to make the resulting sequence of operations correct. That is, the result of each getMin operation is equal to the result in the record, and the heap is non-empty when getMin ad removeMin are applied. Vova wants to complete this as fast as possible, as the Petya may get back at any moment. He asks you to add the least possible number of operation records to the current log. Note that arbitrary number of operations may be added at the beginning, between any two other operations, or at the end of the log.

The first line of the input contains the only integer n (1 ≤ n ≤ 100 000) — the number of the records left in Petya's journal. Each of the following n lines describe the records in the current log in the order they are applied. Format described in the statement is used. All numbers in the input are integers not exceeding 109 by their absolute value.

The first line of the output should contain a single integer m — the minimum possible number of records in the modified sequence of operations. Next m lines should contain the corrected sequence of records following the format of the input (described in the statement), one per line and in the order they are applied. All the numbers in the output should be integers not exceeding 109 by their absolute value. Note that the input sequence of operations must be the subsequence of the output sequence. It's guaranteed that there exists the correct answer consisting of no more than 1 000 000 operations.

6
insert 1
insert 1
removeMin
removeMin
insert 2
getMin 2

NoteIn the first sample, after number 3 is inserted into the heap, the minimum number is 3. To make the result of the first getMin equal to 4 one should firstly remove number 3 from the heap and then add number 4 into the heap.In the second sample case number 1 is inserted two times, so should be similarly removed twice.

var binaryHeap = function(comp) {

  comp = comp || function(a, b) {
    return a < b;
  };

  var arr = [];

  var swap = function(a, b) {
    var temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
  };

  var bubbleDown = function(pos) {
    var left = 2 * pos + 1;
    var right = left + 1;
    var largest = pos;
    if (left < arr.length && comp(arr[left], arr[largest])) {
      largest = left;
    }
    if (right < arr.length && comp(arr[right], arr[largest])) {
      largest = right;
    }
    if (largest != pos) {
      swap(largest, pos);
      bubbleDown(largest);
    }
  };

  var bubbleUp = function(pos) {
    if (pos <= 0) {
      return;
    }
    var parent = Math.floor((pos - 1) / 2);
    if (comp(arr[pos], arr[parent])) {
      swap(pos, parent);
      bubbleUp(parent);
    }
  };

  var that = {};

  that.getMin = function() {
      return arr[0];
  }

  that.pop = function() {
    if (arr.length === 0) {
      throw new Error("pop() called on emtpy binary heap");
    }
    var value = arr[0];
    var last = arr.length - 1;
    arr[0] = arr[last];
    arr.length = last;
    if (last > 0) {
      bubbleDown(0);
    }
    return value;
  };

  that.push = function(value) {
    arr.push(value);
    bubbleUp(arr.length - 1);
  };

  that.size = function() {
    return arr.length;
  };

  return that;
};

var n = Number(readline());

var heap = new binaryHeap();

var a = [];

for (var it = 1; it <= n; ++it) {
    var raw_line = readline();
    var line = raw_line.split(' ');
    if (line.length === 1) {
        if (heap.size() === 0) {
            heap.push(0);
            a.push("insert 0");
        }
        heap.pop();
    } else {
        var command = line[0];
        var number = parseInt(line[1]);
        if (command === "insert") {
            heap.push(number);
        } else {
            while (heap.size() > 0 && heap.getMin() < number) {
                heap.pop();
                a.push("removeMin")
            }
            if (heap.size() === 0 || heap.getMin() !== number) {
                heap.push(number);
                a.push("insert " + number);
            }
            //heap.pop();
        }
    }
    a.push(raw_line);
    //print(heap.size());
}

print(a.length);
for (var i = 0; i < a.length; ++i) {
    print(a[i]);
}

var binaryHeap = function(comp) {

  comp = comp || function(a, b) {
    return a < b;
  };

  var arr = [];

  var swap = function(a, b) {
    var temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
  };

  var bubbleDown = function(pos) {
    var left = 2 * pos + 1;
    var right = left + 1;
    var largest = pos;
    if (left < arr.length && comp(arr[left], arr[largest])) {
      largest = left;
    }
    if (right < arr.length && comp(arr[right], arr[largest])) {
      largest = right;
    }
    if (largest != pos) {
      swap(largest, pos);
      bubbleDown(largest);
    }
  };

  var bubbleUp = function(pos) {
    if (pos <= 0) {
      return;
    }
    var parent = Math.floor((pos - 1) / 2);
    if (comp(arr[pos], arr[parent])) {
      swap(pos, parent);
      bubbleUp(parent);
    }
  };

  var that = {};

  that.getMin = function() {
      return arr[0];
  }

  that.pop = function() {
    if (arr.length === 0) {
      throw new Error("pop() called on emtpy binary heap");
    }
    var value = arr[0];
    var last = arr.length - 1;
    arr[0] = arr[last];
    arr.length = last;
    if (last > 0) {
      bubbleDown(0);
    }
    return value;
  };

  that.push = function(value) {
    arr.push(value);
    bubbleUp(arr.length - 1);
  };

  that.size = function() {
    return arr.length;
  };

  return that;
};

var n = Number(readline());

var heap = new binaryHeap(function(x) { return x; });

var a = [];

for (var it = 1; it <= n; ++it) {
    var raw_line = readline();
    var line = raw_line.split(' ');
    if (line.length === 1) {
        if (heap.size() === 0) {
            heap.push(0);
            a.push("insert 0");
        }
        heap.pop();
    } else {
        var command = line[0];
        var number = parseInt(line[1]);
        if (command === "insert") {
            heap.push(number);
        } else {
            while (heap.size() > 0 && heap.getMin() < number) {
                heap.pop();
                a.push("removeMin")
            }
            if (heap.size() === 0 || heap.getMin() !== number) {
                heap.push(number);
                a.push("insert " + number);
            }
            //heap.pop();
        }
    }
    a.push(raw_line);
}

print(a.length);
for (var i = 0; i < a.length; ++i) {
    print(a[i]);
}

var binaryHeap = function(comp) {

  comp = comp || function(a, b) {
    return a < b;
  };

  var arr = [];

  var swap = function(a, b) {
    var temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
  };

  var bubbleDown = function(pos) {
    var left = 2 * pos + 1;
    var right = left + 1;
    var largest = pos;
    if (left < arr.length && comp(arr[left], arr[largest])) {
      largest = left;
    }
    if (right < arr.length && comp(arr[right], arr[largest])) {
      largest = right;
    }
    if (largest != pos) {
      swap(largest, pos);
      bubbleDown(largest);
    }
  };

  var bubbleUp = function(pos) {
    if (pos <= 0) {
      return;
    }
    var parent = Math.floor((pos - 1) / 2);
    if (comp(arr[pos], arr[parent])) {
      swap(pos, parent);
      bubbleUp(parent);
    }
  };

  var that = {};

  that.getMin = function() {
      return arr[0];
  }

  that.pop = function() {
    if (arr.length === 0) {
      throw new Error("pop() called on emtpy binary heap");
    }
    var value = arr[0];
    var last = arr.length - 1;
    arr[0] = arr[last];
    arr.length = last;
    if (last > 0) {
      bubbleDown(0);
    }
    return value;
  };

  that.push = function(value) {
    arr.push(value);
    bubbleUp(arr.length - 1);
  };

  that.size = function() {
    return arr.length;
  };

  return that;
};

var n = Number(readline());

var heap = new binaryHeap(function(x) { return x; });

var a = [];

for (var it = 1; it <= n; ++it) {
    var raw_line = readline();
    var line = raw_line.split(' ');
    if (line.length === 1) {
        if (heap.size() === 0) {
            heap.push(0);
            a.push("insert 0");
        }
        heap.pop();
    } else {
        var command = line[0];
        var number = parseInt(line[1]);
        if (command === "insert") {
            heap.push(number);
        } else {
            while (heap.size() > 0 && heap.getMin() < number) {
                heap.pop();
                a.push("removeMin")
            }
            if (heap.size() === 0 || heap.getMin() !== number) {
                heap.push(number);
                a.push("insert " + number);
            }
            heap.pop();
        }
    }
    a.push(raw_line);
}

print(a.length);
for (var i = 0; i < a.length; ++i) {
    print(a[i]);
}

function BinaryHeap(scoreFunction){
  this.content = [];
  this.scoreFunction = scoreFunction;
}

BinaryHeap.prototype = {
  push: function(element) {
    // Add the new element to the end of the array.
    this.content.push(element);
    // Allow it to bubble up.
    this.bubbleUp(this.content.length - 1);
  },

  getMin: function() {
    return this.content[0];
  },

  pop: function() {
    // Store the first element so we can return it later.
    var result = this.content[0];
    // Get the element at the end of the array.
    var end = this.content.pop();
    // If there are any elements left, put the end element at the
    // start, and let it sink down.
    if (this.content.length > 0) {
      this.content[0] = end;
      this.sinkDown(0);
    }
    return result;
  },

  remove: function(node) {
    var length = this.content.length;
    // To remove a value, we must search through the array to find
    // it.
    for (var i = 0; i < length; i++) {
      if (this.content[i] != node) continue;
      // When it is found, the process seen in 'pop' is repeated
      // to fill up the hole.
      var end = this.content.pop();
      // If the element we popped was the one we needed to remove,
      // we're done.
      if (i == length - 1) break;
      // Otherwise, we replace the removed element with the popped
      // one, and allow it to float up or sink down as appropriate.
      this.content[i] = end;
      this.bubbleUp(i);
      this.sinkDown(i);
      break;
    }
  },

  size: function() {
    return this.content.length;
  },

  bubbleUp: function(n) {
    // Fetch the element that has to be moved.
    var element = this.content[n], score = this.scoreFunction(element);
    // When at 0, an element can not go up any further.
    while (n > 0) {
      // Compute the parent element's index, and fetch it.
      var parentN = Math.floor((n + 1) / 2) - 1,
      parent = this.content[parentN];
      // If the parent has a lesser score, things are in order and we
      // are done.
      if (score >= this.scoreFunction(parent))
        break;

      // Otherwise, swap the parent with the current element and
      // continue.
      this.content[parentN] = element;
      this.content[n] = parent;
      n = parentN;
    }
  },

  sinkDown: function(n) {
    // Look up the target element and its score.
    var length = this.content.length,
    element = this.content[n],
    elemScore = this.scoreFunction(element);

    while(true) {
      // Compute the indices of the child elements.
      var child2N = (n + 1) * 2, child1N = child2N - 1;
      // This is used to store the new position of the element,
      // if any.
      var swap = null;
      // If the first child exists (is inside the array)...
      if (child1N < length) {
        // Look it up and compute its score.
        var child1 = this.content[child1N],
        child1Score = this.scoreFunction(child1);
        // If the score is less than our element's, we need to swap.
        if (child1Score < elemScore)
          swap = child1N;
      }
      // Do the same checks for the other child.
      if (child2N < length) {
        var child2 = this.content[child2N],
        child2Score = this.scoreFunction(child2);
        if (child2Score < (swap == null ? elemScore : child1Score))
          swap = child2N;
      }

      // No need to swap further, we are done.
      if (swap == null) break;

      // Otherwise, swap and continue.
      this.content[n] = this.content[swap];
      this.content[swap] = element;
      n = swap;
    }
  }
};

var n = Number(readline());

var heap = new BinaryHeap(function(x) { return x; });

var a = [];

for (var it = 1; it <= n; ++it) {
    var raw_line = readline();
    var line = raw_line.split(' ');
    if (line.length === 1) {
        if (heap.size() === 0) {
            a.push("insert 0");
        }
        heap.pop();
    } else {
        var command = line[0];
        var number = parseInt(line[1]);
        if (command === "insert") {
            heap.push(number);
        } else {
            while (heap.size() > 0 && heap.getMin() < number) {
                heap.pop();
                a.push("removeMin")
            }
            if (heap.size() === 0 || heap.getMin() !== number) {
                heap.push(number);
                a.push("insert " + number);
            }
            heap.pop();
        }
    }
    a.push(raw_line);
}

print(a.length);
for (var i = 0; i < a.length; ++i) {
    print(a[i]);
}


While performing complex market analysis William encountered the following problem:For a given array $$$a$$$ of size $$$n$$$ and a natural number $$$e$$$, calculate the number of pairs of natural numbers $$$(i, k)$$$ which satisfy the following conditions:   $$$1 \le i, k$$$  $$$i + e \cdot k \le n$$$.  Product $$$a_i \cdot a_{i + e} \cdot a_{i + 2 \cdot e} \cdot \ldots \cdot a_{i + k \cdot e} $$$ is a prime number. A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$e$$$ $$$(1 \le e \le n \le 2 \cdot 10^5)$$$, the number of items in the array and number $$$e$$$, respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^6)$$$, the contents of the array. 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 answer in the following format: Output one line containing the number of pairs of numbers $$$(i, k)$$$ which satisfy the conditions.

NoteIn the first example test case two pairs satisfy the conditions:   $$$i = 2, k = 1$$$, for which the product is: $$$a_{2} \cdot a_{5} = 2$$$ which is a prime number.  $$$i = 3, k = 1$$$, for which the product is: $$$a_{3} \cdot a_{6} = 19$$$ which is a prime number. In the second example test case there are no pairs that satisfy the conditions.In the third example test case four pairs satisfy the conditions:   $$$i = 1, k = 1$$$, for which the product is: $$$a_{1} \cdot a_{4} = 2$$$ which is a prime number.  $$$i = 1, k = 2$$$, for which the product is: $$$a_{1} \cdot a_{4} \cdot a_{7} = 2$$$ which is a prime number.  $$$i = 3, k = 1$$$, for which the product is: $$$a_{3} \cdot a_{6} = 2$$$ which is a prime number.  $$$i = 6, k = 1$$$, for which the product is: $$$a_{6} \cdot a_{9} = 2$$$ which is a prime number. In the fourth example test case there are no pairs that satisfy the conditions.In the fifth example test case five pairs satisfy the conditions:   $$$i = 1, k = 1$$$, for which the product is: $$$a_{1} \cdot a_{2} = 2$$$ which is a prime number.  $$$i = 1, k = 2$$$, for which the product is: $$$a_{1} \cdot a_{2} \cdot a_{3} = 2$$$ which is a prime number.  $$$i = 1, k = 3$$$, for which the product is: $$$a_{1} \cdot a_{2} \cdot a_{3} \cdot a_{4} = 2$$$ which is a prime number.  $$$i = 2, k = 1$$$, for which the product is: $$$a_{2} \cdot a_{3} = 2$$$ which is a prime number.  $$$i = 2, k = 2$$$, for which the product is: $$$a_{2} \cdot a_{3} \cdot a_{4} = 2$$$ which is a prime number. In the sixth example test case there are no pairs that satisfy the conditions.

"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.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

function main() {
  var t = +(readline());
  while (t--) {
    solution();
  }
}

function solution() {
  let inputLine = readline().split(" ");
  let n = +inputLine[0];
  let e = +inputLine[1];

  let array = [], dp = new Array(n).fill(0);

  let arrayLine = readline().split(" ");
  for (let i = 0; i < n; i++)
    array[i] = +arrayLine[i];

  for (let i = n-1; i >= 0; i--) {
    if (isPrime(array[i])) {
      let k = 1;
      while(i + k*e < n && array[i + k*e] === 1)
        k++;
      dp[i] = k-1;
    }
    else if (array[i] === 1 && i + e < n) {
        if (isPrime(array[i + e])) dp[i] = dp[i + e]+1;
        else if (array[i + e] === 1) dp[i] = dp[i + e];
    }
  }

  const sum = dp.reduce(function(total, item) {
    return total+item;
  });

  console.log(sum);
}

function isPrime(num) {
  if (num === 2) return true;
    if (num === 1 || num%2 === 0 ) return false;

    let root = Math.floor(Math.sqrt(num));
    root += (root%2)-1;
    while (root > 1) {
      if (num%root === 0)
        return false;
      root -= 2;
    }
    return true;
}

"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.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

function main() {
  var t = +(readline());
  while (t--) {
    solution();
  }
}

function solution() {
  let inputLine = readline().split(" ");
  let n = +inputLine[0];
  let e = +inputLine[1];

  let array = [], dp = new Array(n).fill(0);

  let arrayLine = readline().split(" ");
  for (let i = 0; i < n; i++)
    array[i] = +arrayLine[i];

  for (let i = n-1; i >= 0; i--) {
    let k = 1;
    if (isPrime(array[i])) {
      while(i + k*e < n && array[i + k*e] === 1)
        k++;
      dp[i] = k-1;
    }
    else if (array[i] === 1 && i + k*e < n) {
        if (isPrime(array[i + k*e])) dp[i] = dp[i + k*e]+1;
        else if (array[i + k*e] === 1) dp[i] = dp[i + k*e];
    }
  }

  const sum = dp.reduce(function(total, item) {
    return total+item;
  });

  console.log(sum);
}

function isPrime(num) {
  if (num === 2) return true;
    if (num === 1 || num%2 === 0 ) return false;

    let root = Math.floor(Math.sqrt(num));
    root += (root%2)-1;
    while (root > 1) {
      if (num%root === 0)
        return false;
      root -= 2;
    }
    return true;
}

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

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

const isPrime = num => {
	for(let i = 2, s = Math.sqrt(num); i <= s; i++)
		if(num % i === 0) return false;
	return num > 1;
}

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

		let l = [], r = [];
		for (let i = 0; i < e; i++) {
			for (let j = i, cnt = 0; j < n; j += e) {
				if (a[j] == 1) {
					cnt++;
				}
				else {
					l[j] = cnt;
					cnt = 0;
				}
			}
			for (let j = n - i - 1, cnt = 0; j >= 0; j -= e) {
				if (a[j] == 1) {
					cnt++;
				}
				else {
					r[j] = cnt;
					cnt = 0;
				}
			}
		}

		let ans = 0;
		for (let i = 0; i < n; i++) {
			if (isPrime(a[i])) {
				ans += (l[i] + 1)*(r[i] + 1) - 1;
			}
		}
		console.log(ans);
	}
}

var isPrime = [];
for(var i=0; i<1000002; i++){
  isPrime.push(1);
}

function complex_market_analysis(){

  var inp = readline().split(" ");
	var n = parseInt(inp[0]);
	var e = parseInt(inp[1]);
	var a = readline().split(" ").map(x=>parseInt(x));

	var w=[];
	for(var i=0; i<n; i++){
	  w.push(1);
	}
	var r = 0;
	for(var i=0; i<n; i++){
		if (w[i]){
			var j = 0;
			var z = i;
			var last = -1;
			var last1 = -1;
			var p = 0;
			while (z < n){
				w[z] = 0;
				var v = a[z];

				if (v > 1){
				  last1 = last;
					last = j;
					p = isPrime[v];
					if (p){
						r -= 1;
					}
				}
				if (p){
					r += (last - last1)
				}
				z += e
				j += 1
			}
			}

	}
	print(r);
}

function prime_pairs(){
	var M = isPrime.length;
	isPrime[1] = 0;
	isPrime[0] = 0;
	var i = 2;
	while (i * i < M){
		if (isPrime[i]){
			var j = i * i;
			while (j < M){
				isPrime[j] = 0;
				j += i;
			}
		}
		i += 1
	}
var t = parseInt(readline());
for (var i=0; i<t; i++){
  complex_market_analysis();
}
}

prime_pairs();

    "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.split("\n");
      main();
    });
    function readline() {
      return inputString[currentLine++];
    }

    function main() {
      var t = +(readline());
      while (t--) {
        solution();
      }
    }

    function solution() {
      let inputLine = readline().split(" ");
      let n = +inputLine[0];
      let e = +inputLine[1];

      let array = [], dp = new Array(n).fill(0);

      let arrayLine = readline().split(" ");
      for (let i = 0; i < n; i++)
        array[i] = +arrayLine[i];

      for (let i = n-1; i >= 0; i--) {
        let k = 1;
        if (isPrime(array[i])) {
          while(i + k*e < n && array[i + k*e] === 1)
            k++;
          dp[i] = k-1;
        }
        else if (array[i] === 1) {
            if (isPrime(array[i + k*e])) { dp[i] = dp[i + k*e]+1; break;}
            else if (array[i + k*e] === 1) {dp[i] = dp[i + k*e]; break;}
        }
      }

      const sum = dp.reduce(function(total, item) {
        return total+item;
      });

      console.log(sum);
    }

    function isPrime(num) {
      if (num === 2) return true;
        if (num === 1 || num%2 === 0 ) return false;

        let root = Math.floor(Math.sqrt(num));
        root += (root%2)-1;
        while (root > 1) {
          if (num%root === 0)
            return false;
          root -= 2;
        }
        return true;
    }

"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.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********
function main() {
  let t = parseInt(readline());
  while (t--)
    solution();
}

function solution() {
  let inputLine = readline().split(" ");
  let n = +inputLine[0];
  let e = +inputLine[1];

  let array = [], dp = [];
  array[0] = 0;

  let arrayLine = readline().split(" ");
  for (let i = 0; i < n; i++)
    array[i] = +arrayLine[i];

  // for (let i = 0; i < n; i++) {
  //   if (isPrime(array[i])) {
  //         let t = i-e;
  //         while (t >= 0 && t < n && array[t] === 1) {
  //           dp[i]++;
  //       }
  //     }
  //   }
  console.log(array);
}

function isPrime(num) {
  if (num === 2) return true;
    if (num === 1 || num%2 === 0 ) return false;

    let root = Math.floor(Math.sqrt(num));
    root += (root%2)-1;
    while (root > 1) {
      if (num%root === 0)
        return false;
      root -= 2;
    }
    return true;
}

var isPrime = [];
for(var i=0; i<1000002; i++){
  isPrime.push(1);
}

function complex_market_analysis(){
  // var n = 9;
  // var e = 3;
  // var a = [2,4,2,1,1,1,1,4,2];
  var inp = readline().split(" ");
	var n = parseInt(inp[0]);
	print('n', n);
	var e = parseInt(inp[0]);
	print('e', e);
	var a = readline().split(" ").map(x=>parseInt(x));
	print('a', a);

	var w=[];
	for(var i=0; i<n; i++){
	  w.push(1);
	}
	var r = 0;
	for(var i=0; i<n; i++){
		if (w[i]){
			var j = 0;
			var z = i;
			var last = -1;
			var last1 = -1;
			var p = 0;
			while (z < n){
				w[z] = 0;
				var v = a[z];

				if (v > 1){
				  last1 = last;
					last = j;
					p = isPrime[v];
					if (p){
						r -= 1;
					}
				}
				if (p){
					r += (last - last1)
				}
				z += e
				j += 1
			}
			}

	}
	print(r);
}

function prime_pairs(){
	var M = isPrime.length;
	isPrime[1] = 0;
	isPrime[0] = 0;
	var i = 2;
	while (i * i < M){
		if (isPrime[i]){
			var j = i * i;
			while (j < M){
				isPrime[j] = 0;
				j += i;
			}
		}
		i += 1
	}
var t = parseInt(readline());
for (var i=0; i<t; i++){
  complex_market_analysis();
}
}

prime_pairs();

var isPrime = [];
for(var i=0; i<1000002; i++){
  isPrime.push(1);
}

function complex_market_analysis(){
  // var n = 9;
  // var e = 3;
  // var a = [2,4,2,1,1,1,1,4,2];
  var inp = readline().split(" ");
	var n = parseInt(inp[0]);
	var e = parseInt(inp[0]);
	var a = readline().split(" ").map(x=>parseInt(x));

	var w=[];
	for(var i=0; i<n; i++){
	  w.push(1);
	}
	var r = 0;
	for(var i=0; i<n; i++){
		if (w[i]){
			var j = 0;
			var z = i;
			var last = -1;
			var last1 = -1;
			var p = 0;
			while (z < n){
				w[z] = 0;
				var v = a[z];

				if (v > 1){
				  last1 = last;
					last = j;
					p = isPrime[v];
					if (p){
						r -= 1;
					}
				}
				if (p){
					r += (last - last1)
				}
				z += e
				j += 1
			}
			}

	}
	print(r);
}

function prime_pairs(){
	var M = isPrime.length;
	isPrime[1] = 0;
	isPrime[0] = 0;
	var i = 2;
	while (i * i < M){
		if (isPrime[i]){
			var j = i * i;
			while (j < M){
				isPrime[j] = 0;
				j += i;
			}
		}
		i += 1
	}
var t = parseInt(readline());
for (var i=0; i<t; i++){
  complex_market_analysis();
}
}

prime_pairs();


There are $$$n$$$ trees in a park, numbered from $$$1$$$ to $$$n$$$. The initial height of the $$$i$$$-th tree is $$$h_i$$$.You want to water these trees, so they all grow to the same height.The watering process goes as follows. You start watering trees at day $$$1$$$. During the $$$j$$$-th day you can:   Choose a tree and water it. If the day is odd (e.g. $$$1, 3, 5, 7, \dots$$$), then the height of the tree increases by $$$1$$$. If the day is even (e.g. $$$2, 4, 6, 8, \dots$$$), then the height of the tree increases by $$$2$$$.  Or skip a day without watering any tree. Note that you can't water more than one tree in a day. Your task is to determine the minimum number of days required to water the trees so they grow to the same height.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of trees. The second line of the test case contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$ ($$$\sum n \le 3 \cdot 10^5$$$).

For each test case, print one integer — the minimum number of days required to water the trees, so they grow to the same height.

NoteConsider the first test case of the example. The initial state of the trees is $$$[1, 2, 4]$$$.  During the first day, let's water the first tree, so the sequence of heights becomes $$$[2, 2, 4]$$$;  during the second day, let's water the second tree, so the sequence of heights becomes $$$[2, 4, 4]$$$;  let's skip the third day;  during the fourth day, let's water the first tree, so the sequence of heights becomes $$$[4, 4, 4]$$$. Thus, the answer is $$$4$$$.

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

function solve(n, data, max) {
  let b = 0,
    a = 0
  for (let i = 0; i < n; i++) {
    let num = max - data[i]
    if (num % 2) b++
    a += Math.floor(num / 2)
  }
  // if (b > a) return b * 2 - 1
  let x = Math.max(Math.floor((a - b) / 3), 0)
  a -= x
  b += 2 * x
  if (b === a - 2) {
    a--
    b += 2
  }
  if (b > a) return b * 2 - 1
  return a * 2
}

void (function main() {
  const _ = Number(inputs[0])
  let res = []

  for (let __ = 0; __ < _; __++) {
    let n = Number(inputs[__ * 2 + 1])
    const data = inputs[__ * 2 + 2].trim().split(' ').map(Number)
    let t = -1
    for (let [k, v] of data.entries()) {
      if (t === -1 || data[t] < v) t = k
    }

    let ans = solve(n, data, data[t])

    ans = Math.min(ans, solve(n, data, data[t] + 1))

    res.push(ans)
  }

  console.log(res.join('\n'))
})()

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

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

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

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

		const ans = [];
		let goal = 0;
		for (let i = 0; i < n; i++) goal = Math.max(goal, h[i]);
		for (let round = 0; round < 2; round++, goal++) {
			let need = 0, oddReq = 0, oddHas;
			for (let i = 0; i < n; i++) {
				need += goal - h[i];
				oddReq += (goal- h[i]) & 1;
			}
			ans[round] = Math.ceil(need*2/3);
			oddHas = Math.ceil(ans[round]/2);
			if (oddReq > oddHas) {
				ans[round] += (oddReq - oddHas) * 2 - (ans[round]%2 == 0 ? 1 : 0);
			}
			//console.log({oddHas});
		}

		console.log(Math.min(...ans));
	}
}

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

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

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

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

		const ans = [];
		let goal = 0;
		for (let i = 0; i < n; i++) goal = Math.max(goal, h[i]);
		for (let round = 0; round < 2; round++, goal++) {
			let need = 0, oddReq = 0, oddHas;
			for (let i = 0; i < n; i++) {
				need += goal - h[i];
				oddReq += (goal- h[i]) & 1;
			}
			ans[round] = Math.ceil(need*2/3);
			oddHas = Math.ceil(ans/2);
			//console.log({goal, need, oddReq, oddHas, ans});
			if (oddReq > oddHas) {
				ans[round] += (oddReq - oddHas) * 2 - (ans%2 == 0 ? 1 : 0);
			}
		}

		console.log(Math.min(...ans));
	}
}

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

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

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

const check = (a, days, max) => {
    let twos = div(days, 2);
    let ones = div(days + 1, 2);

    for (const num of a) {
        if (num === max) continue;
        let diff = max - num;
        if (diff % 2 === 1) {
            ones--;
            diff--;
        }
        if (ones < 0) return false;
        if (diff === 0) continue;
        let used2s = Math.min(div(diff, 2), twos);
        twos -= used2s;
        diff -= used2s * 2;
        if (diff === 0) continue;
        let used1s = Math.min(diff, ones);
        ones -= used1s;
        diff -= used1s;
        if (diff !== 0) return false;
    }
    return true;
}

const calc = (n, a)=>{
    if (n === 1) return 0;

    let max = a[0];
    for (const num of a) {
        max = Math.max(max, num);
    }

    let l = 0, r = 300000000000000;
    let mid;
    while (l < r) {
        mid = l + div((r - l), 2);
        // console.log(`mid`, mid);
        const res = check(a, mid, max) || check(a, mid, max + 1);
        // console.log(`res`, res);
        if (!res) {
            l = mid + 1;
        } else {
            r = mid;
        }
    }

    return r;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        let a = ra();
        console.log(`${calc(n, a)}`);
    }
}

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) {
    let max = -Infinity
    for (let i = 0; i < arr.length; i++) {
        max = Math.max(max, arr[i])
    }
    return Math.min(help(n, arr, max), help(n, arr, max + 1))
}
function help(n, arr, max) {
    //
    let odd = 0
    let even = 0
    for (let i = 0; i < arr.length; i++) {
        const d = max - arr[i]
        if (d & 1) {
            odd++
        }
        even += Math.floor(d / 2)
        // const r = d % 3
        // if (r === 1) {
        //     odd++
        // } else if (r === 2) {
        //     even++
        // }
        // ans += 2 * Math.floor(d / 3)
    }
// console.log(odd, even)
    let ans = 0
    if (odd > even) {
        ans = 2 * odd - 1
    } else {
        const diff = even - odd
        const k = Math.floor(diff / 3)
        const r = diff % 3
        ans = 2 * (odd + 2 * k)
        if (r === 1) {
            ans += 2
        } else if (r === 2) {
            ans += 3
        }
    }
    return ans
}

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

module.exports = E;

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

const MOD = 32768;

let can_achieve = (h, days, goal)=>{
  let doubles = Math.floor(days/2);
  let ones = Math.floor((days+1)/2);
  //l({doubles, ones, days})
  let leftovers = [];
  for (let x of h){
    if (goal-x>0){
      let g = goal-x;
      if (g%2){
        g--;
        ones--;
      }
      leftovers.push(g);
    }
  }
  //l({leftovers})
  if (ones<0)
    return false;
  for (let l of leftovers){
    let deduct_doubles = Math.min(doubles, Math.floor(l/2));
    doubles -= deduct_doubles;
    l -= deduct_doubles*2;
    let deduct_ones = Math.min(ones, l);
    ones -= deduct_ones;
    l -= deduct_ones;
    if (l>0)
      return false;
  }
  //l('yes')
  return true
};

const calc = (n, h)=>{
  h.sort((a, b)=>a-b);
  let min = h[0];
  let max = h[h.length-1]
  if (min==max)
    return 0;
  let l = 0, r = 3*1e14+5;
  while (l<r){
    let m = Math.floor((l+r)/2);
    if (can_achieve(h, m, max) || can_achieve(h, m, max+1))
      r = m;
    else
      l = m+1;
  }
  if (can_achieve(h, l-1, max) || can_achieve(h, l-1, max+1))
    return l-1;
  if (can_achieve(h, l, max) || can_achieve(h, l, max+1))
    return l;
  return l+1;
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let h = ra();
      l('ans')
      print(calc(n, h));
    }
}

E.calc = calc;

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

function solve(n, data, max) {
  let b = 0,
    a = 0
  for (let i = 0; i < n; i++) {
    let num = max - data[i]
    if (num % 2) b++
    a += Math.floor(num / 2)
  }
  // if (b > a) return b * 2 - 1
  let x = Math.max(Math.floor((a - b) / 3), 0)
  a -= x
  b += 2 * x
  if (b === a - 2) {
    a--
    b += 2
  }
  if (b > a) return b * 2 - 1
  return a * 2
}

void (function main() {
  const _ = Number(inputs[0])
  let res = []

  for (let __ = 0; __ < _; __++) {
    let n = Number(inputs[__ * 2 + 1])
    const data = inputs[__ * 2 + 2].trim().split(' ').map(Number)
    let t = -1
    for (let [k, v] of data.entries()) {
      if (t === -1 || data[t] < v) t = k
    }

    let ans = solve(n, data, data[t])
    data[t]++
    ans = Math.min(ans, solve(n, data, data[t]))

    res.push(ans)
  }

  console.log(res.join('\n'))
})()

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

function solve(n, data, max) {
  let b = 0,
    a = 0
  for (let i = 0; i < n; i++) {
    let num = max - data[i]
    if (num % 2) b++
    a += Math.floor(num / 2)
  }
  // if (b > a) return b * 2 - 1
  let x = Math.max(Math.floor((a - b) / 3), 0)
  a -= x
  b += 2 * x
  if (b === a - 2) {
    a--
    b += 2
  }
  if (b > a) return b * 2 - 1
  return a * 2
}

void (function main() {
  const _ = Number(inputs[0])
  let res = []

  for (let __ = 0; __ < _; __++) {
    let n = Number(inputs[__ * 2 + 1])
    const data = inputs[__ * 2 + 2].trim().split(' ').map(Number)
    let t = -1
    for (let [k, v] of data.entries()) {
      if (t === -1 || data[t] < v) t = k
    }

    let ans = solve(n, data, data[t])
    data[t]++
    ans = Math.min(ans, solve(n, data, data[t]) + 1)

    res.push(ans)
  }

  console.log(res.join('\n'))
})()

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

function solve(n, data, max) {
  let b = 0,
    a = 0
  for (let i = 0; i < n; i++) {
    let num = max - data[i]
    if (num % 2) b++
    a += Math.floor(num / 2)
  }
  if (b > a) return b * 2 - 1
  let x = Math.ceil((a - b) / 3)
  a -= x
  b += 2 * x
  return a + b
}

void (function main() {
  const _ = Number(inputs[0])
  let res = []

  for (let __ = 0; __ < _; __++) {
    let n = Number(inputs[__ * 2 + 1])
    const data = inputs[__ * 2 + 2].trim().split(' ').map(Number)
    let t = -1
    for (let [k, v] of data.entries()) {
      if (t === -1 || data[t] < v) t = k
    }

    let ans = solve(n, data, data[t])
    data[t]++
    ans = Math.min(ans, solve(n, data, data[t]) + 1)

    res.push(ans)
  }

  console.log(res.join('\n'))
})()

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

function solve(n, data) {
  let b = 0,
    a = 0,
    max = Math.max(...data)
  for (let i = 0; i < n; i++) {
    let num = max - data[i]
    if (num % 2) b++
    a += Math.floor(num / 2)
  }
  let x = Math.ceil((a - b) / 3)
  a -= x
  b += 2 * x
  return a + b
}
void (function main() {
  const _ = Number(inputs[0])
  let res = []

  for (let __ = 0; __ < _; __++) {
    let n = Number(inputs[__ * 2 + 1])
    const data = inputs[__ * 2 + 2].trim().split(' ').map(Number)

    res.push(solve(n, data))
  }

  console.log(res.join('\n'))
})()

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

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

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

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

		const goal = Math.max(...h);

		let need = 0, oddReq = 0, oddHas;
		for (let i = 0; i < n; i++) {
			need += goal - h[i];
			oddReq += (goal- h[i]) & 1;
		}

		let ans = Math.ceil(need*2/3);
		oddHas = Math.ceil(ans/2);
		if (oddReq > oddHas) {
			ans += (oddReq - oddHas) * 2 - (ans%2 == 0 ? 1 : 0);
		}

		console.log(ans);
	}
}

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

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

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

const check = (a, days) => {
    let twos = div(days, 2);
    let ones = div(days + 1, 2);

    let max = a[0];
    for (const num of a) {
        max = Math.max(max, num);
    }

    for (const num of a) {
        if (num === max) continue;
        let diff = max - num;
        if (diff % 2 === 1) {
            ones--;
            diff--;
        }
        if (ones < 0) return false;
        if (diff === 0) continue;
        let used2s = Math.min(div(diff, 2), twos);
        twos -= used2s;
        diff -= used2s * 2;
        if (diff === 0) continue;
        let used1s = Math.min(diff, ones);
        ones -= used1s;
        diff -= used1s;
        if (diff !== 0) return false;
    }
    return true;
}

const calc = (n, a)=>{
    if (n === 1) return 0;

    let l = 0, r = 300000000000000;
    let mid;
    while (l < r) {
        mid = l + div((r - l), 2);
        // console.log(`mid`, mid);
        const res = check(a, mid);
        // console.log(`res`, res);
        if (!res) {
            l = mid + 1;
        } else {
            r = mid;
        }
    }

    return r;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        let a = ra();
        console.log(`${calc(n, a)}`);
    }
}

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

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

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

const calc = (n, a)=>{
    if (n === 1) return 0;
    let res = 0;

    let max = a[0];
    for (const num of a) {
        max = Math.max(max, num);
    }
    let rem = 0;
    let count = 0;
    for (const num of a) {
        if (num !== max) {
            rem += max - num;
            count++;
        }
    }

    const days2 = div(rem, 3);
    // console.log(`days2`, days2);
    const left = rem % 3;
    // console.log(`left`, left);
    res = (days2 * 2) + (left === 1 ? 1 : (left === 2 ? 2 : 0));

    return res;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        let a = ra();
        console.log(`${calc(n, a)}`);
    }
}

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

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

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

const calc = (n, a)=>{
    if (n === 1) return 0;
    let res = 0;

    let max = a[0];
    for (const num of a) {
        max = Math.max(max, num);
    }
    let rem = 0;
    let count = 0;
    for (const num of a) {
        if (num !== max) {
            rem += max - num;
            count++;
        }
    }

    const days2 = div(rem, 3);
    const left = rem % 3;
    res = (days2 * 2) + (left === 1 ? 1 : 2);

    return res;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        let a = ra();
        console.log(`${calc(n, a)}`);
    }
}

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) {
    let max = -Infinity
    for (let i = 0; i < arr.length; i++) {
        max = Math.max(max, arr[i])
    }
    //
    let odd = 0
    let even = 0
    for (let i = 0; i < arr.length; i++) {
        const d = max - arr[i]
        if (d & 1) {
            odd++
        }
        even += Math.floor(d / 2)
        // const r = d % 3
        // if (r === 1) {
        //     odd++
        // } else if (r === 2) {
        //     even++
        // }
        // ans += 2 * Math.floor(d / 3)
    }
// console.log(odd, even)
    let ans = 0
    if (odd > even) {
        ans = 2 * odd - 1
    } else {
        const diff = even - odd
        const k = Math.floor(diff / 3)
        const r = diff % 3
        ans = 2 * (odd + 2 * k)
        if (r === 1) {
            ans += 2
        } else if (r === 2) {
            ans += 3
        }
    }
    return ans
}

const readline = require('readline')

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

function solve(n, arr) {
    let max = -Infinity
    for (let i = 0; i < arr.length; i++) {
        max = Math.max(max, arr[i])
    }
    //
    let ans = 0
    let odd = 0
    let even = 0
    for (let i = 0; i < arr.length; i++) {
        const d = max - arr[i]
        if (d & 1) {
            odd++
        }
        even += Math.floor(d / 2)
        // const r = d % 3
        // if (r === 1) {
        //     odd++
        // } else if (r === 2) {
        //     even++
        // }
        // ans += 2 * Math.floor(d / 3)
    }
// console.log(ans, odd, even)
    if (odd >= even) {
        ans += 2 * odd - 1
    } else {
        const diff = even - odd
        const k = Math.floor(diff / 3)
        const r = diff % 3
        ans = 2 * (odd + 2 * k)
        if (r === 1) {
            ans += 2
        } else if (r === 2) {
            ans += 3
        }
    }
    return ans
}

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

module.exports = E;

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

const MOD = 32768;

let can_achieve = (h, days, goal)=>{
  let doubles = Math.floor(days/2);
  let ones = Math.floor((days+1)/2);
  //l({doubles, ones, days})
  let leftovers = [];
  for (let x of h){
    if (goal-x>0){
      let g = goal-x;
      if (g%2){
        g--;
        ones--;
      }
      leftovers.push(g);
    }
  }
  //l({leftovers})
  if (ones<0)
    return false;
  for (let l of leftovers){
    let deduct_doubles = Math.min(doubles, Math.floor(l/2));
    doubles -= deduct_doubles;
    l -= deduct_doubles*2;
    let deduct_ones = Math.min(ones, l);
    ones -= deduct_ones;
    l -= deduct_ones;
    if (l>0)
      return false;
  }
  //l('yes')
  return true
};

const calc = (n, h)=>{
  h.sort((a, b)=>a-b);
  let min = h[0];
  let max = h[h.length-1]
  let l = 0, r = 3*1e14+5;
  while (l<r){
    let m = Math.floor((l+r)/2);
    if (can_achieve(h, m, max) || can_achieve(h, m, max+1))
      r = m;
    else
      l = m+1;
  }
  if (can_achieve(h, l-1, max) || can_achieve(h, l-1, max+1))
    return l-1;
  return l;
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let h = ra();
      l('ans')
      print(calc(n, h));
    }
}

E.calc = calc;


Alina has discovered a weird language, which contains only $$$4$$$ words: $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$. It also turned out that there are no spaces in this language: a sentence is written by just concatenating its words into a single string.Alina has found one such sentence $$$s$$$ and she is curious: is it possible that it consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$?In other words, determine, if it's possible to concatenate these $$$a+b+c+d$$$ words in some order so that the resulting string is $$$s$$$. Each of the $$$a+b+c+d$$$ words must be used exactly once in the concatenation, but you can choose the order in which they are concatenated.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0\le a,b,c,d\le 2\cdot 10^5$$$) — the number of times that words $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$ respectively must be used in the sentence. The second line contains the string $$$s$$$ ($$$s$$$ consists only of the characters $$$\texttt{A}$$$ and $$$\texttt{B}$$$, $$$1\le |s| \le 2\cdot 10^5$$$, $$$|s|=a+b+2c+2d$$$)  — the sentence. Notice that the condition $$$|s|=a+b+2c+2d$$$ (here $$$|s|$$$ denotes the length of the string $$$s$$$) is equivalent to the fact that $$$s$$$ is as long as the concatenation of the $$$a+b+c+d$$$ words. The sum of the lengths of $$$s$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.

For each test case output $$$\texttt{YES}$$$ if it is possible that the sentence $$$s$$$ consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$, and $$$\texttt{NO}$$$ otherwise. You can output each letter in any case.

8
1 0 0 0
B
0 0 1 0
AB
1 1 0 1
ABAB
1 0 1 1
ABAAB
1 1 2 2
BAABBABBAA
1 1 2 3
ABABABBAABAB
2 3 5 4
AABAABBABAAABABBABBBABB
1 3 3 10
BBABABABABBBABABABABABABAABABA

NoteIn the first test case, the sentence $$$s$$$ is $$$\texttt{B}$$$. Clearly, it can't consist of a single word $$$\texttt{A}$$$, so the answer is $$$\texttt{NO}$$$.In the second test case, the sentence $$$s$$$ is $$$\texttt{AB}$$$, and it's possible that it consists of a single word $$$\texttt{AB}$$$, so the answer is $$$\texttt{YES}$$$.In the third test case, the sentence $$$s$$$ is $$$\texttt{ABAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{B} = \texttt{ABAB}$$$.In the fourth test case, the sentence $$$s$$$ is $$$\texttt{ABAAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{AB}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{AB} = \texttt{ABAAB}$$$. In the fifth test case, the sentence $$$s$$$ is $$$\texttt{BAABBABBAA}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, two words $$$\texttt{AB}$$$, and two words $$$\texttt{BA}$$$, as $$$\texttt{BA} + \texttt{AB} + \texttt{B} + \texttt{AB} + \texttt{BA} + \texttt{A}= \texttt{BAABBABBAA}$$$.

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = CALC(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

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

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

tests = [
``, // Test #1
``, // Test #2
``, // Test #3
``, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const CALC = (testN)=>{
  // READING:
  let [a, b, c, d] = ra();
  let s = readline();
  LT({s, a, b, c, d});
  // PROCESSING:
  let ans = 0;
  let cA = 0;
  let cB = 0;
  let cC = 0;
  let cD = 0;
  let n = s.length;
  for (let i=0; i<n; i++){
    if (s[i]=='A')
      cA++;
    else
      cB++;
    if (i<n-1){
      if (s[i]+s[i+1]=='AB')
        cC++;
      else if (s[i]+s[i+1]=='BA')
        cD++;
    }
  }
  let fragments = [];
  let cur = '';
  for (let i=0; i<n; i++){
    cur += s[i]
    if (s[i]==s[i+1]){
      if (cur.length==1){
        if (cur=='A')
          a--;
        else
          b--;
      } else {
        fragments.push(cur);
      }
      cur = '';
    }
  }
  if (cur.length==1){
    if (cur=='A')
      a--;
    else
      b--;
  } else {
    fragments.push(cur);
  }
  if (a<0 || b<0 || c<0 || d<0)
    return 'NO'
  let options = [];
  L({fragments, a, b})
  for (let f of fragments){
    if (f.length%2){
      if (f[0]=='A')
        a--;
      else
        b--;
      if (a<0 || b<0)
        return 'NO'
      f = '*'+f.slice(2);
    }
    options.push(f)
  }
  options.sort((o1, o2)=>{
    if (o1[0]=='*' && o2[0]=='*'){
      return o1.length-o2.length;
    }
    if (o1[0]=='*' || o2[0]=='*'){
      return o1[0]=='*' ? 1 : -1;
    }
    return o1.length-o2.length;
  });
  L('options', options)
  L({a, b, c, d})
  for (let f of options){
    let length = f.length/2;
    if (f[0]=='*'){
      let use = Math.min(c, length);
      length -= use;
      c -= use;
      use = Math.min(d, length);
      length -= use;
      d -= use;
    }
    if (f[0]=='A' && c>0){
      let use = Math.min(c, length);
      length -= use;
      c -= use;
    } else if (f[0]=='B' && d>0){
      let use = Math.min(d, length);
      length -= use;
      d -= use;
    }
    if (length>0){
      if (c>0){
        let use = Math.min(c, length-1);
        length -= use;
        c -= use;
      }
      if (d>0){
        let use = Math.min(d, length-1);
        length -= use;
        d -= use;
      }
      a -= length;
      b -= length;
    }
    if (a<0 || b<0)
      return 'NO';
  }
  return 'YES';
};

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = CALC(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

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

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

tests = [
``, // Test #1
``, // Test #2
``, // Test #3
``, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const CALC = (testN)=>{
  // READING:
  let [a, b, c, d] = ra();
  let s = readline();
  LT({s, a, b, c, d});
  // PROCESSING:
  let ans = 0;
  let cA = 0;
  let cB = 0;
  let cC = 0;
  let cD = 0;
  let n = s.length;
  for (let i=0; i<n; i++){
    if (s[i]=='A')
      cA++;
    else
      cB++;
    if (i<n-1){
      if (s[i]+s[i+1]=='AB')
        cC++;
      else if (s[i]+s[i+1]=='BA')
        cD++;
    }
  }
  let fragments = [];
  let cur = '';
  for (let i=0; i<n; i++){
    cur += s[i]
    if (s[i]==s[i+1]){
      if (cur.length==1){
        if (cur=='A')
          a--;
        else
          b--;
      } else {
        fragments.push(cur);
      }
      cur = '';
    }
  }
  if (cur.length==1){
    if (cur=='A')
      a--;
    else
      b--;
  } else {
    fragments.push(cur);
  }
  if (a<0 || b<0 || c<0 || d<0)
    return 'NO'
  let options = [];
  for (let f of fragments){
    if (f.length%2){
      if (f[0]=='A')
        a--;
      else
        b--;
      if (a<0 || b<0)
        return 'NO'
      f = f.slice(1);
    }
    options.push(f)
  }
  for (let f of options){
    let length = f.length/2;
    if (f[0]=='A' && c>0){
      let use = Math.min(c, length);
      length -= use;
      c -= use;
    }
    if (f[0]=='B' && d>0){
      let use = Math.min(d, length);
      length -= use;
      d -= use;
    }
    if (length>1){
      if (c>0){
        let use = Math.min(c, length-1);
        length -= use;
        c -= use;
      }
      if (d>0){
        let use = Math.min(d, length-1);
        length -= use;
        d -= use;
      }
      a -= length;
      b -= length;
    }
    if (a<0 || b<0)
      return 'NO';
  }
  L('options', options)
  return 'YES';
};


Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him.

The single line contains a number n (1 ≤ n ≤ 104) which is the number of mounds.

Print n integers pi (1 ≤ pi ≤ n) which are the frog's route plan.    All the pi's should be mutually different.  All the |pi–pi + 1|'s should be mutually different (1 ≤ i ≤ n - 1).  If there are several solutions, output any.

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 numPads = parseInt(readline(), 10);
	var visits = new Array(numPads);
	var currentPad = +1,
		jumpSize = numPads-1;
	for (var visitIndex = 0; visitIndex < numPads; ++visitIndex) {
		visits[visitIndex] = currentPad;
		currentPad += (visitIndex % 2 == 0 ? jumpSize : -jumpSize);
		--jumpSize;
	}
	print(visits.join(" "));
}

main();

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

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

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

function main() {
	var numPads = parseInt(readline(), 10);
	var visits = new Array(numPads);
	var currentPad = 1,
		jumpSize = numPads-1;
	for (var visitIndex = 0; visitIndex < numPads; ++visitIndex) {
		visits[visitIndex] = currentPad;
		currentPad += (visitIndex % 2 == 0 ? jumpSize : -jumpSize);
		--jumpSize;
	}
	print(visits.join(" "));
}

main();

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

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

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

function main() {
	var numPads = parseInt(readline(), 10);
	var visits = new Array(numPads);
	var currentPad = 1*1,
		jumpSize = numPads-1;
	for (var visitIndex = 0; visitIndex < numPads; ++visitIndex) {
		visits[visitIndex] = currentPad;
		currentPad += (visitIndex % 2 == 0 ? jumpSize : -jumpSize);
		--jumpSize;
	}
	print(visits.join(" "));
}

main();


Ilya plays a card game by the following rules.A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom contains number bi, then when the player is playing the card, he gets ai points and also gets the opportunity to play additional bi cards. After the playing the card is discarded.More formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number bi, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards.Of course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of cards Ilya has. Each of the next n lines contains two non-negative space-separated integers — ai and bi (0 ≤ ai, bi ≤ 104) — the numbers, written at the top and the bottom of the i-th card correspondingly.

Print the single number — the maximum number of points you can score in one round by the described rules.

NoteIn the first sample none of two cards brings extra moves, so you should play the one that will bring more points.In the second sample you should first play the third card that doesn't bring any points but lets you play both remaining cards.

print(function(n) {

	var zero = [];
	var ans = 0;
	var t = 1;
	for (var i = 0; i < n; i++)
		readline().split(' ').map(Number).reduce(function(a, b) {
			if (b === 0) zero.push(a);
			else ans += a, t += b - 1;
		});

	zero.sort(function(a, b) {
		return b - a
	});
	for (var i = 0, l = Math.min(t,zero.length); i < l; i++)
		ans += zero[i];

	return ans;
}(+readline()));

print(function(n) {

	var a = [];
	for (var i = 0; i < n; i++)
		a.push(readline().split(' ').map(Number));
	a.sort(function(a, b) {
		if (a[1] === b[1]) return b[0] - a[0];
		return b[1] - a[1];
	});

	var t = 1;
	var ans = 0;
	var i = 0;
	while (t > 0 && i < a.length) {
		ans += a[i][0];
		t += a[i][1]-1;
		i++;
	}
	return ans;
}(+readline()));

;(function () {

	print(function (n) {

		var cards = [], points = 0;

		while (n--) {
			cards.push(readline().split(' ').map(Number));
		}

		cards.sort(function (a, b) { return (b[1] * 1e5 + b[0]) - (a[1] * 1e5 + a[0]); });

		n = 1;
		for (var i = 0, _i = cards.length; i < _i && 0 < n; i++) {
			n += cards[i][1] - 1;
			points += cards[i][0];
		}

		return points;

	}(+readline()));

}.call(this));

print(function(n) {

	var zero = [];
	var ans = 0;
	var t = 0;
	for (var i = 0; i < n; i++)
		readline().split(' ').map(Number).reduce(function(a, b) {
			if (b === 0) zero.push(a);
			else ans += a, t += b - 1;
		});

	zero.sort(function(a, b) {
		return b - a
	});
	for (var i = 0, l = Math.min(t,zero.length); i < l; i++)
		ans += zero[i];

	return ans;
}(+readline()));


It is the hard version of the problem. The only difference is that in this version $$$3 \le k \le n$$$.You are given a positive integer $$$n$$$. Find $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, such that:  $$$a_1 + a_2 + \ldots + a_k = n$$$  $$$LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$$$ Here $$$LCM$$$ is the least common multiple of numbers $$$a_1, a_2, \ldots, a_k$$$.We can show that for given constraints the answer always exists.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^4)$$$  — the number of test cases. The only line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$3 \le n \le 10^9$$$, $$$3 \le k \le n$$$). It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, for which all conditions are satisfied.

'use strict';

function solve(n, m) {
  let res = [],
      one = 0;
  if (n & 1) {
    if (m === 3) return `1 ${(n - 1) / 2} ${(n - 1) / 2}`;
    m--;
    one++;
    n--;
  }
  for (let i = 30; i >= 0; i--) {
    if (res.length) {
      while (1 << i <= n) {
        let cur = 1 << i;
        while (n >= cur) {
          res.push(cur);
          n -= cur;
        }
      }
    } else {
      if (1 << i <= n / 2) {
        let cur = 1 << i;
        while (n >= cur) {
          res.push(cur);
          n -= cur;
        }
      }
    }
  }
  if (res.length === m) {
    if (one) res.push(1);
    return res.join(' ');
  } else if (res.length > m) {
    let sum = res.splice(2, res.length - m).reduce((a, b) => a + b, 0) / 2;
    res[0] += sum;
    res[1] += sum;
    if (one) res.push(1);
    return res.join(' ');
  }
  m -= res.length;
  while (m--) {
    let cur = res[res.length - 1];
    if (cur === 2) {
      res.pop();
      one += 2;
    } else {
      res[res.length - 1] /= 2;
      res.push(cur / 2);
    }
  }
  return (res.join(' ') + ' 1'.repeat(one)).trim();
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const [n, m] = (await read()).split(' ').map(Number);
      res.push(solve(n, m));
    }
    console.log(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', () => {
  inputs = str.split('\n').values();
  main(read);
});

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, k] = rna();

		let ans = [];
		n -= k - 3;
		if (n % 2 == 0) {
			if (n % 4 == 0){
				ans = [n/2, n/4, n/4];
			} else {
				ans = [n/2-1, n/2-1, 2]
			}
		} else {
			ans = [(n-1)/2, (n-1)/2, 1];
		}

		ans.push(...Array(k-3).fill(1));

		console.log(ans.join(' '));
	}
}

'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();
var mod = 1000000000n + 7n
var maxN = 1002

function main() {
  const x = readline();
  //
  Array(parseInt(x)).fill(1).map((t, iii) => {
    // var n = parseInt(readline())
    var [n, k] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    });
    // var a = readline().split(' ').map((x, iii) => {
    //   return parseInt(x)
    // });
    var ans = new Array(k).fill(1)
    n = n-(k-3)
    var x
    if (n % 2 === 1) {
      x = (n - 1) / 2
      ans[0] = 1
      ans[1] = x
      ans[2] = x
      // return console.log(1, x, x)
    }
    if (n % 2 === 0) {
      ans[0] = 2
      ans[1] = (n-2)/2
      ans[2] = (n-2)/2
    }

    if (n % 4 === 0) {
      x = n / 4
      ans[0] = x*2
      ans[1] = x
      ans[2] = x
    }

    return console.log(ans.join(' '))

  });
}

'use strict';

function solve(n, m) {
  let res = [],
      one = 0;
  if (n & 1) {
    if (m === 3) return `1 ${(n - 1) / 2} ${(n - 1) / 2}`;
    m--;
    one++;
    n--;
  }
  for (let i = 30; i >= 0; i--) {
    if (res.length) {
      while (1 << i <= n) {
        let cur = 1 << i;
        while (n >= cur) {
          res.push(cur);
          n -= cur;
        }
      }
    } else {
      if (1 << i <= n / 2) {
        let cur = 1 << i;
        while (n >= cur) {
          res.push(cur);
          n -= cur;
        }
      }
    }
  }
  if (res.length === m) {
    if (one) res.push(1);
    return res.join(' ');
  } else if (res.length > m) {
    let sum = res.splice(2, res.length - m + 2).reduce((a, b) => a + b, 0) / 2;
    res[0] += sum;
    res[1] += sum;
    if (one) res.push(1);
    return res.join(' ');
  }
  m -= res.length;
  while (m--) {
    let cur = res[res.length - 1];
    if (cur === 2) {
      res.pop();
      one += 2;
    } else {
      res[res.length - 1] /= 2;
      res.push(cur / 2);
    }
  }
  return (res.join(' ') + ' 1'.repeat(one)).trim();
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const [n, m] = (await read()).split(' ').map(Number);
      res.push(solve(n, m));
    }
    console.log(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', () => {
  inputs = str.split('\n').values();
  main(read);
});


Mitya has a rooted tree with $$$n$$$ vertices indexed from $$$1$$$ to $$$n$$$, where the root has index $$$1$$$. Each vertex $$$v$$$ initially had an integer number $$$a_v \ge 0$$$ written on it. For every vertex $$$v$$$ Mitya has computed $$$s_v$$$: the sum of all values written on the vertices on the path from vertex $$$v$$$ to the root, as well as $$$h_v$$$ — the depth of vertex $$$v$$$, which denotes the number of vertices on the path from vertex $$$v$$$ to the root. Clearly, $$$s_1=a_1$$$ and $$$h_1=1$$$.Then Mitya erased all numbers $$$a_v$$$, and by accident he also erased all values $$$s_v$$$ for vertices with even depth (vertices with even $$$h_v$$$). Your task is to restore the values $$$a_v$$$ for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values $$$a_v$$$ for all vertices in the tree.

The first line contains one integer $$$n$$$ — the number of vertices in the tree ($$$2 \le n \le 10^5$$$). The following line contains integers $$$p_2$$$, $$$p_3$$$, ... $$$p_n$$$, where $$$p_i$$$ stands for the parent of vertex with index $$$i$$$ in the tree ($$$1 \le p_i < i$$$). The last line contains integer values $$$s_1$$$, $$$s_2$$$, ..., $$$s_n$$$ ($$$-1 \le s_v \le 10^9$$$), where erased values are replaced by $$$-1$$$.

Output one integer — the minimum total sum of all values $$$a_v$$$ in the original tree, or $$$-1$$$ if such tree does not exist.

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function doIt(lines) {
    const nodesNum = parseInt(lines[0]);
    const parents = lines[1].split(" ").map(x => parseInt(x));
    const weights = lines[2].split(" ").map(x => parseInt(x));

    parents.unshift(-1);
    parents.unshift(-1);
    weights.unshift(0);
    let ret = 0
    for (let i=1; i <= nodesNum; i++) {
        const weight = weights[i];
        const parent = parents[i];
        if (weight !== -1 && parent>1) {
            weights[parent] = Math.min(weights[parent]==-1?10000000000:weights[parent], weight);
        }
    }

    for (let i=1; i<=nodesNum;i++) {
        const weight = weights[i];
        const parent = parents[i];
        if (parent === -1)
            ret +=weight;
        else if (weight < 0){}
        else {
            const nodeWeight = weight - weights[parent];
            if (nodeWeight < 0) {
                ret = -1;
                break;
            } else {
                ret +=nodeWeight;
            }
        }
    }
    console.log(ret);
}

readLines(3, doIt);

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function doIt(lines) {
    const nodesNum = parseInt(lines[0]);
    const path = lines[1].split(" ").map(x => parseInt(x));
    const weights = lines[2].split(" ").map(x => parseInt(x));

    let ret = weights[0];
    for (let i=0; i<path.length; i++) {
        const parent = path[i];
        const weight = weights[i+1];
        if (weight != -1) {
            const grandp = path[parent-2];
            const grandpw = weights[grandp-1];
            if (weight < grandpw) {
                ret = -1;
                break;
            }

            ret += weight-grandpw;
        }
    }
    console.log(ret);
}

readLines(3, doIt);


Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:  Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.  Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≤ i ≤ n).  Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.

The first line contains integers n, m (1 ≤ n, m ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≤ ti ≤ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≤ vi ≤ n, 1 ≤ xi ≤ 109). If ti = 2, then it is followed by integer yi (1 ≤ yi ≤ 104). And if ti = 3, then it is followed by integer qi (1 ≤ qi ≤ n).

For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.

print(function(n, m) {
	var ans = [],
		t = 0,
		a = ('0 ' + readline()).split(' ').map(Number);

	for (var i = 0; i < m; i++) {
		go.apply(0, rn());
	}

	return ans.join('\n');

	function go(type, x, y) {
		if (type === 1) a[x] = y - t;
		else if (type === 2) t += x;
		else ans.push(a[x] + t);
	}

} .apply(0, rn()));
function rn() {
	return readline().split(' ').map(Number);
}

print(function(n, m) {
	var ans = [],
		t = 0,
		a = ('0 ' + readline()).split(' ').map(Number);

	for (var i = 0; i < m; i++) {
		var l = readline().split(' ').map(Number);
		if (l[0] === 1)
			a[l[1]] = l[2] - t;
		else if (l[0] === 2)
			t += l[1];
		else
			ans.push(a[l[1]] + t);
	}

	return ans.join('\n');

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

var data = readline().split(" ").map( c => parseInt(c))
var arra = readline().split(" ").map( c => parseInt(c))
var artt = new Array(arra.length).fill(0)
var incre = 0
for (var i = 0; i< data[1]; i++){
	var query = readline().split(" ").map( c => parseInt(c))
	if (query[0] == 1){
		arra[query[1]-1] = query[2]
		artt[query[1]-1] = incre
	}
	else if (query[0] == 2){
		incre += query[1]
	}
	else {
		print(arra[query[1]-1]+incre-artt[query[1]-1])
	}
}

function main()
{
    var tmp;
    tmp = readline().split(" ").map(function (x) { return parseInt(x); });
    var n = tmp[0],
        m = tmp[1];
    var a = readline().split(" ").map(function (x) { return parseInt(x); });
    var y = 0;
    while ( m-- )
    {
        tmp = readline().split(" ").map(function (x) { return parseInt(x); });
        if ( tmp[0] == 1 )
        {
            a[tmp[1]-1] = tmp[2]-y;
        }
        else if ( tmp[0] == 2 )
        {
            y += tmp[1];
        }
        else if ( tmp[0] == 3 )
        {
            print(a[tmp[1]-1]+y);
        }
    }
}

main();

function main(){
    var tmp;
    tmp = readline().split(" ").map(function (x) { return parseInt(x); });
    var n = tmp[0],
        m = tmp[1];
    var a = readline().split(" ").map(function (x) { return parseInt(x); });
    var y = 0;
    while ( m-- ){
        tmp = readline().split(" ").map(function (x) { return parseInt(x); });
        if ( tmp[0] == 1 ){
            a[tmp[1]-1] = tmp[2]-y;
        }
        else if ( tmp[0] == 2 ){
            y += tmp[1];
        }
        else if ( tmp[0] == 3 ){
            print(a[tmp[1]-1]+y);
        }
    }
}

main();