Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1,s2,...,sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1≤i≤n). Help Polycarpus determine the length of the city phone code.

The first line of the input contains an integer n (2≤n≤3·10^4) — the number of Polycarpus's friends. The following n lines contain strings s1,s2,...,sn — the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different.

Print the number of digits in the city phone code.

A prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209".
In the first sample the city phone code is string "00".
In the second sample the city phone code is an empty string.
In the third sample the city phone code is string "770123456789".

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

//Don't have to see. end------------------------------------------
function Main(){
	var N = nextInt();
	var list = new Array(N);
	for(var i = 0; i < N; i++){
		list[i] = next();
	}
	for(var i = 0; i < list[0].length; i++){
		var s = list[0][i];
		for(var j = 0; j < N; j++){
			if(s != list[j][i]){
				myout(i);
				return;
			}
		}
	}
	myout(list[0].length);
}


Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).

The first input line contains four integer numbers n, t1, t2, k (1≤n,t1,t2≤1000; 1≤k≤100) — the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1≤i≤n) line contains space-separated integers ai, bi (1≤ai,bi≤1000) — the speeds which the participant number i chose.

Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.

First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2·3·0.5+4·3>4·3·0.5+2·3.

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

function readline() {
  return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {

    const [n, t1, t2, k]= readline().split(" ").map((x) => +x);

   let matrix = [];
  for (let i = 0; i < n; i++) {
    matrix.push(
      readline()
        .split(" ").map((x) => +x)
     );
  }

    growingMushrooms(n, t1, t2, k,matrix);

}

function growingMushrooms(n, t1, t2, k, speedOfParticipants) {
  let records = [];
  for (let i = 0; i < n; i++) {
    const [ai, bi] = speedOfParticipants[i];

    records.push({
      speed: Math.max(
        t1 * ai - t1 * ai * (k / 100) + t2 * bi,
        t1 * bi - t1 * bi * (k / 100) + t2 * ai
      ),
      no: i,
    });
  }

  let sortBy = [
    {
      prop: "speed",
      direction: -1,
    },
    {
      prop: "no",
      direction: 1,
    },
  ];

  records.sort((a, b) => {
    let i = 0,
      result = 0;
    while (i < sortBy.length && result === 0) {
      result =
        sortBy[i].direction *
        (a[sortBy[i].prop] < b[sortBy[i].prop]
          ? -1
          : a[sortBy[i].prop] > b[sortBy[i].prop]
          ? 1
          : 0);
      i++;
    }
    return result;
  });

  for (let i = 0; i < n; i++) {
    console.log(records[i].no + 1, " ", records[i].speed.toFixed(2));
  }
}


Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.

The first input line contains integer n (1≤n≤100) — amount of numbers in the sequence. The second line contains n space-separated integer numbers — elements of the sequence. These numbers don't exceed 100 in absolute value.

If the given sequence has the second order statistics, output this order statistics, otherwise output NO.

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


One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day n?

The first line contains two integers n and b (1≤n,b≤2000) — the number of days and the initial number of money in bourles. The next line contains n integers ai (1≤ai≤2000) — the prices of Martian dollars.

Print the single number — which maximal sum of money in bourles can Vasya get by the end of day n.

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

function findMaxFrom(arr, from){
    let ans = arr[from];
    for(let i = from + 1 ; i < arr.length ; i++ ){
        if(ans < arr[i])
        ans = arr[i];
    }
    return ans;

}

let N = -1, arr = [], rubles = 0, ans = 0;

rl.on('line', (input) => {
    if (N === -1) {
        arr = input.split(' ').map(it => parseInt(it));
        N = arr[0];
        rubles = arr[1];
        ans = rubles;
    }
    else {
        arr = input.split(' ').map(it => parseInt(it));

        for (let i = 0; i < N - 1; i++) {
            let dollars = parseInt(rubles / arr[i]);
            let rem = rubles % arr[i];
            let maxCurr = Math.max(...arr.slice(i + 1));
          // let maxCurr = findMaxFrom(arr, i + 1)
            let newRub = dollars * maxCurr + rem;

            if (newRub > ans)
                ans = newRub;
        }

        console.log(ans);
        rl.close();
    }
})

/*

n = 2  rubl = 4
3 7

I. 4 rubl -> 1$ (1 rubl)
II. 1$ -> 7 rubl + 1 rubl

-----------------------------------

n = 4 rubl = 10
4 2 3 1

I. 10 rubl -> 10 / 4 = 2$ (2 rubl)
II. 2$ -> 2 * 2 = 4rubl
III. 2$ -> 2 * 3 = 6rubl
IV. 2$ -> 2 * 1 = 2 rubl

II. 10 rubl -> 10 / 2 = 5$
III. 5$ -> 5 * 3 = 15 rubl

*/


Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the garden’s plan. On the plan the garden is represented as a rectangular checkered field n×m in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldn’t plant the trees too close to each other that’s why one square contains no more than one tree). Vasya wants to find a rectangular land lot a×b squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible.

The first line contains two integers n and m (1≤n,m≤50) which represent the garden location. The next n lines contain m numbers 0 or 1, which describe the garden on the scheme. The zero means that a tree doesn’t grow on this square and the 1 means that there is a growing tree. The last line contains two integers a and b (1≤a,b≤50). Note that Vasya can choose for building an a×b rectangle as well a b×a one, i.e. the side of the lot with the length of a can be located as parallel to the garden side with the length of n, as well as parallel to the garden side with the length of m.

Print the minimum number of trees that needs to be chopped off to select a land lot a×b in size to build a house on. It is guaranteed that at least one lot location can always be found, i. e. either a≤n and b≤m, or a≤m и b≤n.

In the second example the upper left square is (1,1) and the lower right is (3,2).

const readline = require('readline');

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

var calculate = function (cont, row, col, a, b) {
    let ct = 0;
    for (let i = row; i < row + a; i++)
        for (let j = col; j < col + b; j++)
            ct += cont[i][j];
    return ct;
}

let n = -1, m = -1, cont = new Array(), a, b, i = 0, temp = new Array();
rl.on('line', (input) => {

    if (n === -1) {
        temp = input.split(' ').map(item => { return parseInt(item) });
        n = temp[0], m = temp[1];
    }
    else if (i++ < n) {
        cont.push(input.split(' ').map(item => { return parseInt(item) }));
    }
    else {
        temp = input.split(' ').map(item => { return parseInt(item) });
        a = temp[0], b = temp[1];
    }

}).on('close', () => {
    //console.log(cont);
    let ans = n * m, trees;
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {

            if (i + a <= n && j + b <= m) {
                trees = calculate(cont, i, j, a, b);
                if (ans > trees) ans = trees;
            }

            if (i + b <= n && j + a <= m) {
                trees = calculate(cont, i, j, b, a);
                if (ans > trees) ans = trees;
            }
        }
    }
    console.log(ans);
});


Vasya collects coins: he has exactly one coin for every year from 1 to n. Naturally, Vasya keeps all the coins in his collection in the order in which they were released. Once Vasya's younger brother made a change — he took all the coins whose release year dated from l to r inclusively and put them in the reverse order. That is, he took a certain segment [l,r] and reversed it. At that the segment's endpoints did not coincide. For example, if n=8, then initially Vasya's coins were kept in the order 1 2 3 4 5 6 7 8. If Vasya's younger brother chose the segment [2,6], then after the reversal the coin order will change to 1 6 5 4 3 2 7 8. Vasya suspects that someone else could have spoilt the permutation after his brother. Help him to find that out. Check if the given permutation can be obtained from the permutation 1 2 ... n using exactly one segment reversal. If it is possible, find the segment itself.

The first line contains an integer n (1≤n≤1000) which is the number of coins in Vasya's collection. The second line contains space-separated n integers which are the spoilt sequence of coins. It is guaranteed that the given sequence is a permutation, i.e. it contains only integers from 1 to n, and every number is used exactly 1 time.

