"use strict";
function Main(input) {
    let cin = new Inputer(input);
    let S = cin.getStr();
    let N = S.length;
    const ABC = ["A", "B", "C"];
    const MOD = 1000000007;
    let dp = new Array(N + 1).fill(0).map(() => new Array(4).fill(0));
    for (let i = N; i >= 0; --i) {
        for (let j = 3; j >= 0; --j) {
            if (i == N) {
                dp[i][j] = (j == 3 ? 1 : 0);
            } else {
                dp[i][j] = dp[i + 1][j] * (S[i] == '?' ? 3 : 1);
                if (j < 3 && (S[i] == '?' || S[i] == ABC[j])) {
                    dp[i][j] += dp[i + 1][j + 1];
                }
                dp[i][j] %= MOD;
            }
        }
    }
    console.log(dp[0][0]);
}
class Inputer{constructor(t){this.cnt=0,this.items=t.split(/\n|\s/)}getInt(){return this.items[this.cnt++]-0}getIntArray(t){let r=new Array(t);for(let e=0;e<t;e++)r[e]=this.getInt();return r}getStr(){return this.items[this.cnt++]}getStrArray(t){let r=new Array(t);for(let e=0;e<t;e++)r[e]=this.getStr();return r}}
if (typeof window == "undefined") Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 400 points

Problem Statement

The ABC number of a string T is the number of triples of integers (i, j, k) that satisfy all of the following conditions:

1 ≤ i < j < k ≤ |T| (|T| is the length of T.)

T_i = A (T_i is the i-th character of T from the beginning.)

T_j = B

T_k = C

For example, when T = ABCBC, there are three triples of integers (i, j, k) that satisfy the conditions: (1, 2, 3), (1, 2, 5), (1, 4, 5). Thus, the ABC number of T is 3.

You are given a string S. Each character of S is A, B, C or ?.

Let Q be the number of occurrences of ? in S. We can make 3^Q strings by replacing each occurrence of ? in S with A, B or C. Find the sum of the ABC numbers of all these strings.

This sum can be extremely large, so print the sum modulo 10^9 + 7.

Constraints

3 ≤ |S| ≤ 10^5

Each character of S is A, B, C or ?.

Input

Input is given from Standard Input in the following format:

S

Output

Print the sum of the ABC numbers of all the 3^Q strings, modulo 10^9 + 7.

Sample Input 1

A??C

Sample Output 1

8

In this case, Q = 2, and we can make 3^Q = 9 strings by by replacing each occurrence of ? with A, B or C. The ABC number of each of these strings is as follows:

AAAC: 0

AABC: 2

AACC: 0

ABAC: 1

ABBC: 2

ABCC: 2

ACAC: 0

ACBC: 1

ACCC: 0

The sum of these is 0 + 2 + 0 + 1 + 2 + 2 + 0 + 1 + 0 = 8, so we print 8 modulo 10^9 + 7, that is, 8.

Sample Input 2

ABCBC

Sample Output 2

3

When Q = 0, we print the ABC number of S itself, modulo 10^9 + 7. This string is the same as the one given as an example in the problem statement, and its ABC number is 3.

Sample Input 3

????C?????B??????A???????

Sample Output 3

979596887

In this case, the sum of the ABC numbers of all the 3^Q strings is 2291979612924, and we should print this number modulo 10^9 + 7, that is, 979596887.


"use strict";

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

function main(input) {
  var lines = input.split('\n');
  var S = lines[0];
  var nul = 1;
  var a = 0;
  var ab = 0;
  var abc = 0;
  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = S[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var ch = _step.value;

      if (ch === 'A') {
        a = (a + nul) % P;
      } else if (ch === 'B') {
        ab = (ab + a) % P;
      } else if (ch === 'C') {
        abc = (abc + ab) % P;
      } else if (ch === '?') {
        abc = (abc * 3 + ab) % P;
        ab = (ab * 3 + a) % P;
        a = (a * 3 + nul) % P;
        nul = nul * 3 % P;
      }
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return != null) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  console.log(abc);
}

var P = 1e9 + 7;
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

function splitNum(line) {
  return (Array.isArray(line) ? line : line.split(/\s+/)).map(function (n) {
    return parseInt(n);
  });
}
/**
 * Iterates over integers in [start, end).
 */

function* range(start, end) {
  for (var i = start; i < end; i++) {
    yield i;
  }
}
/**
 * Iterates over integers in [end, start) in desc order.
 */

function* rangeRev(start, end) {
  for (var i = start - 1; i >= end; i--) {
    yield i;
  }
}
/**
 * Runs a recursive function expressed as a generator function.
 */