If it is impossible to obtain the given permutation from the original one in exactly one action, print 0 0. Otherwise, print two numbers l r (1≤l<r≤n) which are the endpoints of the segment that needs to be reversed to obtain from permutation 1 2 ... n the given one.

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
let i = 0;
let orginal = [];
let swapped = [];
readline.on('line', line => {
  i++;
  if (i === 1) {
    orginal = Array.from({length: parseInt(line) + 1}, (x, k) => k);
    orginal.splice(0, 1);
  }
  else {
    readline.close();
    swapped = line.split(' ').map((x) => {
      return parseInt(x);
    });
    difference = orginal.reduce((list, coin, index) => {
      if (coin !== swapped[index]) {
        list.push(coin)
      }
      return list
    }, []);
    if (difference.length === 0) {
      console.log(0, 0)
    } else {
      const firstIndex = orginal.indexOf(difference[0]);
      const lastIndex = orginal.indexOf(difference[difference.length - 1]);
      const originalPart = orginal.slice(firstIndex, lastIndex + 1)
      const reversedPart = swapped.slice(firstIndex, lastIndex + 1);
      if (isEqual(originalPart, reversedPart.reverse())) {
        console.log(difference[0], difference[difference.length - 1])
      } else {
        console.log(0, 0)
      }
    }

  }
});

function isEqual(a, b)
{
  // if length is not equal
  if(a.length!=b.length)
   return false;
  else
  {
  // comapring each element of array
    return a.reduce((value, e, index) => {
      if (e === b[index]) {
        value = true
        return value
      }
      value = false
      return value
    }, false)
  }
}


In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.

The first line contains two integers n and k (1≤n,k≤100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1≤i≤n, 1≤ai≤k).

Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.

In the first example the ranks will be raised in the following manner:
1 2 2 3 → 2 2 3 4 → 2 3 4 4 → 3 4 4 4 → 4 4 4 4
Thus totals to 4 training sessions that require 4 golden coins.

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
let isFirstLine = true;
let number;
let maxRank;
let soldiers;
let coin = 0;
readline.on('line', line => {
  if (isFirstLine) {
    let firstLine = line.split(' ').map(x => parseInt(x));
    number = firstLine[0];
    maxRank = firstLine[1]
    isFirstLine = false;
  } else {
    soldiers = line.split(' ').map(x => parseInt(x));
    readline.close();
    while (soldiers.some(s => s < maxRank)) {
      coin++
      let currentSoldeir = 0;
      for (let i = 0; i < soldiers.length; i++) {
        const soldeir = soldiers[i];
        if (soldeir == maxRank) break
        if (currentSoldeir < soldeir) {
          soldiers[i]++
          currentSoldeir = soldeir;
        }
      soldiers = soldiers.sort((a, b) => a - b)
      }
    }
    console.log(coin);
  }
})


Bob wants to put a new bargaining table in his office. To do so he measured the office room thoroughly and drew its plan: Bob's office room is a rectangular room n×m meters. Each square meter of the room is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed so, that its sides are parallel to the office walls. Bob doesn't want to change or rearrange anything, that's why all the squares that will be occupied by the table should be initially free. Bob wants the new table to sit as many people as possible, thus its perimeter should be maximal. Help Bob find out the maximum possible perimeter of a bargaining table for his office.

The first line contains 2 space-separated numbers n and m (1≤n,m≤25) — the office room dimensions. Then there follow n lines with m characters 0 or 1 each. 0 stands for a free square meter of the office room. 1 stands for an occupied square meter. It's guaranteed that at least one square meter in the room is free.

Output one number — the maximum possible perimeter of a bargaining table for Bob's office room.

'use strict';

function solve(n, m, a) {
  const h = new Array(m).fill(0);
  let res = 0;
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if (a[i][j]) h[j] = 0;else h[j]++;
    }
    const stack = [];
    for (let j = 0; j <= m; j++) {
      while (stack.length && (j === m || h[stack[stack.length - 1]] > h[j])) {
        var _stack;
        const cur = stack.pop(),
              p = (_stack = stack[stack.length - 1]) !== null && _stack !== void 0 ? _stack : -1;
        if (h[cur]) res = Math.max(res, (j - p - 1) * 2 + h[cur] * 2);
      }
      stack.push(j);
    }
  }
  return res;
}

async function main(r) {
  const rns = async () => {
    return (await r()).split(' ').filter(s => s !== '').map(Number);
  };
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = await rns();
      const a = [];
      let tmp = n;
      while (tmp--) {
        a.push((await r()).split('').map(Number));
      }
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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


A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?

Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 10^6.

Output the maximum possible length of a regular bracket sequence.

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

//Don't have to see. end------------------------------------------
function Main(){
	var s = next();
	var queue = [];
	var N = s.length;
	for(var i = 0; i < N; i++){
		if(s[i] == "("){
			queue.push("(");
		}else{
			if(queue.length > 0 && queue[queue.length - 1] == "("){
				queue.pop();
			}else{
				queue.push(")");
			}
		}
	}
	myout(N - queue.length);
}


One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not exactly paper the walls with the oversupply). After considerable brain racking and some pre-estimating, the sponsor representatives ordered a certain number of T-shirts of sizes S, M, L, XL and XXL. The T-shirts turned out to bring good luck, that's why on the contest day there built up a line of K participants willing to get one. Every contestant is characterized by his/her desired T-shirt size (so it happens that for all the participants it is also one of the sizes S, M, L, XL and XXL). The participants come up to get a T-shirt one by one and try to choose the most suitable one, choosing it like this. If there is still a T-shirt of the optimal size left, that he/she takes it without further ado. Otherwise the contestant would prefer to choose a T-shirt with the size as close to the optimal one as possible (the distance between neighboring sizes is considered equal to one). If the variant of choice is not unique, the contestant will take a T-shirt of a bigger size (in case he/she grows more). For example, for a person whose optimal size is L the preference list looks like this: L, XL, M, XXL, S. Using the data on how many T-shirts of every size had been ordered by the organizers, on the size of contestants in the line determine who got a T-shirt of what size.

The first line contains five non-negative integers NS,NM,NL,NXL,NXXL not exceeding 1000 which represent the number of T-shirts of the corresponding sizes. The second line contains an integer K (1≤K≤1000) which represents the number of participants. The next K lines contain the optimal T-shirt sizes for the contestants. The sizes are given in the order in which the participants stand in the line. It is guaranteed that NS+NM+NL+NXL+NXXL≥K.

For each contestant, print a line containing the size of the T-shirt he/she got.

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

const rl = readline.createInterface({ input, output });

let i = 0, n = 0, myMap = new Map();

rl.on('line', (input) => {
   if (i == 0) {
      let arr = input.split(' ').map(it => parseInt(it));
      myMap.set('S', arr[0]);
      myMap.set('M', arr[1]);
      myMap.set('L', arr[2]);
      myMap.set('XL', arr[3]);
      myMap.set('XXL', arr[4]);
      i++;
   }
   else if (i == 1) {
      n = parseInt(input)
      i++;
   }
   else {
      switch (input) {
         case 'S':
            if (myMap.get('S') > 0) {
               console.log('S');
               myMap.set('S', myMap.get('S') - 1);
            }
            else if (myMap.get('M') > 0) {
               console.log('M');
               myMap.set('M', myMap.get('M') - 1);
            }
            else if (myMap.get('L') > 0) {
               console.log('L');
               myMap.set('L', myMap.get('L') - 1);
            }
            else if (myMap.get('XL') > 0) {
               console.log('XL');
               myMap.set('XL', myMap.get('XL') - 1);
            }
            else {
               console.log('XXL');
               myMap.set('XXL', myMap.get('XXL') - 1);
            }
            break;
         case 'M':
            if (myMap.get('M') > 0) {
               console.log('M');
               myMap.set('M', myMap.get('M') - 1);
            }
            else if (myMap.get('L') > 0) {
               console.log('L');
               myMap.set('L', myMap.get('L') - 1);
            }
            else if (myMap.get('S') > 0) {
               console.log('S');
               myMap.set('S', myMap.get('S') - 1);
            }
            else if (myMap.get('XL') > 0) {
               console.log('XL');
               myMap.set('XL', myMap.get('XL') - 1);
            }
            else {
               console.log('XXL');
               myMap.set('XXL', myMap.get('XXL') - 1);
            }
            break;
         case 'L':
            if (myMap.get('L') > 0) {
               console.log('L');
               myMap.set('L', myMap.get('L') - 1);
            }
            else if (myMap.get('XL') > 0) {
               console.log('XL');
               myMap.set('XL', myMap.get('XL') - 1);
            }
            else if (myMap.get('M') > 0) {
               console.log('M');
               myMap.set('M', myMap.get('M') - 1);
            }
            else if (myMap.get('XXL') > 0) {
               console.log('XXL');
               myMap.set('XXL', myMap.get('XXL') - 1);
            }
            else {
               console.log('S');
               myMap.set('S', myMap.get('S') - 1);
            }
           break;
         case 'XL':
            if (myMap.get('XL') > 0) {
               console.log('XL');
               myMap.set('XL', myMap.get('XL') - 1);
            }
            else if (myMap.get('XXL') > 0) {
               console.log('XXL');
               myMap.set('XXL', myMap.get('XXL') - 1);
            }
            else if (myMap.get('L') > 0) {
               console.log('L');
               myMap.set('L', myMap.get('L') - 1);
            }
            else if (myMap.get('M') > 0) {
               console.log('M');
               myMap.set('M', myMap.get('M') - 1);
            }
            else {
               console.log('S');
               myMap.set('S', myMap.get('S') - 1);
            }
           break;
         default:
            if (myMap.get('XXL') > 0) {
               console.log('XXL');
               myMap.set('XXL', myMap.get('XXL') - 1);
            }
            else if (myMap.get('XL') > 0) {
               console.log('XL');
               myMap.set('XL', myMap.get('XL') - 1);
            }
            else if (myMap.get('L') > 0) {
               console.log('L');
               myMap.set('L', myMap.get('L') - 1);
            }
            else if (myMap.get('M') > 0) {
               console.log('M');
               myMap.set('M', myMap.get('M') - 1);
            }
            else {
               console.log('S');
               myMap.set('S', myMap.get('S') - 1);
            }
           break;

      }
   }

});

[{'input': ['1 0 2 0 1\r\n3\r\nXL\r\nXXL\r\nM\r\n'], 'output': ['XXL\r\nL\r\nL\r\n']}, {'input': ['0 0 0 0 1\r\n1\r\nS\r\n'], 'output': ['XXL\r\n']}, {'input': ['1 0 1 0 1\r\n1\r\nS\r\n'], 'output': ['S\r\n']}, {'input': ['1 0 0 0 1\r\n2\r\nS\r\nL\r\n'], 'output': ['S\r\nXXL\r\n']}, {'input': ['1 1 1 1 1\r\n2\r\nXL\r\nM\r\n'], 'output': ['XL\r\nM\r\n']}, {'input': ['1 0 1 1 1\r\n3\r\nS\r\nXXL\r\nL\r\n'], 'output': ['S\r\nXXL\r\nL\r\n']}, {'input': ['1 0 2 1 1\r\n4\r\nS\r\nXXL\r\nL\r\nM\r\n'], 'output': ['S\r\nXXL\r\nL\r\nL\r\n']}, {'input': ['1 0 3 0 1\r\n5\r\nS\r\nS\r\nS\r\nXL\r\nL\r\n'], 'output': ['S\r\nL\r\nL\r\nXXL\r\nL\r\n']}, {'input': ['2 1 0 1 3\r\n4\r\nXL\r\nM\r\nS\r\nS\r\n'], 'output': ['XL\r\nM\r\nS\r\nS\r\n']}, {'input': ['2 2 0 2 1\r\n6\r\nS\r\nXXL\r\nM\r\nXL\r\nXXL\r\nXL\r\n'], 'output': ['S\r\nXXL\r\nM\r\nXL\r\nXL\r\nM\r\n']}, {'input': ['3 1 1 4 1\r\n10\r\nXL\r\nL\r\nL\r\nXXL\r\nXXL\r\nXL\r\nL\r\nXXL\r\nS\r\nM\r\n'], 'output': ['XL\r\nL\r\nXL\r\nXXL\r\nXL\r\nXL\r\nM\r\nS\r\nS\r\n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r\nM\r\nM\r\nXL\r\nL\r\nS\r\nS\r\nXL\r\nS\r\nXXL\r\nXXL\r\nXL\r\nS\r\nXL\r\nXXL\r\nS\r\nS\r\nL\r\nL\r\nXXL\r\nXL\r\nL\r\nXL\r\nM\r\nS\r\nM\r\nM\r\nXL\r\nXXL\r\nS\r\nXL\r\nXL\r\nM\r\nXL\r\nXXL\r\nXXL\r\nXL\r\nL\r\nS\r\nM\r\nXXL\r\nM\r\nL\r\nXXL\r\n'], 'output': ['XXL\r\nM\r\nXL\r\nS\r\nXXL\r\nS\r\nL\r\nXL\r\nXL\r\nXL\r\nXXL\r\nS\r\nXXL\r\nS\r\nXXL\r\nXL\r\nXL\r\nXXL\r\nXL\r\nXXL\r\nM\r\nS\r\nS\r\nS\r\nS\r\nXXL\r\nS\r\nL\r\nXL\r\nXXL\r\nXXL\r\nS\r\nXXL\r\nL\r\nXXL\r\nM\r\nS\r\nL\r\nL\r\nXL\r\nXL\r\nS\r\nXL\r\nL\r\nXL\r\nM\r\nXL\r\nL\r\nM\r\nS\r\nXL\r\nXXL\r\nXL\r\nL\r\nXL\r\nXL\r\nXL\r\nM\r\nM\r\nXL\r\nL\r\nS\r\nS\r\nXL\r\nS\r\nXXL\r\nXXL\r\nXL\r\nS\r\nXL\r\nXXL\r\nS\r\nS\r\nL\r\nL\r\nXXL\r\nXL\r\nL\r\nXL\r\nM\r\nS\r\nM\r\nM\r\nXL\r\nXXL\r\nS\r\nXL\r\nXL\r\nM\r\nXL\r\nXXL\r\nXXL\r\nXL\r\nL\r\nS\r\nM\r\nXXL\r\nM\r\nL\r\nXXL\r\n']}]


Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.

The first line contains the single integer n (1≤n≤1000) — the number of contests where the coder participated.
The next line contains n space-separated non-negative integer numbers — they are the points which the coder has earned. The points are given in the chronological order. All points do not exceed 10000.

Print the single number — the number of amazing performances the coder has had during his whole history of participating in the contests.

In the first sample the performances number 2 and 3 are amazing.
In the second sample the performances number 2, 4, 9 and 10 are amazing.

let fs = require("fs");

let txt = fs
  .readFileSync(0, "utf-8")
  .split(/[\n\r]/)
  .filter((data) => data.length > 0);
let arr = txt[1]
  .split(" ")
  .map((d) => d.trim())
  .filter((d) => d.length > 0)
  .map((d) => Number(d));

let min = arr[1];
let max = arr[1];
let amazing = 0;
arr.forEach((data) => {
  if (data > max) {
    max = data;
    ++amazing;
  } else if (data < min) {
    min = data;
    ++amazing;
  }
});

console.log(amazing);


One day Vasya heard a story: "In the city of High Bertown a bus number 62 left from the bus station. It had n grown-ups and m kids..."The latter events happen to be of no importance to us. Vasya is an accountant and he loves counting money. So he wondered what maximum and minimum sum of money these passengers could have paid for the ride.The bus fare equals one berland ruble in High Bertown. However, not everything is that easy — no more than one child can ride for free with each grown-up passenger. That means that a grown-up passenger who rides with his k (k>0) children, pays overall k rubles: a ticket for himself and (k-1) tickets for his children. Also, a grown-up can ride without children, in this case he only pays one ruble.We know that in High Bertown children can't ride in a bus unaccompanied by grown-ups.Help Vasya count the minimum and the maximum sum in Berland rubles, that all passengers of this bus could have paid in total.

The input file consists of a single line containing two space-separated numbers n and m (0≤n,m≤10^5) — the number of the grown-ups and the number of the children in the bus, correspondingly.

If n grown-ups and m children could have ridden in the bus, then print on a single line two space-separated integers — the minimum and the maximum possible total bus fare, correspondingly.
Otherwise, print "Impossible" (without the quotes).