function runRecursive(func) {
  // 最終結果を受け取るオブジェクトを用意
  var rootCaller = {
    lastReturnValue: null
  }; // 自前のコールスタックを用意

  var callStack = []; // 最初の関数呼び出しを追加

  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  callStack.push({
    iterator: func.apply(void 0, args),
    lastReturnValue: null,
    caller: rootCaller
  });

  while (callStack.length > 0) {
    var stackFrame = callStack[callStack.length - 1];
    var iterator = stackFrame.iterator,
        lastReturnValue = stackFrame.lastReturnValue,
        caller = stackFrame.caller; // 関数の実行を再開

    var _iterator$next = iterator.next(lastReturnValue),
        value = _iterator$next.value,
        done = _iterator$next.done;

    if (done) {
      // 関数がreturnしたので親に返り値を記録
      caller.lastReturnValue = value;
      callStack.pop();
    } else {
      // 関数がyieldした（valueは再帰呼び出しの引数リスト）
      callStack.push({
        iterator: func.apply(void 0, _toConsumableArray(value)),
        lastReturnValue: null,
        caller: stackFrame
      });
    }
  }

  return rootCaller.lastReturnValue;
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


// inputに入力データ全体が入る
function Main(input) {
	var min=Number.MAX_VALUE,max = Number.MIN_VALUE;
	var arr = input.split(" ").map(v=>parseInt(v)).forEach(v=>{min=Math.min(min,v); max=Math.max(max,v);});
	console.log(max-min);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

You have three tasks, all of which need to be completed.

First, you can complete any one task at cost 0.

Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.

Here, |x| denotes the absolute value of x.

Find the minimum total cost required to complete all the task.

Constraints

All values in input are integers.

1 \leq A_1, A_2, A_3 \leq 100

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

Print the minimum total cost required to complete all the task.

Sample Input 1

1 6 3

Sample Output 1

5

When the tasks are completed in the following order, the total cost will be 5, which is the minimum:

Complete the first task at cost 0.

Complete the third task at cost 2.

Complete the second task at cost 3.

Sample Input 2

11 5 5

Sample Output 2

6

Sample Input 3

100 100 100

Sample Output 3

0


const main = i => console.log(
  i.split(' ')
    .map(n => parseInt(n, 10))
    .filter(n => !isNaN(n))
    .map((n, i, arr) => Math.abs(arr[(i + 1) % arr.length] - n))
    .sort()
    .slice(0, 2)
    .reduce((prev, curr) => prev + curr, 0)
)

main(require('fs').readFileSync('/dev/stdin', 'utf-8'))


"use strict";
const Main = (input) =>{
   let xs = input.trim().split('\n');
   let X = xs[0].split('');
   let Y = xs[1].split('');
   X.sort();
   Y.sort();
   let len = X.length;
   let num = 0;
   for(let i=0; i<len; i++){
     if(X[i]==Y[i]){
     num +=1;
     }else{
     num +=0;
     }
   }
   //console.log(num)

   if(num == len){
     console.log('Yes');
     }else{
     console.log('No');
     }
}
Main(require('fs').readFileSync('/dev/stdin','utf8'));

Score : 200 points

Problem Statement

You are given string S and T consisting of lowercase English letters.

Determine if S equals T after rotation.

That is, determine if S equals T after the following operation is performed some number of times:

Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}.

Here, |X| denotes the length of the string X.

Constraints

2 \leq |S| \leq 100

|S| = |T|

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S equals T after rotation, print Yes; if it does not, print No.

Sample Input 1

kyoto
tokyo

Sample Output 1

Yes

In the first operation, kyoto becomes okyot.

In the second operation, okyot becomes tokyo.

Sample Input 2

abc
arc

Sample Output 2

No

abc does not equal arc after any number of operations.

Sample Input 3

aaaaaaaaaaaaaaab
aaaaaaaaaaaaaaab

Sample Output 3

Yes


var lines = [];
var readline = require('readline');

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

rl.on('line', function (x) {
    lines.push(x);
});

rl.on('close', function () {
    var S = lines[0].split("")
    var T = lines[0].split("")

    for (var i = 0; i < T.length; i++){
        if(S === T){console.log("Yes"); return(0)}
        var x = S.pop()
        S.unshift(x);
    }
    console.log("No");
});


function Main(input) {
    var inputArr = input.split('\n');
    var S = inputArr[0];
    var T = inputArr[1];
    var flg = false;

    for(var i = 0 ; i <= S.length ; ++i) {
        if (S === T) {
            flg = true;
            break;
        }
        S = S.slice(S.length - 1) + S.slice(0, S.length-1);
    }

    if (flg) console.log('Yes');
    else console.log('No');
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


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

// inputに入力データ全体が入る
function Main(input) {
  // 1行目がline1, 2行目がline2, …に入る
  var arg   = input.split("\n");
  var line0 = arg[0].split(" ");
  var line1 = arg[1].split(" ");
  //var line2 = tmp[2].split(" ");
  //var line3 = tmp[3].split(" ");

  var input1 = (line0[0]);
  var input2 = (line1[0]);
  //var input3 = Number(line0[2]);
  var a = input1;
  var b = input2;
  //var c = input3;

  var ans = "No";

  //console.log( line0 +" "+ a +" "+ b +" "+ "");

  for(var i=0; i<a.length; i++){
    var first = a[0];
    //console.log("before a = " +  a);

    var tmp =  a.slice(1, a.length);
    //a.push(first);
    //console.log("tmp = " + tmp);
    a = tmp + first;
    //console.log("after a = " + a)

    if(a === b) ans = "Yes"
  }

  console.log(ans);

}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict'

function Main(input) {
  const S = input.split('\n')[0];
  const T = input.split('\n')[1];

  const T2 = T + T;

  if (T2.indexOf(S) !== -1) {
    console.log('Yes');
  } else {
    console.log('No');
  }

}

Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


function gcd(a, b) {
    if (a < b) {
        var tmp = b;
        b = a;
        a = tmp;
    }

    if (b === 0) return a;
    return gcd(b, a%b);
}

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

function Main(input) {
    var inputArr = input.split('\n');
    var N = parseInt(inputArr[0]);
    var a = inputArr[1].split(' ').map(function(num) { return parseInt(num) });

    var koubai = 0;
    for (var i = 0 ; i < a.length - 1 ; ++i) {
        if (koubai === 0) koubai = lcm(a[i], a[i+1]);
        else koubai = lcm(koubai, a[i+1]);
    }

    var sum = 0;
    for (var i = 0 ; i < a.length ; ++i) {
        sum += (koubai*2-1)%a[i];
    }
    console.log(sum);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

You are given N positive integers a_1, a_2, ..., a_N.

For a non-negative integer m, let f(m) = (m\ mod\ a_1) + (m\ mod\ a_2) + ... + (m\ mod\ a_N).

Here, X\ mod\ Y denotes the remainder of the division of X by Y.

Find the maximum value of f.

Constraints

All values in input are integers.

2 \leq N \leq 3000

2 \leq a_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the maximum value of f.

Sample Input 1

3
3 4 6

Sample Output 1

10

f(11) = (11\ mod\ 3) + (11\ mod\ 4) + (11\ mod\ 6) = 10 is the maximum value of f.

Sample Input 2

5
7 46 11 20 11

Sample Output 2

90

Sample Input 3

7
994 518 941 851 647 2 581

Sample Output 3

4527


const main = i => console.log(
  ('-' + i)
    .split(/\s/)
    .map(n => parseInt(n))
    .filter(n => !isNaN(n))
    .reduce((prev, curr) => prev + curr, 0)
)

main(require('fs').readFileSync('/dev/stdin', 'utf-8'))


const main = (arg) => {
  const lines = arg.trim().split('\n');
  const N = Number.parseInt(lines[0]);
  console.log(N % 2 == 0 ? N : 2 * N);
};
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

You are given a positive integer N.
Find the minimum positive integer divisible by both 2 and N.

Constraints

1 \leq N \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum positive integer divisible by both 2 and N.

Sample Input 1

3

Sample Output 1

6

6 is divisible by both 2 and 3.
Also, there is no positive integer less than 6 that is divisible by both 2 and 3.
Thus, the answer is 6.

Sample Input 2

10

Sample Output 2

10

Sample Input 3

999999999

Sample Output 3

1999999998


function main(input) {
    var n = input[0]-0;
    console.log(n%2==0?n:n*2);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"))


function Main(s) {
  var a
  if (s % 2 === 1) {
    a = s
  } else {
    a = s * 2
  }
  console.log(a)
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict'

const main = input => {
	const args = input.trim().split('\n')
	const n = parseInt(args[0], 10)
	const a = args[1].split(' ').map(Number)
	let min = 1000000001
	let max = 0

	for (let i = 0; i < n; i++) {
		min = Math.min(min, a[i])
		max = Math.max(max, a[i])
	}

	console.log(max - min)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))

Score : 200 points

Problem Statement

You are given an integer sequence A of length N.
Find the maximum absolute difference of two elements (with different indices) in A.

Constraints

2 \leq N \leq 100

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum absolute difference of two elements (with different indices) in A.

Sample Input 1

4
1 4 6 3

Sample Output 1

5

The maximum absolute difference of two elements is A_3-A_1=6-1=5.

Sample Input 2

2
1000000000 1

Sample Output 2

999999999

Sample Input 3

5
1 1 1 1 1

Sample Output 3

0


process.stdin.on('data', d => {
  const a = (d + '').split(/\s/).slice(1).sort((a, b) => b - a);
  console.log(a.shift() - a.pop());
})


'use strict';
const inputRaw = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
const INPUT_LIST_LENGTH_INDEX = 0;
const INPUT_LIST_INDEX = 1;
const INPUT_LIST_DELIMITER = " ";
const inputListLength = parseInt(inputRaw[INPUT_LIST_LENGTH_INDEX]);
const inputList = inputRaw[INPUT_LIST_INDEX].split(INPUT_LIST_DELIMITER);

const process = (inputList, inputListLength) => {
  // pattern: min(b) in (sum(A-b)) === median of sorted A

  // sum(A - (b + i)) === sum ((A - i) - b)
  // convert list to A-i
  for (let i=0;i<inputListLength;i++) {
    inputList[i] = parseInt(inputList[i])-i;
  }

  const median = inputList[Math.floor(inputListLength/2)];

  return inputList.reduce((acc, currentItem) => acc + Math.abs(currentItem-median), 0);
}

console.log(process(inputList, inputListLength));

Score : 300 points

Problem Statement

Snuke has an integer sequence A of length N.

He will freely choose an integer b.
Here, he will get sad if A_i and b+i are far from each other.
More specifically, the sadness of Snuke is calculated as follows:

abs(A_1 - (b+1)) + abs(A_2 - (b+2)) + ... + abs(A_N - (b+N))

Here, abs(x) is a function that returns the absolute value of x.

Find the minimum possible sadness of Snuke.

Constraints

1 \leq N \leq 2 \times 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible sadness of Snuke.

Sample Input 1

5
2 2 3 5 5

Sample Output 1

2

If we choose b=0, the sadness of Snuke would be abs(2-(0+1))+abs(2-(0+2))+abs(3-(0+3))+abs(5-(0+4))+abs(5-(0+5))=2.
Any choice of b does not make the sadness of Snuke less than 2, so the answer is 2.

Sample Input 2

9
1 2 3 4 5 6 7 8 9

Sample Output 2

0

Sample Input 3

6
6 5 4 3 2 1

Sample Output 3

18

Sample Input 4

7
1 1 1 1 2 3 4

Sample Output 4

6


'use strict';

const input = require("fs").readFileSync("/dev/stdin", "utf8").split("\n");
const count = parseInt(input[0]);
const inputList = input[1].split(" ");

const process = (input, count) => {
    for (let i=0; i<count; i++) {
        input[i] = parseInt(input[i]) - (i + 1);
    }
    const sorted = input.sort((a,b) => a-b);
    const median = Math.floor(sorted[count/2]);

    return input.reduce((acc, curr) => acc + Math.abs(curr - median), 0);
}

console.log(process(inputList,  count));


'use strict';

function Main(INPUT) {
    const S = INPUT.split("");
    let N = 0;
    for (let i = 0; i < S.length; i++) {
        if (S[i] == "+") {
            N++;
        } else {
            N--;
        }
    }
    console.log(N);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

There is always an integer in Takahashi's mind.

Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is + or -. When he eats +, the integer in his mind increases by 1; when he eats -, the integer in his mind decreases by 1.

The symbols Takahashi is going to eat are given to you as a string S. The i-th character in S is the i-th symbol for him to eat.

Find the integer in Takahashi's mind after he eats all the symbols.

Constraints

The length of S is 4.

Each character in S is + or -.

Input

Input is given from Standard Input in the following format:

S

Output

Print the integer in Takahashi's mind after he eats all the symbols.

Sample Input 1

+-++

Sample Output 1

2

Initially, the integer in Takahashi's mind is 0.

The first integer for him to eat is +. After eating it, the integer in his mind becomes 1.

The second integer to eat is -. After eating it, the integer in his mind becomes 0.

The third integer to eat is +. After eating it, the integer in his mind becomes 1.

The fourth integer to eat is +. After eating it, the integer in his mind becomes 2.

Thus, the integer in Takahashi's mind after he eats all the symbols is 2.

Sample Input 2

-+--

Sample Output 2

-2

Sample Input 3

----

Sample Output 3

-4


function main(input) {
    input = input.split('')
    input = input.map(x => Number(x + 1))
    var ans = input.reduce((x, y) => x + y)
    console.log(ans)

}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict"

function main(input) {
    input = input.split('')
    input = input.map(x => Number(x + 1))
        //let ans = input.reduce((x, y) => x + y)
    let ans = 0;
    for (let i in input) {

        ans += input[i]

    }
    console.log(ans)

}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim();}
function myout(text){console.log(text);}//standard output
//[no]param
//0:noConvert	1:singleNum	2:spaceList	3:newLineList	4:spaceNumList	5:newLineNumList
function myconv(i,no){switch(no){case 0:return i;case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));}}

function Main(input) {
  input = myconv(input,1);
  var tmpInput = input.toString();
  var check = 0;
  for(var i = 0; i < tmpInput.length; i++){
    check += parseInt(tmpInput.slice(i,i+1));
  }
  if(input % check == 0){
     myout("Yes");
     }else{
     myout("No");
     }

}

Main(myin());

Score : 200 points

Problem Statement

Let S(n) denote the sum of the digits in the decimal notation of n.
For example, S(101) = 1 + 0 + 1 = 2.

Given an integer N, determine if S(N) divides N.

Constraints

1 \leq N \leq 10^9

Input

Input is given from Standard Input in the following format:

N

Output

If S(N) divides N, print Yes; if it does not, print No.

Sample Input 1

12

Sample Output 1

Yes

In this input, N=12.
As S(12) = 1 + 2 = 3, S(N) divides N.

Sample Input 2

101

Sample Output 2

No

As S(101) = 1 + 0 + 1 = 2, S(N) does not divide N.

Sample Input 3

999999999

Sample Output 3

Yes


"use strict";

function main(arg) {
    const N = arg.split("\n")[0];
    const S = N.split("").map(n=>parseInt(n)).reduce((m,n)=>m+n);
    console.log(N % S === 0 ? "Yes" : "No");
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main (input) {
  const inputValue = input.split(/\s/g)[0];
  const sum = inputValue.split('').map((num) => parseInt(num)).reduce((prev, current) => prev + current, 0);
  const result = parseInt(inputValue) % sum === 0 ? 'Yes' : 'No';
  console.log('%s', result);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input){

console.log("No");
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


Score : 300 points

Problem Statement

There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.

On this sequence, Snuke can perform the following operation:

Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.

Snuke would like to make all the elements in this sequence equal by repeating the operation above some number of times.
Find the minimum number of operations required.
It can be proved that, Under the constraints of this problem, this objective is always achievable.

Constraints

2 \leq K \leq N \leq 100000

A_1, A_2, ..., A_N is a permutation of 1, 2, ..., N.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of operations required.

Sample Input 1

4 3
2 3 1 4

Sample Output 1

2

One optimal strategy is as follows:

In the first operation, choose the first, second and third elements. The sequence A becomes 1, 1, 1, 4.

In the second operation, choose the second, third and fourth elements. The sequence A becomes 1, 1, 1, 1.

Sample Input 2

3 3
1 2 3

Sample Output 2

1

Sample Input 3

8 3
7 3 1 8 4 6 2 5

Sample Output 3

4


function Main(input) {
	a=input.split('\n');
	b=a[0].split(' ').map(Number);
	c=a[1].split(' ').map(Number);

	N=b[0], K=b[1], r=0;

	while(c.length>1){
		r++;
		d=[];
		for(i=0;i<K;i++){
			d.push(c[i]);
		}

		for(i=0;i<K;i++){
			if(d.sort()[0]!==c[i]){
				c[i]='';
			}
		}

		c=c.join('').split('').map(Number);
	}

	console.log(r);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


// A: LCM
// NG
"use strict";
/*const inputRaw = require("fs")
  .readFileSync("/dev/stdin", "utf8")
  .trim()
  .split("\n");*/
const inputRaw = "8 3\n7 3 1 8 4 6 2 5".split("\n");

const INPUT_SETTINGS_INDEX = 0;
const INPUT_LIST_INDEX = 1;
const INPUT_SETTINGS_N_INDEX = 0;
const INPUT_SETTINGS_K_INDEX = 1;
const INPUT_DELIMITER = " ";

const inputSettings = inputRaw[INPUT_SETTINGS_INDEX].split(INPUT_DELIMITER);
const N = inputSettings[INPUT_SETTINGS_N_INDEX];
const K = inputSettings[INPUT_SETTINGS_K_INDEX];
const inputList = inputRaw[INPUT_LIST_INDEX].split(INPUT_DELIMITER).map(curr => parseInt(curr));

const findMinAndIndex = intList =>
  intList.reduce((acc, curr, index) => (curr < acc ? curr : acc), {
    item: intList[0],
    index: 0,
  });

const process = (N, K, inputList) => {
  let count = 0;
  let currentIndex = 0;
  const output = findMinAndIndex(inputList);
  const item = output.item;
  const index = output.index;

  if (N > 2*K) {
    if (index > K-1 && index < N-K) {
      return Math.floor(N / (K - 1)) + 2;
    } else {
      return Math.floor(N / (K - 1));
    }
  } else {
    return Math.floor(N / (K - 1));
  }
};

console.log(process(parseInt(N), parseInt(K), inputList));


function Main(input) {
  input=input.split("\n");
  if(input[input.length-1]===''){
    input.pop();
  }
  const K=input[0].split(' ')[0]-0;
  var ans=1;
  for(var i=0;i<K;i++){
    console.log(ans);
    ans+=10**(Math.floor(Math.log10(ans+1)));
  }

}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 500 points

Problem Statement

Let S(n) denote the sum of the digits in the decimal notation of n.
For example, S(123) = 1 + 2 + 3 = 6.

We will call an integer n a Snuke number when, for all positive integers m such that m > n, \frac{n}{S(n)} \leq \frac{m}{S(m)} holds.

Given an integer K, list the K smallest Snuke numbers.

Constraints

1 \leq K

The K-th smallest Snuke number is not greater than 10^{15}.

Input

Input is given from Standard Input in the following format:

K

Output

Print K lines. The i-th line should contain the i-th smallest Snuke number.

Sample Input 1

10

Sample Output 1

1
2
3
4
5
6
7
8
9
19


import java.io.*;

class Main {
 public static void main(String arts[]) [
  Scanner sc = new Scanner(System.in);
  int A = sc.nextInt();
  int B = sc.nextInt();

  if(　A >=　9　) {
    System.out.print(":(");
  }
  if( B >= 9 ）{
    System.out.print(":(")
  }
  if( A < 9 B < 9 ) {
    System.out.print("Yay!")
  }
 ]
}

Score: 100 points

Problem Statement

E869120's and square1001's 16-th birthday is coming soon.

Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces.

E869120 and square1001 were just about to eat A and B of those pieces, respectively,

when they found a note attached to the cake saying that "the same person should not take two adjacent pieces of cake".

Can both of them obey the instruction in the note and take desired numbers of pieces of cake?

Constraints

A and B are integers between 1 and 16 (inclusive).

A+B is at most 16.

Input

Input is given from Standard Input in the following format:

A B

Output

If both E869120 and square1001 can obey the instruction in the note and take desired numbers of pieces of cake, print Yay!; otherwise, print :(.

Sample Input 1

5 4

Sample Output 1

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 2

8 8

Sample Output 2

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 3

11 4

Sample Output 3

:(

In this case, there is no way for them to take desired number of pieces, unfortunately.


function Main(input) {
  input = input.split(" ");
  var a = parseInt(input[0]);
  var b = parseInt(input[1]);

  var num = b - a;
  var result = 0;
  function treeHeight(number) {
    for (var i = 1; i <= number; i++) {
      result += i;
    }
    return result;
  }

  var treeB = treeHeight(num);
  console.log(treeB - b);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 200 points

Problem Statement

In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter.

It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not covered with snow, and the results are a meters for the west tower, and b meters for the east tower.

Assuming that the depth of snow cover and the altitude are the same everywhere in the village, find the amount of the snow cover.

Assume also that the depth of the snow cover is always at least 1 meter.

Constraints

1 \leq a < b < 499500(=1+2+3+...+999)

All values in input are integers.

There is no input that contradicts the assumption.

Input

Input is given from Standard Input in the following format:

a b

Output

If the depth of the snow cover is x meters, print x as an integer.

Sample Input 1

8 13

Sample Output 1

2

The heights of the two towers are 10 meters and 15 meters, respectively.
Thus, we can see that the depth of the snow cover is 2 meters.

Sample Input 2

54 65

Sample Output 2

1


var obj = init();
Main();
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
function next(){return obj.next();}
function hasNext(){return obj.hasNext();}
function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");}
function init(){
  var inputFile = myin();
  var returnObj = {
    "list" : inputFile, "index" : 0, "max" : inputFile.length,
    "hasNext" : function(){return (this.index < this.max);},
    "next" : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(t){console.log(t);}//標準出力
function myerr(t){console.error(t);}//標準エラー出力
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す　1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main(){
  var N = nextInt();
  var list = [1];
  var dp = new Array(N + 1).fill(100007);
  dp[0] = 0;
  for(var i = 1; i <= 9; i++){
    var six = Math.pow(6,i);
    if(six <= N){
      list.push(six);
    }
    var nine = Math.pow(9,i);
    if(nine <= N){
      list.push(nine);
    }
  }
  list.sort(function(a,b){
  	return a - b;
  });
  for(var i = 0; i < list.length; i++){
    for(var j = list[i]; j <= N; j++){
      dp[j] = Math.min(dp[j],dp[j - list[i]] + 1);
    }

    //myerr(dp);
  }
  //myerr(list);

  myout(dp[N]);
}

Score : 300 points

Problem Statement

To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation:

1 yen (the currency of Japan)

6 yen, 6^2(=36) yen, 6^3(=216) yen, ...

9 yen, 9^2(=81) yen, 9^3(=729) yen, ...

At least how many operations are required to withdraw exactly N yen in total?

It is not allowed to re-deposit the money you withdrew.

Constraints

1 \leq N \leq 100000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If at least x operations are required to withdraw exactly N yen in total, print x.

Sample Input 1

127

Sample Output 1

4

By withdrawing 1 yen, 9 yen, 36(=6^2) yen and 81(=9^2) yen, we can withdraw 127 yen in four operations.

Sample Input 2

3

Sample Output 2

3

By withdrawing 1 yen three times, we can withdraw 3 yen in three operations.

Sample Input 3

44852

Sample Output 3

16


"use strict";

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

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

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

function main(input) {
  var lines = input.split('\n');

  var _splitNum = splitNum(lines[0]),
      _splitNum2 = _slicedToArray(_splitNum, 1),
      N = _splitNum2[0];

  var nums = [[1, 1]];

  for (var i = 6; i <= 100000; i *= 6) {
    nums.push([i, 1], [i * 2, 2]);
  }

  for (var _i2 = 9; _i2 <= 100000; _i2 *= 9) {
    nums.push([_i2, 1]);
  }

  nums.sort(function (_ref, _ref2) {
    var _ref3 = _slicedToArray(_ref, 2),
        a = _ref3[0],
        _ = _ref3[1];

    var _ref4 = _slicedToArray(_ref2, 2),
        b = _ref4[0],
        _2 = _ref4[1];

    return b - a;
  });
  var result = 0;
  var current = N;

  for (var _i3 = 0; _i3 < nums.length; _i3++) {
    var _nums$_i = _slicedToArray(nums[_i3], 2),
        num = _nums$_i[0],
        cost = _nums$_i[1];

    while (current >= num) {
      result += cost;
      current -= num;
    }
  }

  console.log(result);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));

function splitNum(line) {
  return line.split(/\s+/).map(function (n) {
    return parseInt(n);
  });
}


'use strict'
function main(input) {
  input = input.trim()
  if (input.match(/^10+$/)) {
    console.log(10)
  } else {
    console.log(input.split('').reduce((r, c) => Number(r) + Number(c), 0))
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 200 points

Problem Statement

Takahashi has two positive integers A and B.

It is known that A plus B equals N.
Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10).

Constraints

2 ≤ N ≤ 10^5

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B".

Sample Input 1

15

Sample Output 1

6

When A=2 and B=13, the sums of their digits are 2 and 4, which minimizes the value in question.

Sample Input 2

100000

Sample Output 2

10


function main(input){
  input = input.trim();
  const a = input.split(" ");
  const n = parseInt(a[0], 10),
        m = parseInt(a[1], 10);

  console.log(Math.max(n+m,n-m,n*m));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

You are given two integers A and B.
Find the largest value among A+B, A-B and A \times B.

Constraints

-1000 \leq A,B \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest value among A+B, A-B and A \times B.

Sample Input 1

3 1

Sample Output 1

4

3+1=4, 3-1=2 and 3 \times 1=3. The largest among them is 4.

Sample Input 2

4 -2

Sample Output 2

6

The largest is 4 - (-2) = 6.

Sample Input 3

0 0

Sample Output 3

0


inp = require('fs').readFileSync('/dev/stdin', 'utf8').split('\n')
l = inp.shift().split(' ')
A = l[0] * 1
B = l[1] * 1
max = A + B
if (max < A - B) {
    max = A - B
}
if (max < A * B) {
    max = A * B
}
if (max === 0) {
    max = 0
}
console.log(max)


function Main(input) {
	input = input.trim().split(" ").map((a)=>Number(a));
  var A = input[0];
  var B = input[1];
  var list = [A+B,A-B,A*B];
  console.log(Math.max.apply(null,list));
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input){
  let xs = input.trim().split(' ').map(v=>parseInt(v,10));
  let a = xs[0] + xs[1];
  let b = xs[0] - xs[1];
  let c = xs[0] * xs[1];

  console.log(Math.max(a, b, c));
}

Main(require("fs").readFileSync("/dev/stdin","utf8"));


'use strict';

function Main(INPUT) {
    const N = INPUT.split(" ").map(n => Number(n));
    console.log(Math.max(N[0] + N[1], N[0] - N[1], N[0] * N[1]));
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(s){
  s = s.split(" ").map(a=>+a);
  var a = s[0];
  var b = s[1];
  console.log(0+Math.max(a+b, a-b, a*b));
}

Main(require("fs").readFileSync("/dev/stdin","utf8"));


'use strict'

function main(input) {
    input = input.split("\n");
    const N = parseInt(input[0]);
    const S = input[1];
    let ans = 0;
    for (let i = 0; i < N; i++) {
        let count = 0;
        let obj = {};
        for (let j = 0; j < i; j++) {
            obj[S[j]] = true;
        }
        for (let j = i; j < N; j++) {
            if (obj[S[j]]) {
                count++;
                delete obj[S[j]];
            }
        }
        if (count > ans)
            ans = count;
    }
    console.log(ans);
}

main(require('fs').readFileSync('/dev/stdin', 'utf-8'));

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters.
We will cut this string at one position into two strings X and Y.
Here, we would like to maximize the number of different letters contained in both X and Y.
Find the largest possible number of different letters contained in both X and Y when we cut the string at the optimal position.

Constraints

2 \leq N \leq 100

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the largest possible number of different letters contained in both X and Y.

Sample Input 1

6
aabbca

Sample Output 1

2

If we cut the string between the third and fourth letters into X = aab and Y = bca, the letters contained in both X and Y are a and b.
There will never be three or more different letters contained in both X and Y, so the answer is 2.

Sample Input 2

10
aaaaaaaaaa

Sample Output 2

1

However we divide S, only a will be contained in both X and Y.

Sample Input 3

45
tgxgdqkyjzhyputjjtllptdfxocrylqfqjynmfbfucbir

Sample Output 3

9


const input = require('fs').readFileSync('/dev/stdin', 'utf8').split('\n');
const N = input[0];
const S = input[1];
let max = 0;
let used = [];
for (let i = 1; i < N; i++) {
  const k = S.slice(i - 1, i);
  if (used.indexOf(k) >= 0) {
    used.splice(used.indexOf(k), 1);
  }
  for (let ii = i; ii < N; ii++) {
    if (k == S.slice(ii, ii + 1) && 0 > used.indexOf(k)) {
      f = true;
      used.push(k);
    }
  }
  if (used.length > max) max = used.length;
}
console.log(max);


'use strict'

function Main(input) {
  const N = Number(input.split('\n')[0]);
  const S = input.split('\n')[1].split('');

  let S_left, S_right;
  let counter = 0;
  let sufferlist = [];

  for(let i=1; i<N; i++) {
    S_left = S.slice(0, i)
      .filter((x,i,self) => self.indexOf(x) === i);
    S_right = S.slice(i)
      .filter((x,i,self) => self.indexOf(x) === i);

    for(let j=0; j<S_left.length ;j++) {
      if(S_right.some(value => value === S_left[j])) {
        counter++;
      }
    }
    sufferlist.push(counter);
    counter = 0;

    //console.log(S_left);
    //console.log(S_right);
    //console.log(sufferlist);
  }

  console.log(Math.max.apply(null, sufferlist));

}

Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


const countChar = (str, char) => str.split(char).length - 1;

function Main (input) {
  const inputs = input.split(/\s/g);
  const membersNum = parseInt(inputs[0]);
  const members = inputs[1];
  var result = membersNum;
  var index = 0;

  if (membersNum >= 3 * Math.pow(10, 5)) return;

  while (index < membersNum) {
    const left = members.substr(0, index);
    const right = members.substr(index + 1);
    const sum = countChar(left, 'W') + countChar(right, 'E');
    if (result > sum) result = sum;
    index += 1;
  }
  console.log('%s', result || 1);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

There are N people standing in a row from west to east.
Each person is facing east or west.
The directions of the people is given as a string S of length N.
The i-th person from the west is facing east if S_i = E, and west if S_i = W.

You will appoint one of the N people as the leader, then command the rest of them to face in the direction of the leader.
Here, we do not care which direction the leader is facing.

The people in the row hate to change their directions, so you would like to select the leader so that the number of people who have to change their directions is minimized.
Find the minimum number of people who have to change their directions.

Constraints

2 \leq N \leq 3 \times 10^5

|S| = N

S_i is E or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of people who have to change their directions.

Sample Input 1

5
WEEWW

Sample Output 1

1

Assume that we appoint the third person from the west as the leader.
Then, the first person from the west needs to face east and has to turn around.
The other people do not need to change their directions, so the number of people who have to change their directions is 1 in this case.
It is not possible to have 0 people who have to change their directions, so the answer is 1.

Sample Input 2

12
WEWEWEEEWWWE

Sample Output 2

4

Sample Input 3

8
WWWWWEEE

Sample Output 3

3


'use strict'

function main(s) {

  const lines  = s.split('\n')[1].split('');
  const points = [];

  let count = 0;
  for (let i = 0; i < lines.length; i++) {
    if (lines[i] === 'W') {
      count += 1;
    } else {
      count -= 1;
    }
    points.push(count);
  }

  const index = points.indexOf(Math.min(...points));
  const left  = lines.slice(0, index).filter(p => p === 'W').length;
  const right = lines.slice(index + 1).filter(p => p === 'E').length;
  const result = left + right;

  console.log(result);
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


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

var g_input = '';
process.stdin.on('data', function(chunk) {
    g_input += chunk;
});

process.stdin.on('end', function() {
    Main(g_input.split(/\r?\n/));
});

function Main(input) {

    var n = parseInt(input[0], 10);
    var s = input[1].split('');

    var ww = 0;
    var we = 0;
    var ew = 0;
    var ee = 0;
    var rightCharCount = {};
    var leftCharCount = {};

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

        if (s[i] === 'W') {
            ew++;
        }
        else {
            ee++;
        }
    }

    var change = 0;
    var ans = Number.MAX_SAFE_INTEGER;

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

        if (s[i] === 'W') {
            ew--;
        }
        else {
            ee--;
        }

        change = ww + ee;
        ans = Math.min(ans, change);

        if (s[i] === 'W') {
            ww++;
        }
        else {
            we++;
        }
    }

    console.log(ans);

    return 0;
}


"use strict"
let input = require("fs").readFileSync("/dev/stdin","utf-8");
input = input.split("\n");

let peopleLine = input[1]

let changeNum = 0; // 向きを変える人数
// 左端の人がリーダーの場合の向きを変える人数を数える
for(let i = 1; i < peopleLine.length; i++){
    changeNum += peopleLine[i] == "E" ? 1 : 0;
}
let minChangeNum = changeNum;

// 1つずつずらしてみて、向きを変える人数をそれぞれ計算する
for(let i = 1; i < peopleLine.length; i++){
    changeNum += peopleLine[i - 1] == "W" ? 1 : 0;
    changeNum -= peopleLine[i] == "E" ? 1 : 0;
    minChangeNum = Math.min(minChangeNum, changeNum);
}
console.log(minChangeNum);


function main(input) {
   input = input.trim();
  const a = input.split(" ").map(Number);
 console.log(Math.abs(a[2]-a[0])<=a[3]
		|| (Math.abs(a[1]-a[0])<=a[3] && Math.abs(a[1]-a[2])<=a[3])?"Yes":"No");

}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

Three people, A, B and C, are trying to communicate using transceivers.
They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively.
Two people can directly communicate when the distance between them is at most d meters.
Determine if A and C can communicate, either directly or indirectly.
Here, A and C can indirectly communicate when A and B can directly communicate and also B and C can directly communicate.

Constraints

1 ≤ a,b,c ≤ 100

1 ≤ d ≤ 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

If A and C can communicate, print Yes; if they cannot, print No.

Sample Input 1

4 7 9 3

Sample Output 1

Yes

A and B can directly communicate, and also B and C can directly communicate, so we should print Yes.

Sample Input 2

100 10 1 2

Sample Output 2

No

They cannot communicate in this case.

Sample Input 3

10 10 10 1

Sample Output 3

Yes

There can be multiple people at the same position.

Sample Input 4

1 100 2 10

Sample Output 4

Yes


function Main(input){
	input1 = input.split('\n');
    input2 = input1.map(input1=>parseInt(input1,10));
    a = input3[0];
    b = input3[1];
    c = input3[2];
    d = input3[3];
    if((Math.abs(a-b <=d)) ||(Math.abs(a-b <=d) && Math.abs(b-c <=d))){
    console.log('Yes');
    }else{
    console.log('No');
    }
}
Main(require("fs").readFileSync("/dev/stdin","utf8"));


process.stdin.setEncoding('utf-8');
let count = 0;
let string;
process.stdin.on('data', function(data) {
    count++;
    // console.log(data);

    switch (count) {
        case 1:
            string = data.toString().toLowerCase();
            break;
        case 2:
            main(string, Number(data));
            break;
    }
    // process.exit();
});

function main(string, K) {
    const substringCounts = string.length;

    if(substringCounts < 1 || 5000 < substringCounts)
        process.exit();

    if(K < 1 || 5 < K)
        process.exit();

    let stacks = [];
    let _substr = '';
    for(let i = 0; i <= substringCounts; i++) {
        for(let j = i; j <= substringCounts; j++) {
            _substr = string.substring(i, j);
            if(!stacks.includes(_substr) && !_substr.includes('\n') && _substr !== '')
                stacks.push(string.substring(i, j));
        }
    }
    stacks.sort();
    console.log(stacks[K-1]);
    process.exit();
};

Score : 300 points

Problem Statement

You are given a string s.
Among the different substrings of s, print the K-th lexicographically smallest one.

A substring of s is a string obtained by taking out a non-empty contiguous part in s.
For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z and an empty string are not.
Also, we say that substrings are different when they are different as strings.

Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.

Constraints

1 ≤ |s| ≤ 5000

s consists of lowercase English letters.

1 ≤ K ≤ 5

s has at least K different substrings.

Partial Score

200 points will be awarded as a partial score for passing the test set satisfying |s| ≤ 50.

Input

Input is given from Standard Input in the following format:

s
K

Output

Print the K-th lexicographically smallest substring of K.

Sample Input 1

aba
4

Sample Output 1

b

s has five substrings: a, b, ab, ba and aba.
Among them, we should print the fourth smallest one, b.
Note that we do not count a twice.

Sample Input 2

atcoderandatcodeer
5

Sample Output 2

andat

Sample Input 3

z
1

Sample Output 3

z


const input = require('fs').readFileSync('/dev/stdin', 'utf8');

const list = input.split(' ');

const a = Number(list[0]);

const b = Number(list[1]);

if (a > b) {
  console.log(a - 1);
} else {
  console.log(a);
}

Score: 100 points

Problem Statement

In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year.

For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year.

In this country, a date is called Takahashi when the month and the day are equal as numbers. For example, 5-5 is Takahashi.

How many days from 2018-1-1 through 2018-a-b are Takahashi?

Constraints

a is an integer between 1 and 12 (inclusive).

b is an integer between 1 and 31 (inclusive).

2018-a-b is a valid date in Gregorian calendar.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the number of days from 2018-1-1 through 2018-a-b that are Takahashi.

Sample Input 1

5 5

Sample Output 1

5

There are five days that are Takahashi: 1-1, 2-2, 3-3, 4-4 and 5-5.

Sample Input 2

2 1

Sample Output 2

1

There is only one day that is Takahashi: 1-1.

Sample Input 3

11 30

Sample Output 3

11

There are eleven days that are Takahashi: 1-1, 2-2, 3-3, 4-4, 5-5, 6-6, 7-7, 8-8, 9-9, 10-10 and 11-11.


const BKRT = "\n";
const SPAC = " ";
const NOSP = "";

function Main(input){
	input = [].concat(...input.split(BKRT).map(a=>a.split(SPAC)));
  const strShift = ()=>input.shift();
  const intShift = ()=>~~input.shift();

  var ABC = [intShift(),intShift(),intShift()];
  var d = intShift();

  var max = ABC[0];
  var a = 0;
  for(var i = 1; i < 3; i++){
  	if(max < ABC[i]){
    	max = ABC[i];
      a = i;
    }
  }
  for(var i = 0 ; i < d; i++){
  	ABC[a] *= 2;
  }

  return ~~ABC.reduce((a,b)=>a+b);
}

// If you are interested in the algorithms I used,
// there is no need to read down from this line.

((b,c,d)=>"undefined"!=typeof require?console.log(Main(require("fs").readFileSync("/dev/stdin","utf8"))):[b=b.split("\n").slice(1,-1).join("\n"),c=function(){try{return Main(b)}catch(f){return f.stack||f.message}}(),d=typeof c,"string"==d||(c=JSON.stringify(c)),$("<form>").append([[10,b],0,[1,d],0,[10,c]].map(f=>$(f?"<textarea>":"<br>",f&&{rows:f[0],cols:40,text:f[1]}))).appendTo("body")])(`
5 3 11
1
`);

Score: 200 points

Problem Statement

There are three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times:

Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n.

What is the largest possible sum of the integers written on the blackboard after K operations?

Constraints

A, B and C are integers between 1 and 50 (inclusive).

K is an integer between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

A B C
K

Output

Print the largest possible sum of the integers written on the blackboard after K operations by E869220.

Sample Input 1

5 3 11
1

Sample Output 1

30

In this sample, 5, 3, 11 are initially written on the blackboard, and E869120 can perform the operation once.

There are three choices:

Double 5: The integers written on the board after the operation are 10, 3, 11.

Double 3: The integers written on the board after the operation are 5, 6, 11.

Double 11: The integers written on the board after the operation are 5, 3, 22.

If he chooses 3., the sum of the integers written on the board afterwards is 5 + 3 + 22 = 30, which is the largest among 1. through 3.

Sample Input 2

3 3 4
2

Sample Output 2

22

E869120 can perform the operation twice. The sum of the integers eventually written on the blackboard is maximized as follows:

First, double 4. The integers written on the board are now 3, 3, 8.

Next, double 8. The integers written on the board are now 3, 3, 16.

Then, the sum of the integers eventually written on the blackboard is 3 + 3 + 16 = 22.


'use strict'

function main(s) {

  s = s.split('\n');
  const h = Number(s[0].split(' ')[0]);
  const w = Number(s[0].split(' ')[0]);
  const table = s.slice(1, -1).map(x => x.split(''));

  let ans = 'Yes';
  for (let i = 0; i < h; i++) {
    for (let j = 0; j < w; j++) {
      if (table[i][j] === '.') continue;

      let count = 0;
      if (i - 1 >= 0) {
        if (table[i - 1][j] === '#') count += 1;
      }
      if (i + 1 < h) {
        if (table[i + 1][j] === '#') count += 1;
      }
      if (j + 1 < w) {
        if (table[i][j + 1] === '#') count += 1;
      }
      if (j - 1 >= 0) {
        if (table[i][j - 1] === '#') count += 1;
      }

      if (count === 0) ans = 'No';
    }
  }

  console.log(ans);
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score: 300 points

Problem Statement

We have a canvas divided into a grid with H rows and W columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j).

Initially, all the squares are white. square1001 wants to draw a picture with black paint. His specific objective is to make Square (i, j) black when s_{i, j}= #, and to make Square (i, j) white when s_{i, j}= ..

However, since he is not a good painter, he can only choose two squares that are horizontally or vertically adjacent and paint those squares black, for some number of times (possibly zero). He may choose squares that are already painted black, in which case the color of those squares remain black.

Determine if square1001 can achieve his objective.

Constraints

H is an integer between 1 and 50 (inclusive).

W is an integer between 1 and 50 (inclusive).

For every (i, j) (1 \leq i \leq H, 1 \leq j \leq W), s_{i, j} is # or ..

Input

Input is given from Standard Input in the following format:

H W
s_{1, 1} s_{1, 2} s_{1, 3} ... s_{1, W}
s_{2, 1} s_{2, 2} s_{2, 3} ... s_{2, W}
: :
s_{H, 1} s_{H, 2} s_{H, 3} ... s_{H, W}

Output

If square1001 can achieve his objective, print Yes; if he cannot, print No.

Sample Input 1

3 3
.#.
###
.#.

Sample Output 1

Yes

One possible way to achieve the objective is shown in the figure below. Here, the squares being painted are marked by stars.

Sample Input 2

5 5
#.#.#
.#.#.
#.#.#
.#.#.
#.#.#

Sample Output 2

No

square1001 cannot achieve his objective here.

Sample Input 3

11 11
...#####...
.##.....##.
#..##.##..#
#..##.##..#
#.........#
#...###...#
.#########.
.#.#.#.#.#.
##.#.#.#.##
..##.#.##..
.##..#..##.

Sample Output 3

Yes


"use strict";
function Main(input) {
    let lines = input.split("\n");
    const N = lines.shift().split(/\s/).map((v) => v - 0)[0];
    const a = lines.shift().split(/\s/).map((v) => v - 0);

    // 累積和と連想配列
    let s = new Array(N+1).fill(0);
    let nums = {};
    for (let i = 0; i < N; ++i) s[i+1] = s[i] + a[i];
    for (let i = 0; i < N+1; ++i) {
        let num = nums[s[i]] || 0;
        nums[s[i]] = ++num;
    }

    // 集計処理
    let res = 0;
    for (let it in nums) {
        let num = nums[it];
        res += (num * (num - 1) / 2);
    }
    console.log(res);

}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 200 points

Problem Statement

We have an integer sequence A, whose length is N.

Find the number of the non-empty contiguous subsequences of A whose sums are 0.
Note that we are counting the ways to take out subsequences.
That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from different positions.

Constraints

1 \leq N \leq 2 \times 10^5

-10^9 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Find the number of the non-empty contiguous subsequences of A whose sum is 0.

Sample Input 1

6
1 3 -4 2 2 -2

Sample Output 1

3

There are three contiguous subsequences whose sums are 0: (1,3,-4), (-4,2,2) and (2,-2).

Sample Input 2

7
1 -1 1 -1 1 -1 1

Sample Output 2

12

In this case, some subsequences that have the same contents but are taken from different positions are counted individually.
For example, three occurrences of (1, -1) are counted.

Sample Input 3

5
1 -2 3 -4 5

Sample Output 3

0

There are no contiguous subsequences whose sums are 0.


var q = require("fs").readFileSync("/dev/stdin", "utf8").split(/\s+/).filter(x => x.length);
q.shift();
var a = q.map(x => +x);
var r = [];
// imos' method
for (var i = 1, l = a.length; i < l; i++)
    a[i] += a[i-1];
a.unshift(0);
// registration
for (var i = a.length; i--;)
    r[a[i]] = (r[a[i]] || 0) + 1;
// counting
var sum = 0;
var keys = Object.keys(r);
for (var i = keys.length; i--;)
    sum += r[key] * (r[key] - 1) / 2;
console.log(sum);


function main(input){
  input = input.split('');
  var egg = input[0];
  var meat = input[1];
  var veg = input[2];
  var ndl = 700;
  if(egg === 'o'){
    ndl += 100
  }
  if(meat === 'o'){
    ndl += 100
  }
  if(veg === 'o'){
    ndl += 100
  }
  console.log(ndl);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs 700 yen (the currency of Japan), plus 100 yen for each kind of topping (boiled egg, sliced pork, green onions).

A customer ordered a bowl of ramen and told which toppings to put on his ramen to a clerk. The clerk took a memo of the order as a string S. S is three characters long, and if the first character in S is o, it means the ramen should be topped with boiled egg; if that character is x, it means the ramen should not be topped with boiled egg. Similarly, the second and third characters in S mean the presence or absence of sliced pork and green onions on top of the ramen.

Write a program that, when S is given, prints the price of the corresponding bowl of ramen.

Constraints

S is a string of length 3.

Each character in S is o or x.

Input

Input is given from Standard Input in the following format:

S

Output

Print the price of the bowl of ramen corresponding to S.

Sample Input 1

oxo

Sample Output 1

900

The price of a ramen topped with two kinds of toppings, boiled egg and green onions, is 700 + 100 \times 2 = 900 yen.

Sample Input 2

ooo

Sample Output 2

1000

The price of a ramen topped with all three kinds of toppings is 700 + 100 \times 3 = 1000 yen.

Sample Input 3

xxx

Sample Output 3

700

The price of a ramen without any toppings is 700 yen.


function Main(s) {
  s = s.match(/o/g)||[];
  console.log(700 + s.length * 100);
}
Main(require("fs").readFileSync("/dev/stdin","utf8"));


// https://atcoder.jp/contests/abc095/tasks/abc095_b
"use strict"
function Main(input) {
  const params = input.split('\n');
  const N = Number(params[0].split(' ')[0]);
  const X = Number(params[0].split(' ')[1]);
  const donuts = params.slice(1, -1).map(Number).sort();
  const total = donuts.reduce((acc, cur) => acc + cur);
  console.log(N + Math.floor((X - total) / donuts[0]));
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 200 points

Problem Statement

Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as 0.5 doughnuts.

Now, she has X grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition:

For each of the N kinds of doughnuts, make at least one doughnut of that kind.

At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto. Also, under the constraints of this problem, it is always possible to obey the condition.

Constraints

2 ≤ N ≤ 100

1 ≤ m_i ≤ 1000

m_1 + m_2 + ... + m_N ≤ X ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
m_1
m_2
:
m_N

Output

Print the maximum number of doughnuts that can be made under the condition.

Sample Input 1

3 1000
120
100
140

Sample Output 1

9

She has 1000 grams of Moto and can make three kinds of doughnuts. If she makes one doughnut for each of the three kinds, she consumes 120 + 100 + 140 = 360 grams of Moto. From the 640 grams of Moto that remains here, she can make additional six Doughnuts 2. This is how she can made a total of nine doughnuts, which is the maximum.

Sample Input 2

4 360
90
90
90
90

Sample Output 2

4

Making one doughnut for each of the four kinds consumes all of her Moto.

Sample Input 3

5 3000
150
130
150
130
110

Sample Output 3

26


function main (input) {
	var input = input.split('\n');
    var input1 = input[0].split(' ');
    N = input1[0];
	var X = parseInt(input1[1], 10);
    var m =[];
	for (var i = 0; i < input.length - 1; i++) {
	    m.push(parseInt(input[i + 1], 10));
	}
	var count = N;
	var min = Math.min.apply(null, m);

    while (X >= min) {
		X = X - min;
		count++
    };
  console.log(count);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(lines) {
    const input = lines.split(' ').map(Number)
    const A = input[0]
    const B = input[1]
    const C = input[2]
    const X = input[3]
    const Y = input[4]

    let output = []
    for(let i=0; i<=Math.pow(10,5);i++){
        let cost = 2*C*i + A*Math.max(X-i,0) + B*Math.max(Y-i,0)
        output.push(cost)
    }
    console.log(output.sort(function(a,b){return a-b;})[0])
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 300 points

Problem Statement

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare X A-pizzas and Y B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

1 ≤ A, B, C ≤ 5000

1 ≤ X, Y ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

Print the minimum amount of money required to prepare X A-pizzas and Y B-pizzas.

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

It is optimal to buy four AB-pizzas and rearrange them into two A-pizzas and two B-pizzas, then buy additional one A-pizza.

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

It is optimal to directly buy three A-pizzas and two B-pizzas.

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

It is optimal to buy 200000 AB-pizzas and rearrange them into 100000 A-pizzas and 100000 B-pizzas. We will have 10000 more A-pizzas than necessary, but that is fine.


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0].split(" ")[0]);
  var C = parseInt(input[0].split(" ")[1]);
  x= new Array(N);
  v= new Array(N);
  var half=0;
  for(i=0;i<N;i++){
    tmp=input[i+1].split(" ");
    x[i]=parseInt(tmp[0]);
    if(x[i]<C/2){
      half=i;
    }
    v[i]=parseInt(tmp[1]);
  }
  var ans=0;
  var sum=0;
  for(i=0;i<N;i++){
    if(i==0){
    sum=sum+v[i]-x[i];
    }else{
      sum=sum+v[i]-(x[i]-x[i-1]);

    }
    ans=Math.max(ans,sum);
  }
  for(i=half;i>=0;i--){
    sum=0;
    for(j=0;j<=i;j++){
      if(j==0){
      sum=sum+v[j]-x[j];
      }else{
        sum=sum+v[j]-(x[j]-x[j-1]);

      }
      ans=Math.max(ans,sum);
    }
    sum=sum-x[i];
    for(j=N-1;j>i;j--){
      if(j==N-1){
        sum=sum-(C-x[j])+v[j]
      }else{
        sum=sum-(x[j+1]-x[j])+v[j];

      }
      ans=Math.max(ans,sum);
    }
  }
  for(i=half+1;i<N;i++){
    sum=0;
    for(j=N-1;j>=i;j--){
      if(j==N-1){
      sum=sum+v[j]-(C-x[j]);
      }else{
        sum=sum-(x[j+1]-x[j])+v[j];

      }
      ans=Math.max(ans,sum);
    }
    sum=sum-(C-x[i]);
    for(j=0;j<i;j++){
      if(j==0){
        sum=sum+v[j]-x[j];
      }else{
        sum=sum+v[j]-(x[j]-x[j-1]);

      }
      ans=Math.max(ans,sum);
    }
  }

  console.log('%s', ans);
}

// "実行する"ボタンを押した時に実行される関数 (デバッグ用)
function debug(){
  var input = document.getElementById("input").value;
  Main(input);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 500 points

Problem Statement

"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.

Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories.

Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.

Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.

Constraints

1 ≤ N ≤ 10^5

2 ≤ C ≤ 10^{14}

1 ≤ x_1 < x_2 < ... < x_N < C

1 ≤ v_i ≤ 10^9

All values in input are integers.

Subscores

300 points will be awarded for passing the test set satisfying N ≤ 100.

Input

Input is given from Standard Input in the following format:

N C
x_1 v_1
x_2 v_2
:
x_N v_N

Output

If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c.

Sample Input 1

3 20
2 80
9 120
16 1

Sample Output 1

191

There are three sushi on the counter with a circumference of 20 meters. If he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks seven more meters clockwise, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 9 kilocalories, thus he can take in 191 kilocalories on balance, which is the largest possible value.

Sample Input 2

3 20
2 80
9 1
16 120

Sample Output 2

192

The second and third sushi have been swapped. Again, if he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks six more meters counterclockwise this time, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 8 kilocalories, thus he can take in 192 kilocalories on balance, which is the largest possible value.

Sample Input 3

1 100000000000000
50000000000000 1

Sample Output 3

0

Even though the only sushi is so far that it does not fit into a 32-bit integer, its nutritive value is low, thus he should immediately leave without doing anything.

Sample Input 4

15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000

Sample Output 4

6500000000

All these sample inputs above are included in the test set for the partial score.


function Main(input) {
  var mas = input[0].split(" ");
  var N = perseInt(mas[0]);
  var M = perseInt(mas[1]);
  var X = perseInt(mas[2]);
  var a = input[1];
  var A = a.split(" ");
  var L = null;
  var H = null;
  var num = null;
  var result = null;
  for (var i = 0; i < M; i++) {
    if (X > a[i]) {
      L.push(a[i] + ' ');
    } else {
      H.push(a[i] + ' ');
    }
  }
  if (H.length > L.length) {
    result = L.length;
  } else {
    result = H.length;
  }
  console.log(result);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 200 points

Problem Statement

There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right.

Initially, you are in Square X.
You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N.
However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1.
It is guaranteed that there is no toll gate in Square 0, Square X and Square N.

Find the minimum cost incurred before reaching the goal.

Constraints

1 \leq N \leq 100

1 \leq M \leq 100

1 \leq X \leq N - 1

1 \leq A_1 < A_2 < ... < A_M \leq N

A_i \neq X

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M X
A_1 A_2 ... A_M

Output

Print the minimum cost incurred before reaching the goal.

Sample Input 1

5 3 3
1 2 4

Sample Output 1

1

The optimal solution is as follows:

First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.

Then, travel from Square 4 to Square 5. This time, no cost is incurred.

Now, we are in Square 5 and we have reached the goal.

In this case, the total cost incurred is 1.

Sample Input 2

7 3 2
4 5 6

Sample Output 2

0

We may be able to reach the goal at no cost.

Sample Input 3

10 7 5
1 2 3 4 6 8 9

Sample Output 3

3


// inputに入力データ全体が入る
function Main(input) {
	var line = input.split("\n");
	var N = Number(line[0]);
	var X = line[1].split(" ");

	var Y = [];

	for(var i = 0; i < X.length; i++){
		Y[i] = Number(X[i]);
	}

	Y.sort(function(a, b){
		if(a < b) return -1;
		else return 1;
	});

	var median = [Y[(N/2 - 1)], Y[N/2]];
	var ret = [];

	for(var i = 0; i < X.length; i++){
		if(median[0] <= Number(X[i])) ret.push(median[0]);
		else ret.push(median[1]);
	}

	console.log(ret.join("\n"));

}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

When l is an odd number, the median of l numbers a_1, a_2, ..., a_l is the (\frac{l+1}{2})-th largest value among a_1, a_2, ..., a_l.

You are given N numbers X_1, X_2, ..., X_N, where N is an even number.
For each i = 1, 2, ..., N, let the median of X_1, X_2, ..., X_N excluding X_i, that is, the median of X_1, X_2, ..., X_{i-1}, X_{i+1}, ..., X_N be B_i.

Find B_i for each i = 1, 2, ..., N.

Constraints

2 \leq N \leq 200000

N is even.

1 \leq X_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 X_2 ... X_N

Output

Print N lines.
The i-th line should contain B_i.

Sample Input 1

4
2 4 4 3

Sample Output 1

4
3
3
4

Since the median of X_2, X_3, X_4 is 4, B_1 = 4.

Since the median of X_1, X_3, X_4 is 3, B_2 = 3.

Since the median of X_1, X_2, X_4 is 3, B_3 = 3.

Since the median of X_1, X_2, X_3 is 4, B_4 = 4.

Sample Input 2

2
1 2

Sample Output 2

2
1

Sample Input 3

6
5 5 4 4 3 3

Sample Output 3

4
4
4
4
4
4


function Main(input){
  input=input.trim().split(/\s+/).map(x=>x-0);
  var N=input.shift();
  var n=Math.max.apply(null,input);
  var r=input[input.map(x=>Math.abs(x-n/2)).indexOf(Math.min.apply(null,input.map(x=>Math.abs(x-n/2))))];
  console.log(n+' '+r);
}

Main(require('fs').readFileSync('/dev/stdin','utf8'));

Score : 400 points

Problem Statement

Let {\rm comb}(n,r) be the number of ways to choose r objects from among n objects, disregarding order.
From n non-negative integers a_1, a_2, ..., a_n, select two numbers a_i > a_j so that {\rm comb}(a_i,a_j) is maximized.
If there are multiple pairs that maximize the value, any of them is accepted.

Constraints

2 \leq n \leq 10^5

0 \leq a_i \leq 10^9

a_1,a_2,...,a_n are pairwise distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print a_i and a_j that you selected, with a space in between.

Sample Input 1

5
6 9 4 2 11

Sample Output 1

11 6

\rm{comb}(a_i,a_j) for each possible selection is as follows:

\rm{comb}(4,2)=6

\rm{comb}(6,2)=15

\rm{comb}(6,4)=15

\rm{comb}(9,2)=36

\rm{comb}(9,4)=126

\rm{comb}(9,6)=84

\rm{comb}(11,2)=55

\rm{comb}(11,4)=330

\rm{comb}(11,6)=462

\rm{comb}(11,9)=55

Thus, we should print 11 and 6.

Sample Input 2

2
100 0

Sample Output 2

100 0


function Main(s) {
  s = s.split("\n");
  var a = s[1].split(" ").map(a => +a);
  const n = +s[0];
  var m = Math.max(...a);
  var b = [...a].sort((a,b)=> a-b);
  var c = 9e9;
  for(var i = 0; i < n - 1; i++){
    if(Math.abs(m / 2 - b[i]) < c)c = Math.abs(m / 2 - b[i]);
    else break;
  }
  console.log("%d %d", m, b[i-1]);
}
Main(require("fs").readFileSync("/dev/stdin","utf8"));


inp = require('fs').readFileSync('/dev/stdin', 'utf8').split('\n')
s = inp.shift()
o = {a: 0, b: 0, c: 0}
f = true
for (i=0; i<s.length; i++) {
    o[s[i]] += 1
    if (o[s[i]] > 1) {
        f = false
        break;
    }
}
console.log(f ? 'Yes' : 'No')

Score : 100 points

Problem Statement

You are given a string S of length 3 consisting of a, b and c. Determine if S can be obtained by permuting abc.

Constraints

|S|=3

S consists of a, b and c.

Input

Input is given from Standard Input in the following format:

S

Output

If S can be obtained by permuting abc, print Yes; otherwise, print No.

Sample Input 1

bac

Sample Output 1

Yes

Swapping the first and second characters in bac results in abc.

Sample Input 2

bab

Sample Output 2

No

Sample Input 3

abc

Sample Output 3

Yes

Sample Input 4

aaa

Sample Output 4

No


// inputに入力データ全体が入る
function Main(input) {
	// input に a,b,c がそれぞれ１つ存在すること
    array=input.split("");
    console.log(array.sort().toString());
    if(array.sort().toString() =='a,b,c'){
      console.log("Yes");
    }else{
      console.log("No");
    }

}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


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

function Main(input) {
  input = myconv(input,4);
  var A = input[0];
  var B = input[1];
  var K = input[2];
  var alist = [];
  var blist = [];
  for(var i = A; i < A+K; i++){
    if(i > B){break;}
    alist.push(i);
  }
  for(var i = B; i > B-K; i--){
    if(i < A){break;}
    blist.push(i);
  }
  blist.sort(function(a,b){return a-b;});
  alist = alist.concat(blist);
  alist = Array.from(new Set(alist));
  myout(alist.join("\n"));
}

Main(myin());

Score : 200 points

Problem Statement

Print all the integers that satisfies the following in ascending order:

Among the integers between A and B (inclusive), it is either within the K smallest integers or within the K largest integers.

Constraints

1 \leq A \leq B \leq 10^9

1 \leq K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print all the integers that satisfies the condition above in ascending order.

Sample Input 1

3 8 2

Sample Output 1

3
4
7
8

3 is the first smallest integer among the integers between 3 and 8.

4 is the second smallest integer among the integers between 3 and 8.

7 is the second largest integer among the integers between 3 and 8.

8 is the first largest integer among the integers between 3 and 8.

Sample Input 2

4 8 3

Sample Output 2

4
5
6
7
8

Sample Input 3

2 9 100

Sample Output 3

2
3
4
5
6
7
8
9


"use strict";
function Main(input) {
    let cin = new Inputer(input);
    let X = cin.getIntArray(3);
    const div2 = (a) => Math.floor(a / 2);
    let ans = 0;
    while (!X.every(v=>v==X[2])) {
        X.sort((a, b) => a - b);
        let bc = X[2] - X[1];
        if (bc > 0) {
            X[0] += bc;
            X[1] += bc;
            ans += bc;
        }
        let ac = X[2] - X[0];
        if (ac > 0) {
            let a = Math.ceil(ac / 2);
            X[0] += a * 2;
            ans += a;
        }
    }
    console.log(ans);
}
class Inputer{constructor(t){if(typeof t=='undefined')throw new Error('引数（stdin）を省略できません！');this.cnt=0,this.items=t.split(/\n|\s/)}getInt(){return this.items[this.cnt++]-0}getIntArray(t){if(typeof t=='undefined')throw new Error('引数（1以上）を省略できません！');let r=new Array(t);for(let e=0;e<t;e++)r[e]=this.getInt();return r}getStr(){return this.items[this.cnt++]}getStrArray(t){if(typeof t=='undefined')throw new Error('引数（1以上）を省略できません！');let r=new Array(t);for(let e=0;e<t;e++)r[e]=this.getStr();return r}}
if (typeof window == "undefined") Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

You are given three integers A, B and C. Find the minimum number of operations required to make A, B and C all equal by repeatedly performing the following two kinds of operations in any order:

Choose two among A, B and C, then increase both by 1.

Choose one among A, B and C, then increase it by 2.

It can be proved that we can always make A, B and C all equal by repeatedly performing these operations.

Constraints

0 \leq A,B,C \leq 50

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the minimum number of operations required to make A, B and C all equal.

Sample Input 1

2 5 4

Sample Output 1

2

We can make A, B and C all equal by the following operations:

Increase A and C by 1. Now, A, B, C are 3, 5, 5, respectively.

Increase A by 2. Now, A, B, C are 5, 5, 5, respectively.

Sample Input 2

2 6 3

Sample Output 2

5

Sample Input 3

31 41 5

Sample Output 3

23


'use strict'

function main(s) {

  s = s.split('\n')[0].split(' ').map(n => Number(n));
  const A = s[0];
  const B = s[1];
  const C = s[2];

  const abc_sum = A + B + C;
  let same_sum = Math.max(...[A, B, C]) * 3;

  if (abc_sum % 2 !== same_sum % 2) same_sum += 3;

  const answer = (same_sum - abc_sum) / 2;
  console.log(answer);
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict'

class Main {
  solve() {
    const n = input.nextInt();
    const ab = input.nextIntRange(n);
    if (ab.every(e=>e[0]==e[1])) return 0;
    return _.sum(ab.map((e)=>((e[0]<=e[1]?e[0]:0) * 2 + Math.abs(e[0]-e[1])))) / 2;
  }
}

class Mod {
  constructor(mod) {
    if (mod == null) { mod = Combinatorics.DefaultMod; }
    this.mod = mod;
  }
  mult(a,b) {
    let ret = 0;
    a %= this.mod;
    b %= this.mod;
    while (b) {
      if (b&1) {
        ret += a;
        if (ret > this.mod) { ret -= this.mod; }
      }
      a <<= 1;
      if (a > this.mod) { a -= this.mod; }
      b >>= 1;
    }
    return ret;
  }
  pow(a,b) {
    let ret = 1;
    while(b) {
      if (b&1) { ret = this.mult(ret,a); }
      a = this.mult(a,a);
      b >>= 1;
    }
    return ret;
  }
  div(a,b) { return this.mult(a, this.pow(b, this.mod-2)) }
  comb(n,k) { return MOD.mult(factTable[n],MOD.mult(invFactTable[k],invFactTable[n-k])); }
}
const MOD = new Mod(1e9+7);

class Underscore {
  sum(arr) { return arr.reduce((a,b)=>a+b); }
  modSum(arr,mod) { if (mod == null) { mod = MOD.mod; } return arr.reduce((a,b)=>(a+b)%mod); }
  min(arr, func) { if (func == null) {func = (a,b) => a - b} return arr.reduce((a,b) => func(a,b) < 0 ? a : b); }
  max(arr, func) { if (func == null) {func = (a,b) => a - b} return arr.reduce((a,b) => func(a,b) > 0 ? a : b); }
  sort(arr, func) { if (func == null) {func = (a,b) => a - b} return arr.sort(func) }
  uniq(arr) {
    arr.sort();
    for(let i = 0; i < arr.length - 1; ++i) {
      arr[i] = arr[i+1] == arr[i] ? null : arr[i];
    }
    return arr.filter(e => e != null);
  }
  range(start, stop, step) {
    if (stop == null) { stop = start || 0; start = 0; }
    if (!step) { step = stop < start ? -1 : 1; }
    const length = Math.max(Math.ceil((stop - start) / step), 0);
    const range = Array(length);
    for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; }
    return range;
  }
  first (array, n) {
    if (array == null || array.length < 1) return n == null ? void 0 : [];
    if (n == null) return array[0];
    return this.initial(array, array.length - n);
  };
  initial (array, n) { return array.slice.call(array, 0, Math.max(0, array.length - (n == null ? 1 : n))); }
  tail(array, n) { return array.slice.call(array, n == null ? 1 : n); }
  last (array, n) { if (n == null) return array[array.length - 1]; return this.tail(array, Math.max(0, array.length - n)); }
  sumArray (arr) { return this.tail(arr.reduce(((a,b,i) => {a.push(b + a[i]); return a}), [0])); }
  diffArray (arr) { const s = []; for (let i = 1; i < arr.length; ++i) { s.push(arr[i] - arr[i-1]); } return s; }
  // 配列の値以下の最大のindex
  binarySearch (array, key, iteratee) {
    const itr = (obj) => (typeof obj === 'object') ? obj[iteratee] : obj;
    const value = itr(key);
    let low = 0, high = array.length;
    while (low < high) {
      let mid = Math.floor((low + high) / 2);
      if (itr(array[mid]) < value) low = mid + 1; else high = mid;
    }
    return low;
  };
}
const _ = new Underscore();

class Input {
  constructor() {
    this.cursor = 0;
    this.inputAll();
  }

  inputAll() {
    this.data = (require("fs").readFileSync("/dev/stdin", "utf8")).split('\n');
    return this.data;
  }

  /* 1行 or 複数行文字列 */
  nextLine(n) {
    if (n) {
      const ret = this.data.slice(this.cursor, this.cursor + n);
      this.cursor += n;
      return ret;
    }
    return this.data[this.cursor++];
  }
  /* 1整数 */
  nextInt() { return parseInt(this.nextLine()); }
  /* 一行文字配列 */
  nextStrArr() { return this.nextLine().split(' '); }
  /* 一行整数配列 */
  nextIntArr() { return this.nextStrArr().map((e) => parseInt(e)); }
  /* 一行浮動小数点配列 */
  nextFloatArr() { return this.nextStrArr().map((e) => parseFloat(e)); }
  /* 複数行整数配列 */
  nextIntLine(n) { return this.nextLine(n).map((e) => parseInt(e)) }
  /* 複数行浮動小数点配列 */
  nextFloatLine(n) { return this.nextLine(n).map((e) => parseFloat(e)) }
  /* 複数行文字列二次元配列 */
  nextStrRange(n) { return this.nextLine(n).map((line) => line.split(' ')); }
  /* 複数行整数二次元配列 */
  nextIntRange(n) {
    return this.nextLine(n).map((line) => line.split(' ').map((e) => parseInt(e)));
  }
  /* 複数行浮動小数点数二次元配列 */
  nextFloatRange(n) {
    return this.nextLine(n).map((line) => line.split(' ').map((e) => parseFloat(e)));
  }
}
const input = new Input();

class Out {
  constructor() {
    this.option = {
      'true': 'Yes',
      'false': 'No',
    };
  }
  write(output){
    let ret;
    if (output == null) return;
    if (output === true) { ret = this.option['true']; }
    else if (output === false) { ret = this.option['false']; }
    else { ret = output; }
    console.log(ret);
  }
  bool(option) {
    this.option['false'] = option[0];
    this.option['true'] = option[1];
    return this;
  }
}
const out = new Out();

out.write(new Main().solve());

Score : 700 points

Problem Statement

You are given sequences A and B consisting of non-negative integers.
The lengths of both A and B are N, and the sums of the elements in A and B are equal.
The i-th element in A is A_i, and the i-th element in B is B_i.

Tozan and Gezan repeats the following sequence of operations:

If A and B are equal sequences, terminate the process.

Otherwise, first Tozan chooses a positive element in A and decrease it by 1.

Then, Gezan chooses a positive element in B and decrease it by 1.

Then, give one candy to Takahashi, their pet.

Tozan wants the number of candies given to Takahashi until the process is terminated to be as large as possible, while Gezan wants it to be as small as possible.
Find the number of candies given to Takahashi when both of them perform the operations optimally.

Constraints

1 \leq N \leq 2 × 10^5

0 \leq A_i,B_i \leq 10^9(1\leq i\leq N)

The sums of the elements in A and B are equal.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the number of candies given to Takahashi when both Tozan and Gezan perform the operations optimally.

Sample Input 1

2
1 2
3 2

Sample Output 1

2

When both Tozan and Gezan perform the operations optimally, the process will proceed as follows:

Tozan decreases A_1 by 1.

Gezan decreases B_1 by 1.

One candy is given to Takahashi.

Tozan decreases A_2 by 1.

Gezan decreases B_1 by 1.

One candy is given to Takahashi.

As A and B are equal, the process is terminated.

Sample Input 2

3
8 3
0 1
4 8

Sample Output 2

9

Sample Input 3

1
1 1

Sample Output 3

0


//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n↑入力 ↓出力');
  Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
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';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//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 map = {};
  var aused = new Set();
  var bused = new Set();
  var alist = new Array(N);//red
  var blist = new Array(N);//blue
  for(var i = 0; i < N; i++){
    var tmp = nextIntArray();
    alist[i] = {
      no : i,
      child : [],
      x : tmp[0],
      y : tmp[1]
    };
  }
  for(var i = 0; i < N; i++){
    var tmp = nextIntArray();
    blist[i] = {
      no : i,
      child : [],
      x : tmp[0],
      y : tmp[1]
    };
  }
  for(var i = 0; i < N; i++){
    for(var j = 0; j < N; j++){
      if(alist[j].x < blist[i].x && alist[j].y < blist[i].y){
        blist[i].child.push(j);
      }
    }
    blist[i].child.sort(function(a,b){
    	return alist[b].y - alist[a].y;
    });
  }
  blist.sort(function(a, b){
  	return a.x - b.x;
  });
  //myerr(blist);
  //return;

  for(var i = 0; i < N; i++){
    var child = blist[i].child;
    for(var j = 0; j < child.length; j++){
      if(!aused.has(child[j])){
        aused.add(child[j]);
        break;
      }
    }
  }

  myout(aused.size);
}

Score : 400 points

Problem Statement

On a two-dimensional plane, there are N red points and N blue points.
The coordinates of the i-th red point are (a_i, b_i), and the coordinates of the i-th blue point are (c_i, d_i).

A red point and a blue point can form a friendly pair when, the x-coordinate of the red point is smaller than that of the blue point, and the y-coordinate of the red point is also smaller than that of the blue point.

At most how many friendly pairs can you form? Note that a point cannot belong to multiple pairs.

Constraints

All input values are integers.

1 \leq N \leq 100

0 \leq a_i, b_i, c_i, d_i < 2N

a_1, a_2, ..., a_N, c_1, c_2, ..., c_N are all different.

b_1, b_2, ..., b_N, d_1, d_2, ..., d_N are all different.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N

Output

Print the maximum number of friendly pairs.

Sample Input 1

3
2 0
3 1
1 3
4 2
0 4
5 5

Sample Output 1

2

For example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).

Sample Input 2

3
0 0
1 1
5 2
2 3
3 4
4 5

Sample Output 2

2

For example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).

Sample Input 3

2
2 2
3 3
0 0
1 1

Sample Output 3

0

It is possible that no pair can be formed.

Sample Input 4

5
0 0
7 3
2 2
4 8
1 6
8 5
6 9
5 4
9 1
3 7

Sample Output 4

5

Sample Input 5

5
0 0
1 1
5 5
6 6
7 7
2 2
3 3
4 4
8 8
9 9

Sample Output 5

4


inp = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n')
l = inp.shift().split(' ')
A = l[0] - 0
B = l[1] - 0
cnt = 0
for (i=A; i<=B; i++) {
    s = i+''
    if (s[0] == s[4] && s[1] == s[3]) {
        cnt++
    }
}
console.log(cnt)

Score : 200 points

Problem Statement

Find the number of palindromic numbers among the integers between A and B (inclusive).
Here, a palindromic number is a positive integer whose string representation in base 10 (without leading zeros) reads the same forward and backward.

Constraints

10000 \leq A \leq B \leq 99999

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the number of palindromic numbers among the integers between A and B (inclusive).

Sample Input 1

11009 11332

Sample Output 1

4

There are four integers that satisfy the conditions: 11011, 11111, 11211 and 11311.

Sample Input 2

31415 92653

Sample Output 2

612


function Main(input){
  var tmp = input.split(' ');
  var count = 0;
  for(var i=Number(tmp[0]);i<=Number(tmp[1]);i++){
    count += check(i);
  }
  function check(num){
    var str = String(num);
    var cut = str.substr(Math.ceil(str.length/2)).split('').reverse().join('');
    for(var i=0;i<cut.length;i++){
      if(str[i]!=cut[i]){
        return 0;
      }
    }
    return 1;
  }
  console.log(count);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


// inputに入力データ全体が入る
function Main(input) {
	var line = input.split("\n");
	var tmp = line[0].split(" ");
	var N = Number(tmp[0]);
	var M = Number(tmp[1]);
	var ans = Math.abs((M-2)*(N-2));
	if(ans > 1000000000000000){
		var Ntop = Math.floor(N/1000);
		var Nbottom = N%1000;
		var ansbottom = Nbottom*Math.abs(M-2);
		var ans = (Ntop*Math.abs(M-2) + Math.floor(ansbottom/1000)) + "";
		ans += ansbottom%1000 + "";
		ans = Number(ans);
	}
	console.log(ans);
}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

There is a grid with infinitely many rows and columns. In this grid, there is a rectangular region with consecutive N rows and M columns, and a card is placed in each square in this region.
The front and back sides of these cards can be distinguished, and initially every card faces up.

We will perform the following operation once for each square contains a card:

For each of the following nine squares, flip the card in it if it exists: the target square itself and the eight squares that shares a corner or a side with the target square.

It can be proved that, whether each card faces up or down after all the operations does not depend on the order the operations are performed.
Find the number of cards that face down after all the operations.

Constraints

1 \leq N,M \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of cards that face down after all the operations.

Sample Input 1

2 2

Sample Output 1

0

We will flip every card in any of the four operations. Thus, after all the operations, all cards face up.

Sample Input 2

1 7

Sample Output 2

5

After all the operations, all cards except at both ends face down.

Sample Input 3

314 1592

Sample Output 3

496080


console.log((args=>{
  const [N,M] = args.trim().split(' ').map(v=>v-2);
  return `${Math.abs(N*M)}`
})(require('fs').readFileSync('/dev/stdin', 'utf8')));


function main( input ) {
    const [N, A] = input.split('\n');
    if( N % 500 - A > 0 ) {
        console.log('No');
    } else {
        console.log('Yes');
    }
}

main( require('fs').readFileSync('/dev/stdin', 'utf8') );

Score: 100 points

Problem Statement

E869120 has A 1-yen coins and infinitely many 500-yen coins.

Determine if he can pay exactly N yen using only these coins.

Constraints

N is an integer between 1 and 10000 (inclusive).

A is an integer between 0 and 1000 (inclusive).

Input

Input is given from Standard Input in the following format:

N
A

Output

If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print Yes; otherwise, print No.

Sample Input 1

2018
218

Sample Output 1

Yes

We can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer is Yes.

Sample Input 2

2763
0

Sample Output 2

No

When we have no 1-yen coins, we can only pay a multiple of 500 yen using only 500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.

Sample Input 3

37
514

Sample Output 3

Yes


function Main(inp) {
    var input = inp.split("\n").map(function(n) { return Number(n);});
    var n = input[0];
    var a = input[1];
    if (Math.floor(n / 500) <= a) {
        console.log('Yes');
        return;
    }
    console.log('No');
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
    const args = input.split('\r\n');
    const n = parseInt(args[0], 10);
    const a = parseInt(args[1], 10);

    if (n % 500 <= a) {
        console.log('Yes');
    }
        console.log('No');
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input){
    const args = input.split('\n');
    const N = parseInt(args[0],10),
        cards = args[1].split(' ').map(n => parseInt(n, 10));

    var aSum = 0,
        bSum = 0;

    cards.sort((a, b)=> (a < b ? 1 : -1)).foreach((n, i)=> {
        (i % 2 === 0)? aSum += n: bSum += n;
    });

    console.log(aSum - bSum);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score: 200 points

Problem Statement

We have N cards. A number a_i is written on the i-th card.

Alice and Bob will play a game using these cards. In this game, Alice and Bob alternately take one card. Alice goes first.

The game ends when all the cards are taken by the two players, and the score of each player is the sum of the numbers written on the cards he/she has taken. When both players take the optimal strategy to maximize their scores, find Alice's score minus Bob's score.

Constraints

N is an integer between 1 and 100 (inclusive).

a_i \ (1 \leq i \leq N) is an integer between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print Alice's score minus Bob's score when both players take the optimal strategy to maximize their scores.

Sample Input 1

2
3 1

Sample Output 1

2

First, Alice will take the card with 3. Then, Bob will take the card with 1.
The difference of their scores will be 3 - 1 = 2.

Sample Input 2

3
2 7 4

Sample Output 2

5

First, Alice will take the card with 7. Then, Bob will take the card with 4. Lastly, Alice will take the card with 2. The difference of their scores will be 7 - 4 + 2 = 5. The difference of their scores will be 3 - 1 = 2.

Sample Input 3

4
20 18 2 18

Sample Output 3

18


function main(input){
    const args = input.split("\n");
    const N = parseInt(args[0],10),
        cards = args[1].split(" ").map(n => parseInt(n, 10));

    var aSum = 0,
        bSum = 0;

    cards.sort((a, b)=> b - a).foreach((n, i)=> {
        (i % 2 === 0)? aSum += n: bSum += n;
    });

    console.log(aSum - bSum);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main (input) {
    var N = input.split('\n')[0];
    var card = (input.split('\n')[1].split(' ')).sort();
    card = card.map(function(e){return Number(e);});
    var a = 0;
    var b = 0;
    for (var n = 0; n < N; n++) {
        if (n%2 === 0){
            a = a + card[card.length-1];
            card.pop();
        } else {
            b = b + card[card.length-1];
            card.pop();
        }
    }
    console.log(Math.abs(a-b));
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
  input = input.split("\n");
  var x = parseInt(input[0].split(" ")[0]);
  var y = parseInt(input[0].split(" ")[1]);
  var ans = -1;
  if(x%y!=0){
    for(i=x;i<=10**3;i+=x){
      if(i%y!=0){
        ans = i;
        break;
      }
    }
  }
  console.log('%s', ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

You are given positive integers X and Y.
If there exists a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, choose one such integer and print it.
If it does not exist, print -1.

Constraints

1 ≤ X,Y ≤ 10^9

X and Y are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, or print -1 if it does not exist.

Sample Input 1

8 6

Sample Output 1

16

For example, 16 is a multiple of 8 but not a multiple of 6.

Sample Input 2

3 3

Sample Output 2

-1

A multiple of 3 is a multiple of 3.