In the first sample a grown-up rides with two children and pays two rubles.
In the second sample there are only children in the bus, so the situation is impossible.
 In the third sample there are two cases:  Each of the two grown-ups rides with one children and pays one ruble for the tickets. In this case the passengers pay two rubles in total.  One of the grown-ups ride with two children's and pays two rubles, the another one rides alone and pays one ruble for himself. So, they pay three rubles in total.

/****************************************************************\
                   BISMILLAHIR RAHMANIR RAHIM
****************************************************************
               AUTHOR NAME: MD. TAHURUZZOHA TUHIN
\****************************************************************/

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

function main() {

    let n, m, mx, mn;
    [n, m] = input().split(" ").map(x => parseInt(x));
    if (n === 0 && m === 0) {
        console.log('0 0');
        return;
    }
    if (n === 0) {
        console.log("Impossible");
        return;
    }

    mx = n + m - (m !== 0);
    mn = n + m - Math.min(n, m);

    console.log(mn, mx);

}


There are two sisters Alice and Betty. You have $$$n$$$ candies. You want to distribute these $$$n$$$ candies between two sisters in such a way that:  Alice will get $$$a$$$ ($$$a > 0$$$) candies;  Betty will get $$$b$$$ ($$$b > 0$$$) candies;  each sister will get some integer number of candies;  Alice will get a greater amount of candies than Betty (i.e. $$$a > b$$$);  all the candies will be given to one of two sisters (i.e. $$$a+b=n$$$). Your task is to calculate the number of ways to distribute exactly $$$n$$$ candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent $$$n$$$ as the sum of $$$n=a+b$$$, where $$$a$$$ and $$$b$$$ are positive integers and $$$a>b$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^9$$$) — the number of candies you have.

For each test case, print the answer — the number of ways to distribute exactly $$$n$$$ candies between two sisters in a way described in the problem statement. If there is no way to satisfy all the conditions, print $$$0$$$.

NoteFor the test case of the example, the $$$3$$$ possible ways to distribute candies are:  $$$a=6$$$, $$$b=1$$$;  $$$a=5$$$, $$$b=2$$$;  $$$a=4$$$, $$$b=3$$$.

'use strict';

const rl = require('readline')
  .createInterface({ input: process.stdin, output: process.stdout });
const write = (...args) => {
  process.stdout.write(args.join(' '));
};

const lines = [];
rl.on('line', line => {
  lines.push(line);
});

rl.on('close', main);

let rli = 0;
function readline() {
  return lines[rli++];
}

function main() {
  const time = parseInt(readline());
  for(let t = 0; t < time; ++t) {
    let number = Math.ceil(parseInt(readline())/2);
    if(number > 0) {
      number = number - 1;
    }
    write(`${number}\n`);
  }
  //write(`${one_line}\n`);
}

// solved by: asmjaime


Ania has a large integer $$$S$$$. Its decimal representation has length $$$n$$$ and doesn't contain any leading zeroes. Ania is allowed to change at most $$$k$$$ digits of $$$S$$$. She wants to do it in such a way that $$$S$$$ still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$0 \leq k \leq n$$$) — the number of digits in the decimal representation of $$$S$$$ and the maximum allowed number of changed digits. The second line contains the integer $$$S$$$. It's guaranteed that $$$S$$$ has exactly $$$n$$$ digits and doesn't contain any leading zeroes.

Output the minimal possible value of $$$S$$$ which Ania can end with. Note that the resulting integer should also have $$$n$$$ digits.

NoteA number has leading zeroes if it consists of at least two digits and its first digit is $$$0$$$. For example, numbers $$$00$$$, $$$00069$$$ and $$$0101$$$ have leading zeroes, while $$$0$$$, $$$3000$$$ and $$$1010$$$ don't have leading zeroes.

const readline = require('readline');

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

var line = 0;
var n, k;
var S;

rl.on('line', (data) => {
	++line;

	var arr = data.split(' ');

	if(line===1) {
		n = parseInt(arr[0]);
		k = parseInt(arr[1]);
	} else {
		S = arr[0];
		var array = S;
		var result = '';
//		console.log(array)

		if(k===0) {
			console.log(S);
		} else if(n===1){
			console.log(0);
		} else {
			var idx=1;
			if(array[0]!=='1'){
				--k;
			}
			result+='1';
			for(; idx<n; idx++) {
				if(k===0) {
//					console.log('K is zero for',array[idx]);
					for(var jj=idx; jj<n; jj++) {
						result+=array[jj];
//							console.log('Added',array[jj])
					}
					idx=n;
					break;
				}

				if(array[idx]==='0') {
					result+=0;
				}else {
//					console.log('Decrement for',array[idx],'K is',k-1);
					--k;
					result+=0;
				}

//				console.log(k+1,'ADDED',array[idx])
			}
			console.log(result);
		}
		line=0;
	}
});


The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:    Elements of the main diagonal.   Elements of the secondary diagonal.   Elements of the "middle" row — the row which has exactly  rows above it and the same number of rows below it.   Elements of the "middle" column — the column that has exactly  columns to the left of it and the same number of columns to the right of it.    The figure shows a 5 × 5 matrix.   The good elements are marked with green.  Help the Smart Beaver count the sum of good elements of the given matrix.

The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are:    1 ≤ n ≤ 5  The input limitations for getting 100 points are:   1 ≤ n ≤ 101

Print a single integer — the sum of good matrix elements.

NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  arr.push(d.split(' ').map(Number));

  c++;
});

rl.on('close', () => {
  let ans = 0;
  let n = arr.length;

  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (i == j || i == Math.floor(n / 2) || j == Math.floor(n / 2) || i + j == n-1) {
        ans += arr[i][j];
      }
    }
  }

  console.log(ans);
});


Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on the rear wheel axle has bj (0 < b1 < b2 < ... < bm) teeth. Any pair (i, j) (1 ≤ i ≤ n; 1 ≤ j ≤ m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i, j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i, j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i, j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction  denotes division in real numbers, that is, no rounding is performed.

The first input line contains integer n (1 ≤ n ≤ 50) — the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 104) in the order of strict increasing. The third input line contains integer m (1 ≤ m ≤ 50) — the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.

Print the number of "integer" gears with the maximum ratio among all "integer" gears.

NoteIn the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.

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 len1 = +readLine();
  const arr1 = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  const len2 = +readLine();
  const arr2 = readLine()
    .split(" ")
    .map((n) => parseInt(n));

  let max = Number.MIN_SAFE_INTEGER;
  let count = 0;

  for (let i = 0; i < len2; i++) {
    const a = arr2[i];
    for (let j = 0; j < len1; j++) {
      const b = arr1[j];
      const div = a / b;
      if (Number.isInteger(div)) {
        if (div > max) {
          max = div;
          count = 0;
        }
        if (div === max) count++;
      }
    }
  }
  console.log(count);
}


Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

// author: Oscar Ramos

/// Source Code
// const input = require('competitive-programming-js').inputReader
// const { forn, vector, range } = require('../utils/utils')
//
// const n = input.readNumber()
//
// const coords = []
// forn(n, () => {
//   const [x, y] = input.readNumberArray()
//   coords.push([x, y])
// })
//
// const visited = vector(n, false)
//
// let ans = -1
//
// const dfs = i => {
//   if (!visited[i]) {
//     visited[i] = true
//     forn(n, (j => {
//       if (coords[i][0] === coords[j][0] ||
//         coords[i][1] === coords[j][1]) {
//         dfs(j)
//       }
//     }))
//   }
// }
//
// forn(n, i => {
//   if (!visited[i]) {
//     ans += 1
//   }
//   dfs(i)
// })
//
// console.log(ans)
//

!function(n){var t={};function r(e){if(t[e])return t[e].exports;var o=t[e]={i:e,l:!1,exports:{}};return n[e].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=n,r.c=t,r.d=function(n,t,e){r.o(n,t)||Object.defineProperty(n,t,{enumerable:!0,get:e})},r.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,t){if(1&t&&(n=r(n)),8&t)return n;if(4&t&&"object"==typeof n&&n&&n.__esModule)return n;var e=Object.create(null);if(r.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:n}),2&t&&"string"!=typeof n)for(var o in n)r.d(e,o,function(t){return n[t]}.bind(null,o));return e},r.n=function(n){var t=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(t,"a",t),t},r.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},r.p="",r(r.s=1)}([function(n,t){n.exports=function(n){return null!=n&&"object"==typeof n&&!0===n["@@functional/placeholder"]}},function(n,t,r){n.exports=r(2)},function(n,t,r){let e,o=0,u={readNumber:function(){return Number(e[o++])},readNumberArray:function(){return e[o++].split(" ").map(n=>Number(n))}};var c="";process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",(function(n){c+=n})).on("end",(function(){e=c.trim().split("\n").map(n=>n.trim());const{forn:n,vector:t,range:o}=r(3),i=u.readNumber(),f=[];n(i,()=>{const[n,t]=u.readNumberArray();f.push([n,t])});const a=t(i,!1);let s=-1;const p=t=>{a[t]||(a[t]=!0,n(i,n=>{f[t][0]!==f[n][0]&&f[t][1]!==f[n][1]||p(n)}))};n(i,n=>{a[n]||(s+=1),p(n)}),console.log(s)}))},function(n,t,r){const e=r(4);n.exports={forn:(n,t)=>e(0,n).map(n=>t(n)),fornm:(n,t,r)=>e(0,n).map(n=>e(0,t).map(t=>r(n,t))),matrix:(n,t,r)=>e(0,n).map(()=>e(0,t).map(()=>r)),vector:(n,t)=>e(0,n).map(()=>t),range:e}},function(n,t,r){var e=r(5),o=r(7),u=e((function(n,t){if(!o(n)||!o(t))throw new TypeError("Both arguments to range must be numbers");for(var r=[],e=n;e<t;)r.push(e),e+=1;return r}));n.exports=u},function(n,t,r){var e=r(6),o=r(0);n.exports=function(n){return function t(r,u){switch(arguments.length){case 0:return t;case 1:return o(r)?t:e((function(t){return n(r,t)}));default:return o(r)&&o(u)?t:o(r)?e((function(t){return n(t,u)})):o(u)?e((function(t){return n(r,t)})):n(r,u)}}}},function(n,t,r){var e=r(0);n.exports=function(n){return function t(r){return 0===arguments.length||e(r)?t:n.apply(this,arguments)}}},function(n,t){n.exports=function(n){return"[object Number]"===Object.prototype.toString.call(n)}}]);

/// package.json
// {
//   "name": "competitive",
//   "version": "1.0.0",
//   "description": "",
//   "main": "src/index.js",
//   "scripts": {
//     "convert": "cp-convert -s src/index.js -d output/converted.js",
//     "bundle": "webpack --config ./webpack.config.js",
//     "test": "npm run convert && jest ./",
//     "production": "npm run convert && npm run bundle && node src/getOutput.js",
//     "start": "node src/index.js"
//   },
//   "author": "Oscar Ramos",
//   "dependencies": {
//     "child-process-promise": "^2.2.1",
//     "competitive-programming-js": "^1.0.10",
//     "mathball": "^0.4.0",
//     "ramda": "^0.27.1"
//   },
//   "devDependencies": {
//     "@types/jest": "^26.0.10",
//     "concat-stream": "^2.0.0",
//     "cross-spawn": "^7.0.3",
//     "jest": "^26.4.2",
//     "jest-expect-message": "^1.0.2",
//     "mock-stdin": "^1.0.0",
//     "terser-webpack-plugin": "^4.1.0",
//     "webpack": "^4.44.1",
//     "webpack-cli": "^3.3.12"
//   },
//   "jest": {
//     "setupFilesAfterEnv": ["jest-expect-message"]
//   }
// }
//


Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the garden’s plan. On the plan the garden is represented as a rectangular checkered field n × m in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldn’t plant the trees too close to each other that’s why one square contains no more than one tree). Vasya wants to find a rectangular land lot a × b squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible.

The first line contains two integers n and m (1 ≤ n, m ≤ 50) which represent the garden location. The next n lines contain m numbers 0 or 1, which describe the garden on the scheme. The zero means that a tree doesn’t grow on this square and the 1 means that there is a growing tree. The last line contains two integers a and b (1 ≤ a, b ≤ 50). Note that Vasya can choose for building an a × b rectangle as well a b × a one, i.e. the side of the lot with the length of a can be located as parallel to the garden side with the length of n, as well as parallel to the garden side with the length of m.

Print the minimum number of trees that needs to be chopped off to select a land lot a × b in size to build a house on. It is guaranteed that at least one lot location can always be found, i. e. either a ≤ n and b ≤ m, or a ≤ m и b ≤ n.

NoteIn the second example the upper left square is (1,1) and the lower right is (3,2).

const readline = require('readline');

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

var calculateTrees = function (cont, startRow, endRow, startCol, endCol) {
    let ans = 0;
    for (let i = startRow; i < endRow; i++)
        for (let j = startCol; j < endCol; j++)
            ans += cont[i][j];

    //console.log(" startRow=%d  endRow=%d  startCol=%d  endCol=%d   ans=%d",startRow, endRow, startCol, endCol,ans);
    return ans;
}

var indicator = 0, N, M, temp, cont = [], HouseX, HouseY;
rl.on('line', (input) => {
    if (indicator == 0) {
        temp = input.split(" ").map(item => parseInt(item));
        N = temp[0];
        M = temp[1];
        indicator++;
    }
    else if (indicator <= N) {
        cont.push(input.split(" ").map(item => parseInt(item)));
        indicator++;
    }
    else {
        temp = input.split(" ").map(item => parseInt(item));
        HouseX = temp[0];
        HouseY = temp[1];
    }
}).on('close', () => {
    let ans = N * M, helper;
    for (let i = 0; i < N; i++) {
        for (let j = 0; j < M; j++) {
            if (i + HouseX <= N && j + HouseY <= M) {
                helper = calculateTrees(cont, i, i + HouseX, j, j + HouseY);
                if (ans > helper)
                    ans = helper;
            }
            if (i + HouseY <= N && j + HouseX <= M) {
                helper = calculateTrees(cont, i, i + HouseY, j, j + HouseX);
                if (ans > helper)
                    ans = helper;
            }
        }
    }
    console.log(ans);
});


Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with t humps, representing them as polylines in the plane. Each polyline consists of n vertices with coordinates (x1,y1), (x2,y2), ..., (xn,yn). The first vertex has a coordinate x1=1, the second — x2=2, etc. Coordinates yi might be any, but should satisfy the following conditions:  there should be t humps precisely, i.e. such indexes j (2≤j≤n-1), so that yj-1<yj>yj+1,  there should be precisely t-1 such indexes j (2≤j≤n-1), so that yj-1>yj<yj+1,  no segment of a polyline should be parallel to the Ox-axis,  all yi are integers between 1 and 4. For a series of his drawings of camels with t humps Bob wants to buy a notebook, but he doesn't know how many pages he will need. Output the amount of different polylines that can be drawn to represent camels with t humps for a given number n.

The first line contains a pair of integers n and t (3≤n≤20, 1≤t≤10).

Output the required amount of camels with t humps.

In the first sample test sequences of y-coordinates for six camels are: 123421, 123431, 123432, 124321, 134321 и 234321 (each digit corresponds to one value of yi).

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split(/[\n\r]+/);
const log = (...args) => console.log(...args);

let count = 0;
const readnum = () => input[count++].trim().split(' ').map(a => +a);
const readword = () => input[count++].trim().split(' ');

  let [n,t] = readnum();
  console.log(solve(n,t));

function solve(n,t) {
  let dp = [...Array(25)].map(() =>
    [...Array(5)].map(() =>
      Array(25).fill(0)
    )
  );

    for(let i=1;i<=3;i++) dp[1][i][0]=1;
    for(let x=2;x<22;x++)
    for(let y=1;y<=4;y++)
    for(let t=0;t<21;t++)
    for(let h=1;h<=4;h++){
      if(x==2){
              if(y>h){
              if(t%2) dp[2][y][t+1]+=dp[1][h][t];
              else dp[2][y][t]+=dp[1][h][t];
            }
          }
          else{
              if(t%2){
              if(h>y) dp[x][y][t]+=dp[x-1][h][t];
              else if(h<y) dp[x][y][t+1]+=dp[x-1][h][t];
              }
              else{
              if(h<y) dp[x][y][t]+=dp[x-1][h][t];
              else if(h>y) dp[x][y][t+1]+=dp[x-1][h][t];
              }
          }
    }

    if(t*2+1>n||n>6*t+1) return 0;
    let ans=0;
    for(let i=1;i<=4;i++)
    ans+=dp[n][i][2*t-1];
    return ans;
}


As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai=i).Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth?

The first line contains two integers n and m (1≤n≤10^5,0≤m≤n) — the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1≤ai≤n).
It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth.

Print n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime.

The first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth.
In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not.
In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one.

'use strict';

function solve(n, m, s) {
  const diff = new Array(n + 2).fill(0);
  for (let str of s) {
    const num = Number(str.slice(1));
    if (str[0] === '+') {
      diff[num]++;
      diff[num + 1]--;
    } else {
      diff[0]++;
      diff[num]--;
      diff[num + 1]++;
      diff[n + 1]--;
    }
  }
  const suspects = new Set();
  let sum = diff[0];
  for (let i = 1; i <= n; i++) {
    sum += diff[i];
    if (sum === m) suspects.add(i);
  }
  const res = new Array(n);
  for (let i = 0; i < n; i++) {
    const str = s[i];
    const num = Number(str.slice(1));
    if (str[0] === '+') {
      if (suspects.has(num)) {
        if (suspects.size === 1) res[i] = 'Truth';else res[i] = 'Not defined';
      } else {
        res[i] = 'Lie';
      }
    } else {
      if (suspects.has(num)) {
        if (suspects.size === 1) res[i] = 'Lie';else res[i] = 'Not defined';
      } else {
        res[i] = 'Truth';
      }
    }
  }
  return res.join('\n');
}

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

[{'input': ['1 1\r\n+1\r\n'], 'output': ['Truth\r\n']}, {'input': ['3 2\r\n-1\r\n-2\r\n-3\r\n'], 'output': ['Not defined\r\nNot defined\r\nNot defined\r\n']}, {'input': ['4 1\r\n+2\r\n-3\r\n+4\r\n-1\r\n'], 'output': ['Lie\r\nNot defined\r\nLie\r\nNot defined\r\n']}, {'input': ['1 0\r\n-1\r\n'], 'output': ['Lie\r\n']}, {'input': ['2 2\r\n+1\r\n+1\r\n'], 'output': ['Truth\r\nTruth\r\n']}, {'input': ['2 1\r\n+2\r\n+1\r\n'], 'output': ['Not defined\r\nNot defined\r\n']}, {'input': ['2 0\r\n-2\r\n-2\r\n'], 'output': ['Lie\r\nLie\r\n']}, {'input': ['3 1\r\n+2\r\n+3\r\n+3\r\n'], 'output': ['Truth\r\nLie\r\nLie\r\n']}, {'input': ['6 3\r\n+5\r\n+5\r\n+5\r\n+1\r\n+1\r\n+1\r\n'], 'output': ['Not defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\n']}, {'input': ['4 3\r\n-4\r\n-3\r\n-1\r\n-3\r\n'], 'output': ['Not defined\r\nTruth\r\nNot defined\r\nTruth\r\n']}, {'input': ['10 4\r\n-8\r\n+1\r\n-6\r\n-10\r\n+5\r\n-6\r\n-8\r\n-8\r\n-4\r\n-8\r\n'], 'output': ['Lie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': ['10 5\r\n-4\r\n+4\r\n+4\r\n-9\r\n-9\r\n-4\r\n-4\r\n+2\r\n-9\r\n-4\r\n'], 'output': ['Lie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': ['7 2\r\n+5\r\n+5\r\n+5\r\n-2\r\n+1\r\n-5\r\n-6\r\n'], 'output': ['Lie\r\nLie\r\nLie\r\nNot defined\r\nLie\r\nTruth\r\nNot defined\r\n']}, {'input': ['7 4\r\n+7\r\n-3\r\n-3\r\n-4\r\n+3\r\n+3\r\n+3\r\n'], 'output': ['Not defined\r\nNot defined\r\nNot defined\r\nTruth\r\nNot defined\r\nNot defined\r\nNot defined\r\n']}, {'input': ['6 3\r\n-6\r\n-1\r\n+5\r\n+1\r\n+6\r\n+1\r\n'], 'output': ['Truth\r\nNot defined\r\nNot defined\r\nNot defined\r\nLie\r\nNot defined\r\n']}, {'input': ['5 3\r\n-2\r\n+2\r\n+2\r\n-3\r\n+5\r\n'], 'output': ['Not defined\r\nNot defined\r\nNot defined\r\nTruth\r\nNot defined\r\n']}, {'input': ['3 0\r\n-2\r\n-2\r\n-2\r\n'], 'output': ['Lie\r\nLie\r\nLie\r\n']}, {'input': ['5 3\r\n-1\r\n-1\r\n-4\r\n+1\r\n-4\r\n'], 'output': ['Lie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\n']}, {'input': ['9 6\r\n+2\r\n+7\r\n+7\r\n-1\r\n-4\r\n+7\r\n-7\r\n+7\r\n+5\r\n'], 'output': ['Lie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': ['43 18\r\n-14\r\n-28\r\n+16\r\n+10\r\n+25\r\n-30\r\n+25\r\n+30\r\n+25\r\n+25\r\n+25\r\n+25\r\n-25\r\n+22\r\n+3\r\n-17\r\n+16\r\n-25\r\n+10\r\n+14\r\n+41\r\n+25\r\n-25\r\n+33\r\n+24\r\n-23\r\n-25\r\n+25\r\n-22\r\n+29\r\n+28\r\n-25\r\n-25\r\n-29\r\n+11\r\n+26\r\n-25\r\n+25\r\n+10\r\n+1\r\n-20\r\n-17\r\n+23\r\n'], 'output': ['Truth\r\nTruth\r\nNot defined\r\nLie\r\nNot defined\r\nTruth\r\nNot defined\r\nLie\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nLie\r\nLie\r\nTruth\r\nNot defined\r\nNot defined\r\nLie\r\nLie\r\nLie\r\nNot defined\r\nNot defined\r\nLie\r\nLie\r\nTruth\r\nNot defined\r\nNot defined\r\nTruth\r\nLie\r\nLie\r\nNot defined\r\nNot defined\r\nTruth\r\nLie\r\nLie\r\nNot defined\r\nNot defined\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\n']}, {'input': ['28 12\r\n+10\r\n-7\r\n+17\r\n-20\r\n+7\r\n-7\r\n+13\r\n-21\r\n-7\r\n-7\r\n-18\r\n+7\r\n+7\r\n+3\r\n+6\r\n+14\r\n+7\r\n-24\r\n-21\r\n-7\r\n-7\r\n+4\r\n+7\r\n-7\r\n+21\r\n-7\r\n-26\r\n+7\r\n'], 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\n']}, {'input': ['17 9\r\n-6\r\n+16\r\n+5\r\n+16\r\n-17\r\n+17\r\n-11\r\n+5\r\n+14\r\n+5\r\n-8\r\n-5\r\n+6\r\n-2\r\n-11\r\n+4\r\n+17\r\n'], 'output': ['Truth\r\nNot defined\r\nNot defined\r\nNot defined\r\nTruth\r\nLie\r\nTruth\r\nNot defined\r\nLie\r\nNot defined\r\nTruth\r\nNot defined\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nLie\r\n']}, {'input': ['14 3\r\n+14\r\n+12\r\n-9\r\n+9\r\n-9\r\n-9\r\n+8\r\n+9\r\n+2\r\n+1\r\n-13\r\n-9\r\n+13\r\n+3\r\n'], 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\n']}, {'input': ['10 4\r\n-9\r\n-8\r\n-5\r\n-9\r\n-7\r\n-9\r\n-9\r\n-9\r\n-4\r\n-9\r\n'], 'output': ['Lie\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': ['10 5\r\n-10\r\n-10\r\n-10\r\n-5\r\n-1\r\n+10\r\n-3\r\n-10\r\n-9\r\n-10\r\n'], 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': ['10 4\r\n-3\r\n-3\r\n-3\r\n-3\r\n-3\r\n-2\r\n-2\r\n-6\r\n-7\r\n-3\r\n'], 'output': ['Lie\r\nLie\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\n']}, {'input': ['10 6\r\n-9\r\n-7\r\n-5\r\n-5\r\n-4\r\n-2\r\n-8\r\n-5\r\n-5\r\n-9\r\n'], 'output': ['Truth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': ['10 4\r\n-8\r\n-2\r\n-8\r\n+1\r\n-4\r\n-8\r\n-2\r\n-8\r\n-8\r\n-1\r\n'], 'output': ['Lie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': ['10 2\r\n-8\r\n+10\r\n+1\r\n+8\r\n+4\r\n+8\r\n+6\r\n-8\r\n+10\r\n+1\r\n'], 'output': ['Not defined\r\nLie\r\nLie\r\nNot defined\r\nLie\r\nNot defined\r\nLie\r\nNot defined\r\nLie\r\nLie\r\n']}, {'input': ['10 3\r\n+9\r\n+3\r\n+8\r\n+3\r\n+6\r\n-3\r\n+6\r\n+8\r\n+3\r\n+7\r\n'], 'output': ['Lie\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nLie\r\n']}, {'input': ['10 8\r\n-2\r\n+9\r\n+9\r\n-4\r\n+9\r\n+9\r\n+4\r\n-9\r\n-3\r\n+9\r\n'], 'output': ['Truth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\n']}, {'input': ['10 7\r\n-4\r\n+6\r\n+4\r\n+9\r\n+6\r\n+6\r\n+6\r\n+6\r\n+6\r\n+2\r\n'], 'output': ['Truth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\n']}, {'input': ['10 4\r\n+3\r\n+5\r\n+6\r\n+10\r\n+5\r\n+5\r\n+6\r\n+8\r\n+5\r\n+6\r\n'], 'output': ['Lie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': ['10 7\r\n-6\r\n-10\r\n-3\r\n-1\r\n-3\r\n-7\r\n-2\r\n-7\r\n-7\r\n-3\r\n'], 'output': ['Truth\r\nTruth\r\nNot defined\r\nTruth\r\nNot defined\r\nNot defined\r\nTruth\r\nNot defined\r\nNot defined\r\nNot defined\r\n']}, {'input': ['10 5\r\n-4\r\n-4\r\n-1\r\n-5\r\n-7\r\n-4\r\n-4\r\n-4\r\n-1\r\n-7\r\n'], 'output': ['Lie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\n']}, {'input': ['10 5\r\n-9\r\n-7\r\n-6\r\n-3\r\n-10\r\n-10\r\n-10\r\n-10\r\n-10\r\n-2\r\n'], 'output': ['Truth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': ['10 3\r\n-10\r\n-10\r\n-10\r\n-3\r\n-10\r\n-10\r\n-10\r\n-8\r\n-4\r\n-10\r\n'], 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\n']}, {'input': ['10 5\r\n-8\r\n-8\r\n-4\r\n-9\r\n-10\r\n-2\r\n-9\r\n-8\r\n-8\r\n-8\r\n'], 'output': ['Lie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\n']}, {'input': ['10 5\r\n+7\r\n+8\r\n+9\r\n+1\r\n+7\r\n+7\r\n+7\r\n+6\r\n+6\r\n+7\r\n'], 'output': ['Truth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': ['10 5\r\n+2\r\n+2\r\n+2\r\n+2\r\n+9\r\n+10\r\n+8\r\n+7\r\n+4\r\n+2\r\n'], 'output': ['Truth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': ['10 9\r\n+7\r\n+7\r\n+7\r\n+7\r\n+7\r\n+7\r\n+5\r\n+7\r\n+7\r\n+7\r\n'], 'output': ['Truth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\n']}, {'input': ['10 3\r\n+10\r\n+2\r\n+10\r\n+9\r\n+1\r\n+9\r\n+4\r\n+9\r\n+3\r\n+2\r\n'], 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nLie\r\n']}, {'input': ['10 6\r\n+10\r\n+10\r\n+10\r\n+3\r\n+10\r\n+10\r\n+6\r\n+6\r\n+10\r\n+8\r\n'], 'output': ['Truth\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': ['3 2\r\n-1\r\n+2\r\n+3\r\n'], 'output': ['Truth\r\nNot defined\r\nNot defined\r\n']}]


Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious "Pihters" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters each occupies exactly one point on the two-dimensional kingdom.The outlaw's car was equipped with a GPS transmitter. The transmitter showed that the car made exactly n movements on its way from the headquarters to the stall. A movement can move the car from point (x,y) to one of these four points: to point (x-1,y) which we will mark by letter "L", to point (x+1,y) — "R", to point (x,y-1) — "D", to point (x,y+1) — "U".The GPS transmitter is very inaccurate and it doesn't preserve the exact sequence of the car's movements. Instead, it keeps records of the car's possible movements. Each record is a string of one of these types: "UL", "UR", "DL", "DR" or "ULDR". Each such string means that the car made a single movement corresponding to one of the characters of the string. For example, string "UL" means that the car moved either "U", or "L".You've received the journal with the outlaw's possible movements from the headquarters to the stall. The journal records are given in a chronological order. Given that the ice-cream stall is located at point (0,0), your task is to print the number of different points that can contain the gang headquarters (that is, the number of different possible locations of the car's origin).

The first line contains a single integer n (1≤n≤2·10^5) — the number of the car's movements from the headquarters to the stall.
Each of the following n lines describes the car's possible movements. It is guaranteed that each possible movement is one of the following strings: "UL", "UR", "DL", "DR" or "ULDR".
All movements are given in chronological order.
Please do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin and cout stream or the %I64d specifier.

Print a single integer — the number of different possible locations of the gang's headquarters.

The figure below shows the nine possible positions of the gang headquarters from the first sample:

For example, the following movements can get the car from point (1,0) to point (0,0):

'use strict';

function solve(n, a) {
  let x = 1,
      y = 1;
  for (let s of a) {
    if (s === 'UR' || s === 'DL') y++;else if (s === 'UL' || s === 'DR') x++;else if (s === 'ULDR') x++, y++;
  }
  return x * y;
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = [];
      let tmp = n;
      while (tmp--) {
        a.push(await read());
      }
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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


In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k-1)m,(k-1)m+l], and l<m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.

The first input line contains 4 integer numbers n, d, m, l (1≤n,d,m,l≤10^6,l<m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k-1)m,(k-1)m+l].

Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.

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

rl.on('line', (line) => {
  const [n, d, m, l] = line.split(' ').map(Number);
  let platforms = [];
  for (let i = 0; i < n; i++) {
    platforms.push([(i * m), ((i * m) + l)]);
  }
  let coordinate = 0;
  while (true) {
    coordinate += d;
    let onPlatform = false;
    for (let i = 0; i < n; i++) {
      if (coordinate >= platforms[i][0] && coordinate <= platforms[i][1]) {
        onPlatform = true;
        break;
      }
    }
    if (!onPlatform) {
      console.log(coordinate);
      break;
    }
  }
});


One popular blog site edits the uploaded photos like this. It cuts a rectangular area out of them so that the ratio of height to width (i.e. the height/width quotient) can vary from 0.8 to 1.25 inclusively. Besides, at least one side of the cut area should have a size, equal to some power of number 2 (2^x for some integer x). If those rules don't indicate the size of the cut are clearly, then the way with which the cut part possesses the largest area is chosen. Of course, both sides of the cut area should be integer. If there are several answers to this problem, you should choose the answer with the maximal height.

The first line contains a pair of integers h and w (1≤h,w≤10^9) which are the height and width of the uploaded photo in pixels.

Print two integers which are the height and width of the cut area.

function cutArea(h, w) {
    let min = Math.min(h, w);
    let max = Math.max(h, w);
    let power = Math.floor(Math.log2(min));
    let minCut = Math.pow(2, power);
    let maxCut = Math.min(max, Math.floor(minCut * 1.25));
    if (maxCut / minCut < 0.8) {
        minCut = Math.floor(maxCut / 1.25);
    }
    return [maxCut, minCut].sort((a, b) => b - a).join(' ');
}

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
let input = [];
rl.on('line', function (line) {
    input.push(line);
}).on('close', function () {
    const [h, w] = input[0].split(' ').map(Number);
    console.log(cutArea(h, w));
    process.exit();
});


Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed.It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h^2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1≤d<l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed.The car can enter Bercouver at any speed.

The first line of the input file contains two integer numbers a and v (1≤a,v≤10000). The second line contains three integer numbers l, d and w (2≤l≤10000; 1≤d<l; 1≤w≤10000).

Print the answer with at least five digits after the decimal point.

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

const getMinTime = (a, v, l, d, w) => {
    let t1, t2, t3, t4, t5, t6, t7, t8, t9;
    let v1 = Math.sqrt(2 * a * d);
    let v2 = Math.sqrt(2 * a * (l - d));
    if (v < w) {
        if (v < v1 && v < v2) {
            t1 = v / a;
            t2 = (l - a * t1 * t1 / 2) / v;
            return t1 + t2;
        } else if (v1 < v2) {
            t1 = v1 / a;
            t2 = (l - a * t1 * t1 / 2) / v1;
            return t1 + t2;
        } else {
            t1 = v2 / a;
            t2 = (l - a * t1 * t1 / 2) / v2;
            return t1 + t2;
        }
    } else {
        if (v1 < w) {
            t1 = v1 / a;
            t2 = (l - a * t1 * t1 / 2) / v1;
            return t1 + t2;
        } else {
            t1 = w / a;
            t2 = (d - a * t1 * t1 / 2) / w;
            if (v2 < v) {
                t3 = v2 / a;
                t4 = (l - d - a * t3 * t3 / 2) / v2;
                return t1 + t2 + t3 + t4;
            } else {
                t3 = (v * v - w * w) / (2 * a);
                t4 = (l - d - t3) / v;
                return t1 + t2 + t3 / v + t4;
            }
        }
    }
}

rl.on('line', (line) => {
    let [a, v] = line.split(' ').map(Number);
    let [l, d, w] = line.split(' ').map(Number);
    console.log(getMinTime(a, v, l, d, w).toFixed(5));
});


The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it.

The first input line contains an integer n (1≤n≤1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000≤yi≤9999).

Print n numbers z1, z2, ..., zn (1000≤zi≤2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes).

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  const ils = ipt.split(EOL).slice(0, -1)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL).slice(1)
      if (iii[0] == 1081) {
        console.log(rr.slice(-50).reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = v
          return m
        }, []).map(l => l.join(' ')).join('\n'), iii.slice(rr.length - 3, rr.length + 3))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      if (f + fss == p + pss) return p + pss
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        if (ps.every(v => v == 9) && fs.filter(v => v != 9).length > 1)
          return pn + 1 + fss
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})


You have a simple undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.Let's make a definition.Let $$$v_1$$$ and $$$v_2$$$ be two some nonempty subsets of vertices that do not intersect. Let $$$f(v_{1}, v_{2})$$$ be true if and only if all the conditions are satisfied:  There are no edges with both endpoints in vertex set $$$v_1$$$.  There are no edges with both endpoints in vertex set $$$v_2$$$.  For every two vertices $$$x$$$ and $$$y$$$ such that $$$x$$$ is in $$$v_1$$$ and $$$y$$$ is in $$$v_2$$$, there is an edge between $$$x$$$ and $$$y$$$. Create three vertex sets ($$$v_{1}$$$, $$$v_{2}$$$, $$$v_{3}$$$) which satisfy the conditions below;  All vertex sets should not be empty.  Each vertex should be assigned to only one vertex set.  $$$f(v_{1}, v_{2})$$$, $$$f(v_{2}, v_{3})$$$, $$$f(v_{3}, v_{1})$$$ are all true. Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$3 \le n \le 10^{5}$$$, $$$0 \le m \le \text{min}(3 \cdot 10^{5}, \frac{n(n-1)}{2})$$$) — the number of vertices and edges in the graph.
The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$a_{i}$$$ and $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le n$$$) — it means there is an edge between $$$a_{i}$$$ and $$$b_{i}$$$. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.

If the answer exists, print $$$n$$$ integers. $$$i$$$-th integer means the vertex set number (from $$$1$$$ to $$$3$$$) of $$$i$$$-th vertex. Otherwise, print $$$-1$$$.
If there are multiple answers, print any.

const readline = require('readline')

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

function solve(n, edges) {
    const adj = {}
    for (let u = 1; u <= n; u++) {
        adj[u] = {}
    }
    edges.forEach(([a, b]) => {
        adj[a][b] = 1
        adj[b][a] = 1
    })

    const gs = Array(n + 1)
    const vs = []
    let g = 1
    for (let u = 1; u <= n; u++) {
        if (gs[u]) continue
        if (g > 3) return -1
        const temp = [u]
        gs[u] = g
        for (let v = u + 1; v <= n; v++) {
            if (!adj[u][v] && !gs[v]) {
                gs[v] = g
                temp.push(v)
            }
        }
        vs.push(temp)
        g++
    }
// console.log(gs, vs)
    if (vs.length < 3) return -1
    for (let i = 0; i < vs.length; i++) {
        for (let a = 0; a < vs[i].length; a++) {
            const u = vs[i][a]
            for (let j = i + 1; j < vs.length; j++) {
                for (let b = 0; b < vs[j].length; b++) {
                    const v = vs[j][b]
                    if (!adj[u][v]) return -1
                }
            }
        }
    }
    for (let [u, v] of edges) {
        if (gs[u] === gs[v]) return -1
    }
    gs.shift()
    return gs.join(' ')
}


Vasya plays the Geometry Horse.The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value. There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f  points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t+1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i+1 after destruction of pi (1≤i≤t) figures, so the (pi+1)-th figure to be destroyed is considered with factor equal to i+1.Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.

The first line contains the only integer number n (1≤n≤100) — the number of figure types.
Each of the following n lines contains two integer numbers ki and ci (1≤ki≤10^9,0≤ci≤1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly.
The next line contains the only integer number t (1≤t≤100) — the number that describe the factor's changes.
The next line contains t integer numbers pi (1≤p1<p2<...<pt≤10^12), separated with spaces.
Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.

Print the only number — the maximum number of points Vasya can get.

In the first example Vasya destroys three figures first and gets 3·1·10=30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10=40 points. As a result Vasya will get 70 points.
In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8+5·10)·1=74 points.

var readline = require('readline')
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
var inputs = []

const fn = debounce(function () {
  var n = +inputs[0];
  var monsters = inputs.slice(1, n + 1).map(function (str) {
    return str.split(' ').map(function (x) {
      return BigInt(x);
    });
  });
  var t = +inputs[n + 1];
  var p = inputs[n + 2].split(' ').map(function (x) {
    return BigInt(x);
  });
  p.push(BigInt(1e13));
  monsters.sort(function (a, b) {
    return Number(a[1] - b[1]);
  });
  var i = 0,
    j = 0,
    sum = 0n,
    ans = 0n,
    pre = 0n,
    factor = 1n;
  for (; i < n; i++) {
    var _a = monsters[i],
      cnt = _a[0],
      score = _a[1];
    sum += cnt;
    while (sum > p[j] && j < t) {
      ans += BigInt(p[j] - pre) * score * factor;
      // console.log(ans, p[j], pre, score, factor)
      pre = p[j];
      j++;
      factor++;
    }
    if (sum <= p[j]) {
      ans += BigInt(sum - pre) * score * factor;
      // console.log(ans, p[j], pre, score, factor)
      pre = sum;
    }
  }
  write(ans + '');
})
rl.on('line', function (line) {
  inputs.push(line.trim());
  fn()
})

function debounce(cb, delay) {
  if (delay === void 0) {
    delay = 100;
  }
  var timer = -1;
  return function () {
    if (timer !== -1) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      cb();
      timer = -1;
    }, delay);
  };
}

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