"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const N = ~~arg[0];
    const b = arg[1].split(" ").map(n=>~~n);

    let answer = [];

    for(let i in b) {
        if(i % 2 === 0) {
            answer.push(b[i]);
        } else {
            answer.unshift(b[i]);
        }
    }

    if(N % 2 !== 0) answer = answer.reverse();

    console.log(answer.join(""));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 300 points

Problem Statement

You are given an integer sequence of length n, a_1, ..., a_n.
Let us consider performing the following n operations on an empty sequence b.

The i-th operation is as follows:

Append a_i to the end of b.

Reverse the order of the elements in b.

Find the sequence b obtained after these n operations.

Constraints

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

0 \leq a_i \leq 10^9

n and a_i are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print n integers in a line with spaces in between.
The i-th integer should be b_i.

Sample Input 1

4
1 2 3 4

Sample Output 1

4 2 1 3

After step 1 of the first operation, b becomes: 1.

After step 2 of the first operation, b becomes: 1.

After step 1 of the second operation, b becomes: 1, 2.

After step 2 of the second operation, b becomes: 2, 1.

After step 1 of the third operation, b becomes: 2, 1, 3.

After step 2 of the third operation, b becomes: 3, 1, 2.

After step 1 of the fourth operation, b becomes: 3, 1, 2, 4.

After step 2 of the fourth operation, b becomes: 4, 2, 1, 3.

Thus, the answer is 4 2 1 3.

Sample Input 2

3
1 2 3

Sample Output 2

3 1 2

As shown above in Sample Output 1, b becomes 3, 1, 2 after step 2 of the third operation. Thus, the answer is 3 1 2.

Sample Input 3

1
1000000000

Sample Output 3

1000000000

Sample Input 4

6
0 6 7 6 7 0

Sample Output 4

0 6 6 0 7 7


"use strict";
const Main = (input) => {
	let xs = input.trim().split(' ').map(v=>parseInt(v,10));
  	if(xs[0] <= (xs[2] -xs[1])){
    console.log('dangerous');
    }else if(xs[0] > (xs[2] -xs[1]) && xs[1] >= xs[2]){
    console.log('delicious');
    }else if(xs[0] > (xs[2] -xs[1]) && xs[1] <= xs[2]){
    console.log('safe');
    }
}
Main(require('fs').readFileSync('/dev/stdin','utf8'));

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

Score : 100 points

Problem Statement

Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier.
He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though.

Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Otherwise, he does not find it delicious.

Takahashi bought some food A days before the "best-by" date, and ate it B days after he bought it.

Write a program that outputs delicious if he found it delicious, safe if he did not found it delicious but did not get a stomachache either, and dangerous if he got a stomachache.

Constraints

1 ≤ X,A,B ≤ 10^9

Input

Input is given from Standard Input in the following format:

X A B

Output

Print delicious if Takahashi found the food delicious; print safe if he neither found it delicious nor got a stomachache; print dangerous if he got a stomachache.

Sample Input 1

4 3 6

Sample Output 1

safe

He ate the food three days after the "best-by" date. It was not delicious or harmful for him.

Sample Input 2

6 5 1

Sample Output 2

delicious

He ate the food by the "best-by" date. It was delicious for him.

Sample Input 3

3 7 12

Sample Output 3

dangerous

He ate the food five days after the "best-by" date. It was harmful for him.

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.


    function main ( str ) {
      str = str.split(" ");
      var x= str[0];
      var a= str[1];
      var b= str[2];
      if( a>=b ) console.log("delicious");
      else if( b-a-1 < x ) console.log("safe");
      else console.log("dangerous");
    }


function main (s) {
    s=s.split(" ");
	for(var i=0;i<3;i++)s[i]=parseInt(s[i]);
	if(s[2]-s[1]<=0)console.log("delicious\n");
	else if(s[2]-s[1]<=s[0])console.log("safe\n");
	else console.log("dangerous\n");
}

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


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const M = parseInt(arg[0].split(" ")[1]);

    // 差が2以上あると交互に並べられない
    if(Math.abs(N - M) > 1) {
        console.log(0);
        return;
    }

    const MOD = 1e9 + 7;
    let answer = 1;

    for(let i=1; i<=N; i++) {
        answer = (answer % MOD) * (i % MOD);
    }

    for(let i=1; i<=M; i++) {
        answer = (answer % MOD) * (i % MOD);
    }

    /* -----------------------------------------------------
       差が1のときは、組み合わせが2通り 例：犬猿犬猿, 猿犬猿犬
       差が0のときは、組み合わせが1通り 例：犬猿犬猿犬
       それによって答えを2倍にするかどうか分ける
    --------------------------------------------------------*/
    console.log(answer * ((N == M) + 1) % MOD);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 300 points

Problem Statement

Snuke has N dogs and M monkeys. He wants them to line up in a row.

As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.

How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that).
Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Constraints

1 ≤ N,M ≤ 10^5

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of possible arrangements, modulo 10^9+7.

Sample Input 1

2 2

Sample Output 1

8

We will denote the dogs by A and B, and the monkeys by C and D. There are eight possible arrangements: ACBD, ADBC, BCAD, BDAC, CADB, CBDA, DACB and DBCA.

Sample Input 2

3 2

Sample Output 2

12

Sample Input 3

1 8

Sample Output 3

0

Sample Input 4

100000 100000

Sample Output 4

530123477


console.log((args=>{
  const [,g,b] = args.trim().split(' ');
  return ((2*g+b)%4)?'YES':'NO';
})(require('fs').readFileSync('/dev/stdin', 'utf8')));

Score : 100 points

Problem Statement

AtCoDeer has three cards, one red, one green and one blue.

An integer between 1 and 9 (inclusive) is written on each card: r on the red card, g on the green card and b on the blue card.

We will arrange the cards in the order red, green and blue from left to right, and read them as a three-digit integer.

Is this integer a multiple of 4?

Constraints

1 ≤ r, g, b ≤ 9

Input

Input is given from Standard Input in the following format:

r g b

Output

If the three-digit integer is a multiple of 4, print YES (case-sensitive); otherwise, print NO.

Sample Input 1

4 3 2

Sample Output 1

YES

432 is a multiple of 4, and thus YES should be printed.

Sample Input 2

2 3 4

Sample Output 2

NO

234 is not a multiple of 4, and thus NO should be printed.


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

function Main(input) {

	var text = input.split("\n")[1]

	var p = /\(([\[\]]*?)\)|([\[\]\)]*?)\)|\(([\[\]\(]*)/

	while( p.test(text) )
		text = text.replace(p, "[$1$2$3]")

	print(text.replace(/\[/g, "(").replace(/\]/g, ")"))

}


function main(input){
    input = input.split(" ");
    temp = parseInt(input[0] + input[1] + input[2], 10);
    if(temp % 4 === 0){
        console.log("YES")
    }else{
        console.log("NO")
    }
}

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(inputs) {
  var N = parseInt(inputs[0]);
  var vs = inputs[1].split(" ").map(function(a){return parseInt(a);});
  var max = 0;
  var min = 100000;
  for(var i in vs){
    max = Math.max(max, vs[i]);
    min = Math.min(min, vs[i]);
  }
  console.log(max - min);
}


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const A = arg[1].split(" ").map(n=>parseInt(n));

    let answer = 0;
    let free = 0;
    let colors = [0, 0, 0, 0, 0, 0, 0, 0];

    for(let i in A) {
        if(A[i] < 400) {
            colors[0]++;
        } else if(A[i] < 800) {
            colors[1]++;
        } else if(A[i] < 1200) {
            colors[2]++;
        } else if(A[i] < 1600) {
            colors[3]++;
        } else if(A[i] < 2000) {
            colors[4]++;
        } else if(A[i] < 2400) {
            colors[5]++;
        } else if(A[i] < 2800) {
            colors[6]++;
        } else if(A[i] < 3200) {
            colors[7]++;
        } else {
            free++;
        }
    }

    answer += colors.filter(n=>n !== 0).length;

    console.log(Math.max(1, answer) + " " + (answer + free));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 300 points

Problem Statement

In AtCoder, a person who has participated in a contest receives a color, which corresponds to the person's rating as follows:

Rating 1-399 : gray

Rating 400-799 : brown

Rating 800-1199 : green

Rating 1200-1599 : cyan

Rating 1600-1999 : blue

Rating 2000-2399 : yellow

Rating 2400-2799 : orange

Rating 2800-3199 : red

Other than the above, a person whose rating is 3200 or higher can freely pick his/her color, which can be one of the eight colors above or not.

Currently, there are N users who have participated in a contest in AtCoder, and the i-th user has a rating of a_i.

Find the minimum and maximum possible numbers of different colors of the users.

Constraints

1 ≤ N ≤ 100

1 ≤ a_i ≤ 4800

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum possible number of different colors of the users, and the maximum possible number of different colors, with a space in between.

Sample Input 1

4
2100 2500 2700 2700

Sample Output 1

2 2

The user with rating 2100 is "yellow", and the others are "orange". There are two different colors.

Sample Input 2

5
1100 1900 2800 3200 3200

Sample Output 2

3 5

The user with rating 1100 is "green", the user with rating 1900 is blue and the user with rating 2800 is "red".

If the fourth user picks "red", and the fifth user picks "blue", there are three different colors. This is one possible scenario for the minimum number of colors.

If the fourth user picks "purple", and the fifth user picks "black", there are five different colors. This is one possible scenario for the maximum number of colors.

Sample Input 3

20
800 810 820 830 840 850 860 870 880 890 900 910 920 930 940 950 960 970 980 990

Sample Output 3

1 1

All the users are "green", and thus there is one color.


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

function Main(input) {

	Array.zeros = (n) => { return Array.apply(null, Array(n)).map( ()=>0 ) }
	Array.prototype.max = function() { return Math.max.apply(null, this) }
	Array.prototype.min = function() { return Math.min.apply(null, this) }
	Array.prototype.non0length = function() { return this.reduce( (pre, current) => pre + (current != 0) ) }
	var num = (val) => Array.isArray(val) ? val.map( (v)=>Number(v) ) : Number(val)
	var print = console.log

	var line = input.split("\n")
	var n = num( line[0] )
	var a = num( line[1].split(" ") )

	var colors = 8
	var counter = Array.zeros(colors)
	var freecolor = 0

	for (var late of a) {
		if(late < 3200) {
			counter[~~(late/400)]++
		} else {
			freecolor++
		}
	}

	var non0 = counter.non0length()

	if( non0 + freecolor > colors )
		print( non0?non0:1, colors )
	else
		print( non0?non0:1, non0+freecolor )

}


function Main(input) {
	input = input.split("\n")[1].split(" ");
  var max, min;
  var count = [0, 0, 0, 0, 0, 0, 0, 0, 0];
  for (val in input) {
    var n = parseInt(input[val], 10);
    var q = Math.floor(n / 400);
    count[q]++;
  }
  var nonZero = 0;
  for (var i=0; i<8; i++) {
    if (count[i] != 0) nonZero++;
  }
  min = Math.min(nonZero, 1);
  max = nonZero + count[8];

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


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
        //console.log('%s',input);
	input = input.split("\n");
	tmp = input[1].split(" ");
	var max = [];
	for(var i=0;i < 9;i++){
		max[i] = 0;
	}
	for(var i=0;i < tmp.length ;i++){
		var a = parseInt(tmp[i], 10);
		if(0 <= a && a < 400)max[0] = 1;
		else if(400 <= a && a < 800)max[1] = 1;
		else if(800 <= a && a < 1200)max[2] = 1;
		else if(1200 <= a && a < 1600)max[3] = 1;
		else if(1600 <= a && a < 2000)max[4] = 1;
		else if(2000 <= a && a < 2400)max[5] = 1;
		else if(2400 <= a && a < 2800)max[6] = 1;
		else if(2800 <= a && a < 3200)max[7] = 1;
		else if(3200 <= a && a <= 4800)max[8] += 1;
	}
	var b = 0;
	for(var i=0;i < 8;i++){
		b += max[i];
	}
	/*maxを求める*/
	var ma = b + max[8];
	if(ma > 8)ma = 8;
	/*minを求める*/
	var mi = b;
	if(b == 0 && max[8] > 0){
		mi = 1;
	}
	//出力
	console.log('%d %d',ma,mi);
}

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


// inputに入力データ全体が入る
function Main(input) {

	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");

	line = input[0].split(" ");

	var r;

	r = line[0] + line[1]

	if(r >= 10)
	    r = "error"

	console.log(r);

}

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

Score : 100 points

Problem Statement

You are given two integers A and B as the input. Output the value of A + B.

However, if A + B is 10 or greater, output error instead.

Constraints

A and B are integers.

1 ≤ A, B ≤ 9

Input

Input is given from Standard Input in the following format:

A B

Output

If A + B is 10 or greater, print the string error (case-sensitive); otherwise, print the value of A + B.

Sample Input 1

6 3

Sample Output 1

9

Sample Input 2

6 4

Sample Output 2

error


function main (input) {
    const S = input.split('');
    var ans = 'yes';

    for (var i = 0; i < S.length; i++){
        for (var j = i+1; j < S.length -j; j++) {
            if (S[i] === S[j]) {
            ans = 'no';
            }
        }
    }
    console.log(ans);
}

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

Score : 200 points

Problem Statement

You are given a string S consisting of lowercase English letters. Determine whether all the characters in S are different.

Constraints

2 ≤ |S| ≤ 26, where |S| denotes the length of S.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If all the characters in S are different, print yes (case-sensitive); otherwise, print no.

Sample Input 1

uncopyrightable

Sample Output 1

yes

Sample Input 2

different

Sample Output 2

no

Sample Input 3

no

Sample Output 3

yes


function Main(input) {
  input = input.trim()
  input = input.split(" ");
  if(hoge(input[1])==hoge(input[0])){
  console.log("Yes")
  }else{
  console.log("No")
  }
}Main(require("fs").readFileSync("/dev/stdin", "utf8"));
function hoge(n){
if(n==1||n==3|n==5||n==7||n==8||n==10||n==12) return 1;
  else if(n==2) return 3;
  else return 2;
}

Score : 100 points

Problem Statement

Based on some criterion, Snuke divided the integers from 1 through 12 into three groups as shown in the figure below.
Given two integers x and y (1 ≤ x < y ≤ 12), determine whether they belong to the same group.

Constraints

x and y are integers.

1 ≤ x < y ≤ 12

Input

Input is given from Standard Input in the following format:

x y

Output

If x and y belong to the same group, print Yes; otherwise, print No.

Sample Input 1

1 3

Sample Output 1

Yes

Sample Input 2

2 4

Sample Output 2

No


'use strict';

const fs = require('fs');

const groups = [
  [1, 3, 5, 7, 8, 10, 12],
  [4, 6, 9, 11],
  [2],
];

const findGroupIndex = (n) => {
  for (let i = 0; i < 3; i++) {
    if (groups[i].indexOf(n) >= 0) {
      return i;
    }
  }
  return -1;
};

const input = fs.readFileSync('/dev/stdin', 'utf8')
  .split(' ')
  .map(n => parseInt(n, 10));

const x = input[0];
const y = input[1];
console.log(x, y);

console.log(findGroupIndex(x) === findGroupIndex(y) ? 'Yes' : 'No');


l=require('fs').readFileSync(0,'utf8').split('\n')
n=l[0].split(' ').map(n=>parseInt(n))
h=n[0]
w=n[1]
d='#'.repeat(w+2)
r=[d]
for(i=1;i<h+1;i++){r.push(`#${l[i]}#`)}
r.push(d)
console.log(r.join('\n'))

Score : 200 points

Problem Statement

You are given a image with a height of H pixels and a width of W pixels.
Each pixel is represented by a lowercase English letter.
The pixel at the i-th row from the top and j-th column from the left is a_{ij}.

Put a box around this image and output the result. The box should consist of # and have a thickness of 1.

Constraints

1 ≤ H, W ≤ 100

a_{ij} is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

H W
a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}

Output

Print the image surrounded by a box that consists of # and has a thickness of 1.

Sample Input 1

2 3
abc
arc

Sample Output 1

#####
#abc#
#arc#
#####

Sample Input 2

1 1
z

Sample Output 2

###
#z#
###


let [a, b, c] = require("fs").readFileSync("/dev/stdin", "utf8").split(" ").map(Number);
console.log(a <= c && c <= b ? "Yes" : "No");

Score : 100 points

Problem Statement

You are given three integers A, B and C.
Determine whether C is not less than A and not greater than B.

Constraints

-100≤A,B,C≤100

A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

If the condition is satisfied, print Yes; otherwise, print No.

Sample Input 1

1 3 2

Sample Output 1

Yes

C=2 is not less than A=1 and not greater than B=3, and thus the output should be Yes.

Sample Input 2

6 5 4

Sample Output 2

No

C=4 is less than A=6, and thus the output should be No.

Sample Input 3

2 2 2

Sample Output 3

Yes


'use strict'

const main = (input) => {
    input = input.split(' ').map(v => parseInt(v))
    const a = input[0]
    const b = input[1]
    const c = input[2]
    if(c >= a && c <= b){
        console.log('Yes')
    }else{
        console.log('No')
    }
}

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


function Main(input){
  var arr = input.split('\n');
  var NM = arr.shift().split(' ');
  var N = Number(NM[0]);
  var M = Number(NM[1]);
  arr.pop();
  arr.sort();

  var a = [];
  for(var i=0;i<arr.length;i++){
    if(isNaN(a[Number(arr[i].split(' ')[1])-1])){
      a[Number(arr[i].split(' ')[1])-1]=0;
    }
    if(isNaN(a[Number(arr[i].split(' ')[0])-1])){
      a[Number(arr[i].split(' ')[0])-1]=0;
    }
    ++a[Number(arr[i].split(' ')[0])-1];
    ++a[Number(arr[i].split(' ')[1])-1];
  }

  for(var i of a){
    if(isNaN(i)){
      console.log(0);
    }else{
      console.log(i);
    }
  }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 200 points

Problem Statement

There are N cities and M roads.
The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print the answer in N lines.
In the i-th line (1≤i≤N), print the number of roads connected to city i.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City 1 is connected to the 1-st and 3-rd roads.

City 2 is connected to the 1-st and 2-nd roads.

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

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

Sample Output 3

3
3
2
2
2
1
1
2


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	tmp = input[0].split(" ");
	//文字列から10進数に変換するときはparseIntを使います
	var N = parseInt(tmp[0], 10);
	var K = parseInt(tmp[1], 10);
	var A = [];
	var box = [];
	for (var i = 0; i < N; i++) {
		base = input[i+1].split(" ");
		//base1 = parseInt(base[0], 10);
		//base2 = parseInt(base[1], 10);
		for (var j = 0; j < parseInt(base[1]); j++) {
			box.push(parseInt(base[0]));
		}
	}
	console.log("%s",box[K-1]);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

There is an empty array.
The following N operations will be performed to insert integers into the array.
In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array.
Find the K-th smallest integer in the array after the N operations.
For example, the 4-th smallest integer in the array \{1,2,2,3,3,3\} is 3.

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

Print the K-th smallest integer in the array after the N operations.

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

The resulting array is the same as the one in the problem statement.

Sample Input 2

10 500000
1 100000
1 100000
1 100000
1 100000
1 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000

Sample Output 2

1


const main = input => {
  const [A, B, C] = input.trim().split(' ')
  if (A[A.length - 1] === B[0] && B[B.length - 1] === C[0]) {
    console.log('YES')
  } else {
    console.log('NO')
  }
}

// 標準入力
main(require("fs").readFileSync("/dev/stdin", "utf8"))

Score : 100 points

Problem Statement

You are given three strings A, B and C. Check whether they form a word chain.

More formally, determine whether both of the following are true:

The last character in A and the initial character in B are the same.

The last character in B and the initial character in C are the same.

If both are true, print YES. Otherwise, print NO.

Constraints

A, B and C are all composed of lowercase English letters (a - z).

1 ≤ |A|, |B|, |C| ≤ 10, where |A|, |B| and |C| are the lengths of A, B and C, respectively.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

rng gorilla apple

Sample Output 1

YES

They form a word chain.

Sample Input 2

yakiniku unagi sushi

Sample Output 2

NO

A and B form a word chain, but B and C do not.

Sample Input 3

a a a

Sample Output 3

YES

Sample Input 4

aaaaaaaaab aaaaaaaaaa aaaaaaaaab

Sample Output 4

NO


const main = stdin => {
  const input = stdin.trim().split('\n')
  const [A, B, C] = input[0].split(' ').map(x => parseInt(x))

  for (let i = A; i <= 10000; i += A) {
    if (i % B === C) {
      console.log('YES')
      return
    }
  }
  console.log('NO')
}

// 標準入力
main(require("fs").readFileSync("/dev/stdin", "utf8"))

Score : 200 points

Problem Statement

We ask you to select some number of positive integers, and calculate the sum of them.

It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.

Your objective is to make the sum congruent to C modulo B.
Determine whether this is possible.

If the objective is achievable, print YES. Otherwise, print NO.

Constraints

1 ≤ A ≤ 100

1 ≤ B ≤ 100

0 ≤ C < B

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 5.

Sample Input 2

2 2 1

Sample Output 2

NO

The sum of even numbers, no matter how many, is never odd.

Sample Input 3

1 100 97

Sample Output 3

YES

You can select 97, since you may select multiples of 1, that is, all integers.

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const A = parseInt(arg[0].split(" ")[0]);
    const B = parseInt(arg[0].split(" ")[1]);
    const C = parseInt(arg[0].split(" ")[2]);

    let answer = "NO";

    for(let i=0; i<B; i++) {
        let temp = (A * i) % B;
        // console.log((A * i) % B);

        if(temp === C) {
            answer = "YES";
            break;
        }
    }

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


"use strict";

// inputに入力データ全体が入る
function Main(input) {
  input = input.split(" ");
  var a = parseInt(input[0]);
  var b = parseInt(input[1]);
  var c = parseInt(input[2]);

  a = a % b;
  var flag = 0;
  for (var i=0; i<b; i++) {
    if (a*i%b===c) {
      flag = 1;
      break;
    }
  }
  if (flag === 1) {
    console.log("YES");
  } else {
    console.log("NO");
  }
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


Score : 300 points

Problem Statement

You are given an array A of length N.
Your task is to divide it into several contiguous subarrays.
Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order.
At least how many subarrays do you need to divide A into?

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Each A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible number of subarrays after division of A.

Sample Input 1

6
1 2 3 2 2 1

Sample Output 1

2

One optimal solution is to divide the array into [1,2,3] and [2,2,1].

Sample Input 2

9
1 2 1 2 1 2 1 2 1

Sample Output 2

5

Sample Input 3

7
1 2 3 2 1 999999999 1000000000

Sample Output 3

3


function Main(input) {
  input = input.trim()
  input = input.split(" ").map(Number);
if(input[1]-input[0]==input[2]-input[1]){
  console.log("YES");
}else{
  console.log("NO");
}}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

Three poles stand evenly spaced along a line. Their heights are a, b and c meters, from left to right.
We will call the arrangement of the poles beautiful if the tops of the poles lie on the same line, that is, b-a = c-b.

Determine whether the arrangement of the poles is beautiful.

Constraints

1 \leq a,b,c \leq 100

a, b and c are integers.

Input

Input is given from Standard Input in the following format:

a b c

Output

Print YES if the arrangement of the poles is beautiful; print NO otherwise.

Sample Input 1

2 4 6

Sample Output 1

YES

Since 4-2 = 6-4, this arrangement of poles is beautiful.

Sample Input 2

2 5 6

Sample Output 2

NO

Since 5-2 \neq 6-5, this arrangement of poles is not beautiful.

Sample Input 3

3 2 1

Sample Output 3

YES

Since 1-2 = 2-3, this arrangement of poles is beautiful.


function Main( input ){

    input = input.split( '\n' )

    var o = [].slice.call( input[0] )
    var e = [].slice.call( input[1] )

    var pass = ''

    for( ;o.length; ){
        pass += o.shift()
        pass += e.shift()
    }

    console.log( pass )

}

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

Score : 200 points

Problem Statement

Snuke signed up for a new website which holds programming competitions.
He worried that he might forget his password, and he took notes of it.
Since directly recording his password would cause him trouble if stolen,
he took two notes: one contains the characters at the odd-numbered positions, and the other contains the characters at the even-numbered positions.

You are given two strings O and E. O contains the characters at the odd-numbered positions retaining their relative order, and E contains the characters at the even-numbered positions retaining their relative order.
Restore the original password.

Constraints

O and E consists of lowercase English letters (a - z).

1 \leq |O|,|E| \leq 50

|O| - |E| is either 0 or 1.

Input

Input is given from Standard Input in the following format:

O
E

Output

Print the original password.

Sample Input 1

xyz
abc

Sample Output 1

xaybzc

The original password is xaybzc. Extracting the characters at the odd-numbered positions results in xyz, and extracting the characters at the even-numbered positions results in abc.

Sample Input 2

atcoderbeginnercontest
atcoderregularcontest

Sample Output 2

aattccooddeerrbreeggiunlnaerrccoonntteesstt


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const A = arg[1].split(" ").map(n=>parseInt(n)).sort((a,b)=>a-b);

    let teams = [];

    for(let i=0; i<N; i++) {
        teams.push([]);
    }

    let answer = 0;

    for(let i=0; i<3*N; i++) {
        const mod = i % N;

        // 2番目を選択する時
        if(i >= N && i <= N + (N - 1)) {
            if(A[i] < A[i+1]) {
                let temp = A[i];
                A[i] = A[i+1];
                A[i+1] = temp;

                teams[mod].push(A[i]);
            } else {
                teams[mod].push(A[i]);
            }
        } else {
            teams[mod].push(A[i]);
        }
    }

    for(let i=0; i<N; i++) {
        answer += teams[i][1];
    }

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

Score : 300 points

Problem Statement

There are 3N participants in AtCoder Group Contest.
The strength of the i-th participant is represented by an integer a_i.
They will form N teams, each consisting of three participants.
No participant may belong to multiple teams.

The strength of a team is defined as the second largest strength among its members.
For example, a team of participants of strength 1, 5, 2 has a strength 2, and a team of three participants of strength 3, 2, 3 has a strength 3.

Find the maximum possible sum of the strengths of N teams.

Constraints

1 ≤ N ≤ 10^5

1 ≤ a_i ≤ 10^{9}

a_i are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the answer.

Sample Input 1

2
5 2 8 5 1 5

Sample Output 1

10

The following is one formation of teams that maximizes the sum of the strengths of teams:

Team 1: consists of the first, fourth and fifth participants.

Team 2: consists of the second, third and sixth participants.

Sample Input 2

10
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 2

10000000000

The sum of the strengths can be quite large.


"use strict"
function Main(input) {
  input = input.trim().split('\n');
  const N = Number(input[0].trim());
  let A = input[1].trim().split(' ').map(Number).sort((a, b) => b-a);

  let ret = 0;
  for(let i=0; i<N*2; i++){
    if((i+1)%2===0){
      ret += A[i];
    }
  }

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


function Main(input) {
  var inputs = input.split("\n");
  var n = parseInt(inputs[0], 10);
  var a = inputs[1].split(" ").map(e => parseInt(e, 10)).sort((x, y) => y - x);
  var sum = 0;
  for (var i = 1; i < n * 3 - 1; i += 2) {
    sum += a[i];
  }
  console.log(sum);
}

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


var lines = [];
var readline = require('readline');
var C = [].fill(0);
var result = Infinity;

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

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

rl.on('close', function () {
    var N = Number(lines.shift()); var n = N;
    var counter = [].fill(0);

    for (var i = 2; i < Math.sqrt(N); i++) {
        if (counter[i] === undefined && n % i === 0) { counter[i] = 0; }
        while (n % i === 0) {
            n = n / i;
            counter[i]++;
        }
    }

    if (counter.length === 0) console.log(N.toString().length);
    else {

        counter.forEach(function (value, index, array) {
            for (var i = 0; i < value; i++) {
                C.push(index);
            }
        });
        if (n !== 1) C.push(n);
        dfs(0, []);
        console.log(result);
    }
});

function dfs(n, comb) {
    if (n === C.length) { calc(comb); return (0); }

    comb[n] = 0;
    dfs(n + 1, comb);

    comb[n] = 1;
    dfs(n + 1, comb);
}

function calc(comb) {
    var a = 1; var b = 1;

    for (var i = 0; i < comb.length; i++) {
        if (comb[i] === 0) { a *= C[i]; }
        else { b *= C[i]; }
    }
    if (result > b.toString().length && a.toString().length <= b.toString().length) { result = b.toString().length; }
}

Score : 300 points

Problem Statement

You are given an integer N.

For two positive integers A and B, we will define F(A,B) as the larger of the following: the number of digits in the decimal notation of A, and the number of digits in the decimal notation of B.

For example, F(3,11) = 2 since 3 has one digit and 11 has two digits.

Find the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Constraints

1 \leq N \leq 10^{10}

N is an integer.

Input

The input is given from Standard Input in the following format:

N

Output

Print the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Sample Input 1

10000

Sample Output 1

3

F(A,B) has a minimum value of 3 at (A,B)=(100,100).

Sample Input 2

1000003

Sample Output 2

7

There are two pairs (A,B) that satisfy the condition: (1,1000003) and (1000003,1). For these pairs, F(1,1000003)=F(1000003,1)=7.

Sample Input 3

9876543210

Sample Output 3

6


function main(input) {
const a = input.split(" ");
  console.log(a[0]=="H"?a[1]
             :a[1]=="D"?"H"
             :"D");
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest.
In this game, an honest player always tells the truth, and an dishonest player always tell lies.
You are given two characters a and b as the input. Each of them is either H or D, and carries the following information:

If a=H, AtCoDeer is honest; if a=D, AtCoDeer is dishonest.
If b=H, AtCoDeer is saying that TopCoDeer is honest; if b=D, AtCoDeer is saying that TopCoDeer is dishonest.

Given this information, determine whether TopCoDeer is honest.

Constraints

a=H or a=D.

b=H or b=D.

Input

The input is given from Standard Input in the following format:

a b

Output

If TopCoDeer is honest, print H. If he is dishonest, print D.

Sample Input 1

H H

Sample Output 1

H

In this input, AtCoDeer is honest. Hence, as he says, TopCoDeer is honest.

Sample Input 2

D H

Sample Output 2

D

In this input, AtCoDeer is dishonest. Hence, contrary to what he says, TopCoDeer is dishonest.

Sample Input 3

D D

Sample Output 3

H


function Main(input) {
	input = input.split(' ');
  const a = input[0];
  const b = input[1];

 if((a === 'H' && b === 'H') || (a === 'D' && b === 'D')) {
   console.log('H')
 } else {
   console.log('D')
 }
}

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


'use strict'

const main = input => {
	const args = input.trim().split(' ')
	if (args[0] === 'H' && args[1] === 'H') console.log('H')
	else if (args[0] === 'H' && args[1] === 'D') console.log('D')
	else if (args[0] === 'D' && args[1] === 'H') console.log('D')
	else console.log('H')
}

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


function Main(input) {
  input = input.split(" ");
  var a = input[0];
  var b = input[1];
  var s;
  if(a!="H"){
    if(b=="H"){
      s="D";
    }else{
      s="H";
    }
    s=b;
  }

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

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


function Main(input) {
  input = input.split(" ");
  var a = input[0];
  var b = input[1];
  if(a!="H"){
    if(b=="H"){
      b="D";
    }else{
      b="H";
    }
  }

  console.log('%s', b);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const main = input => {
  const [W, a, b] = input.trim().split(' ').map(x => parseInt(x))
  if (a > b) {
    console.log(Math.max(a - (b + W), 0))
  } else if (a < b) {
    console.log(Math.max(b - (a + W), 0))
  } else {
    console.log(0)
  }
}

// 標準入力
main(require("fs").readFileSync("/dev/stdin", "utf8"))

Score : 200 points

Problem Statement

AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W.
If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the horizontal range of [b,b+W], as shown in the following figure:

AtCoDeer will move the second rectangle horizontally so that it connects with the first rectangle.
Find the minimum distance it needs to be moved.

Constraints

All input values are integers.

1≤W≤10^5

1≤a,b≤10^5

Input

The input is given from Standard Input in the following format:

W a b

Output

Print the minimum distance the second rectangle needs to be moved.

Sample Input 1

3 2 6

Sample Output 1

1

This input corresponds to the figure in the statement. In this case, the second rectangle should be moved to the left by a distance of 1.

Sample Input 2

3 1 3

Sample Output 2

0

The rectangles are already connected, and thus no move is needed.

Sample Input 3

5 10 1

Sample Output 3

4


"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(a){return a?cin[cid++]:+cin[cid++];}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}

var myOut = main();
if(myOut !== undefined)console.log(myOut);

function main(){
  var n = next(), k = next();
  var a = [];
  for(var i = 0; i < n; i++){
    var t = next();
    if(t < k)a.push(t);
  }
  n = a.length;
  a.sort((a,b)=>b-a);
  var dp = xArray(0,k);
  dp[0] = 1;
  var q = -1;
  for(var i = 0; i < n; i++){
    var t = a[i];
    for(var j = k-t; j < k; j++){
      if(dp[j]){
        q = i;
        break;
      }
    }
    for(var j = k-t; j--;){
      dp[j+t] |= dp[j];
    }
  }
  return n-q-1;
}

Score : 600 points

Problem Statement

AtCoDeer the deer has N cards with positive integers written on them. The number on the i-th card (1≤i≤N) is a_i.
Because he loves big numbers, he calls a subset of the cards good when the sum of the numbers written on the cards in the subset, is K or greater.

Then, for each card i, he judges whether it is unnecessary or not, as follows:

If, for any good subset of the cards containing card i, the set that can be obtained by eliminating card i from the subset is also good, card i is unnecessary.

Otherwise, card i is NOT unnecessary.

Find the number of the unnecessary cards. Here, he judges each card independently, and he does not throw away cards that turn out to be unnecessary.

Constraints

All input values are integers.

1≤N≤5000

1≤K≤5000

1≤a_i≤10^9 (1≤i≤N)

Partial Score

300 points will be awarded for passing the test set satisfying N,K≤400.

Input

The input is given from Standard Input in the following format:

N K
a_1 a_2 ... a_N

Output

Print the number of the unnecessary cards.

Sample Input 1

3 6
1 4 3

Sample Output 1

1

There are two good sets: {2,3} and {1,2,3}.

Card 1 is only contained in {1,2,3}, and this set without card 1, {2,3}, is also good. Thus, card 1 is unnecessary.

For card 2, a good set {2,3} without card 2, {3}, is not good. Thus, card 2 is NOT unnecessary.

Neither is card 3 for a similar reason, hence the answer is 1.

Sample Input 2

5 400
3 1 4 1 5

Sample Output 2

5

In this case, there is no good set. Therefore, all the cards are unnecessary.

Sample Input 3

6 20
10 4 3 10 25 2

Sample Output 3

3


Score : 300 points

Problem Statement

Every day, N passengers arrive at Takahashi Airport.
The i-th passenger arrives at time T_i.

Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers.
Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport.
Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane.
For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).

When setting the departure times for buses under this condition, find the minimum required number of buses.
Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.

Constraints

2 \leq N \leq 100000

1 \leq C \leq 10^9

1 \leq K \leq 10^9

1 \leq T_i \leq 10^9

C, K and T_i are integers.

Input

The input is given from Standard Input in the following format:

N C K
T_1
T_2
:
T_N

Output

Print the minimum required number of buses.

Sample Input 1

5 3 5
1
2
3
6
12

Sample Output 1

3

For example, the following three buses are enough:

A bus departing at time 4.5, that carries the passengers arriving at time 2 and 3.

A bus departing at time 6, that carries the passengers arriving at time 1 and 6.

A bus departing at time 12, that carries the passenger arriving at time 12.

Sample Input 2

6 3 3
7
6
2
8
10
6

Sample Output 2

3


function Main(input) {
	input = parseInt(input.trim().split(" "));
  var x = 800 * input;
  var y = 200 * Math.floor(input / 15);
  console.log(x - y);
}

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

Score : 100 points

Problem Statement

Snuke has a favorite restaurant.

The price of any meal served at the restaurant is 800 yen (the currency of Japan), and each time a customer orders 15 meals, the restaurant pays 200 yen back to the customer.

So far, Snuke has ordered N meals at the restaurant.
Let the amount of money Snuke has paid to the restaurant be x yen, and let the amount of money the restaurant has paid back to Snuke be y yen.
Find x-y.

Constraints

1 ≤ N ≤ 100

Input

The input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

20

Sample Output 1

15800

So far, Snuke has paid 16000 yen, and the restaurant has paid back 200 yen. Thus, the answer is 15800.

Sample Input 2

60

Sample Output 2

47200

Snuke has paid 48000 yen for 60 meals, and the restaurant has paid back 800 yen.


'use strict'

function main(input) {
  input = Number(input)
  const divider = 1000000007

  let power = 1
  for (let i=1; i<=input; i++) {
    power = (power * i) % divider
  }

  console.log(power)
}

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

Score : 200 points

Problem Statement

Snuke loves working out. He is now exercising N times.

Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i.

Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7.

Constraints

1 ≤ N ≤ 10^{5}

Input

The input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^{9}+7.

Sample Input 1

3

Sample Output 1

6

After Snuke exercises for the first time, his power gets multiplied by 1 and becomes 1.

After Snuke exercises for the second time, his power gets multiplied by 2 and becomes 2.

After Snuke exercises for the third time, his power gets multiplied by 3 and becomes 6.

Sample Input 2

10

Sample Output 2

3628800

Sample Input 3

100000

Sample Output 3

457992974

Print the answer modulo 10^{9}+7.


'use strict'
const main = arg => {
	const input = arg.trim().split("\n");
	let N = input[0].split(' ')[0]
	function fact(n) {
		var result = 1;
		for (var i = 1; i <= n; i++) {
			result = result * i % 1000000007;
		}
		return result;
	}
	console.log(fact(N) % 1000000007)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict";

const main = arg => {
    const N = arg.split("\n")[0]*1;
    // 階乗を出す
  	let x = factorial(N)%1000000007;
  	console.log(x);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

function factorial(num) {
  if (num === 1) {
    return 1;
  } else {
    return num * factorial(num - 1);
  }
};


'use strict'

function main(arg) {
  arg = arg.split(' ');
  const a = arg[0];
  const b = arg[1];
  if (a == b) console.log('Drow');
  if (a < b) {
    if (a !== 1) {
      console.log('Bob');
    } else {
      console.log('Alice');
  } else {
    if (b !== 1) {
      console.log('Alice');
    } else {
      console.log('Bob');
    }
  }
}

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

Score : 100 points

Problem Statement

Alice and Bob are playing One Card Poker.

One Card Poker is a two-player game using playing cards.

Each card in this game shows an integer between 1 and 13, inclusive.

The strength of a card is determined by the number written on it, as follows:

Weak 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 < 10 < 11 < 12 < 13 < 1 Strong

One Card Poker is played as follows:

Each player picks one card from the deck. The chosen card becomes the player's hand.

The players reveal their hands to each other. The player with the stronger card wins the game.

If their cards are equally strong, the game is drawn.

You are watching Alice and Bob playing the game, and can see their hands.

The number written on Alice's card is A, and the number written on Bob's card is B.

Write a program to determine the outcome of the game.

Constraints

1≦A≦13

1≦B≦13

A and B are integers.

Input

The input is given from Standard Input in the following format:

A B

Output

Print Alice if Alice will win. Print Bob if Bob will win. Print Draw if the game will be drawn.

Sample Input 1

8 6

Sample Output 1

Alice

8 is written on Alice's card, and 6 is written on Bob's card.
Alice has the stronger card, and thus the output should be Alice.

Sample Input 2

1 1

Sample Output 2

Draw

Since their cards have the same number, the game will be drawn.

Sample Input 3

13 1

Sample Output 3

Bob


Score : 300 points

Problem Statement

You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

How many different paths start from vertex 1 and visit all the vertices exactly once?

Here, the endpoints of a path are considered visited.

For example, let us assume that the following undirected graph shown in Figure 1 is given.

Figure 1: an example of an undirected graph

The following path shown in Figure 2 satisfies the condition.

Figure 2: an example of a path that satisfies the condition

However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices.

Figure 3: an example of a path that does not satisfy the condition

Neither the following path shown in Figure 4, because it does not start from vertex 1.

Figure 4: another example of a path that does not satisfy the condition

Constraints

2≦N≦8

0≦M≦N(N-1)/2

1≦a_i<b_i≦N

The given graph contains neither self-loops nor double edges.

Input

The input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once.

Sample Input 1

3 3
1 2
1 3
2 3

Sample Output 1

2

The given graph is shown in the following figure:

The following two paths satisfy the condition:

Sample Input 2

7 7
1 3
2 7
3 4
4 5
4 6
5 6
6 7

Sample Output 2

1

This test case is the same as the one described in the problem statement.


'use strict';

function visitedAll(visited) {
  let flag = true;
  for (let vis of visited) {
    if (vis !== 1) {
      flag = false;
    }
  }
  return flag;
}

function dfs(v, N, graph, visited) {
  if (visitedAll(visited)) {
    count++;
  }

  for (let i = 0; i < N; i++) {
    if (graph[v][i] === 1 && visited[i] === 0) {
      visited[i] = 1;
      dfs(i, N, graph, visited);
      visited[i] = 0;
    }
  }

  return count;

}

function main(input) {
  const tmp = input.split('\n');
  const NM = tmp.shift().split(' ').map((elem) => parseInt(elem, 10));
  const N = NM[0];
  const M = NM[1];

  let graph = Array(N).fill(0).map((elem) => Array(N).fill(0));
  for (let line of tmp) {
    const splited = line.split(' ').map((elem) => parseInt(elem, 10));
    const a = splited[0];
    const b = splited[1];

    graph[a - 1][b - 1] = 1;
    graph[b - 1][a - 1] = 1;
  }
  let visited = Array(N).fill(0);
  visited[0] = 1;
  console.log(dfs(0, N, graph, visited));
}
let count = 0;
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


'use strict'
const main = arg => {
	const input = arg.trim().split("\n");
	let N = Number(input[0].split(' ')[0])
	console.log(N >= 1200 ? 'ARC' : 'ABC')
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than 1200, and participate in AtCoder Regular Contest (ARC) otherwise.

You are given Smeke's current rating, x. Print ABC if Smeke will participate in ABC, and print ARC otherwise.

Constraints

1 ≦ x ≦ 3{,}000

x is an integer.

Input

The input is given from Standard Input in the following format:

x

Output

Print the answer.

Sample Input 1

1000

Sample Output 1

ABC

Smeke's current rating is less than 1200, thus the output should be ABC.

Sample Input 2

2000

Sample Output 2

ARC

Smeke's current rating is not less than 1200, thus the output should be ARC.


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);

  	let temp = Math.floor(N / 11);
  	let rest = N % 11;

//   	console.log(temp)
//   	console.log(rest)
//     console.log(temp * 11)

//     console.log(temp * 2)

    console.log((temp * 2) + Math.ceil(rest / 6));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 300 points

Problem Statement

Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.

Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:

Operation: Rotate the die 90° toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain y points where y is the number written in the side facing upward.

For example, let us consider the situation where the side showing 1 faces upward, the near side shows 5 and the right side shows 4, as illustrated in the figure.
If the die is rotated toward the right as shown in the figure, the side showing 3 will face upward.
Besides, the side showing 4 will face upward if the die is rotated toward the left, the side showing 2 will face upward if the die is rotated toward the front, and the side showing 5 will face upward if the die is rotated toward the back.

Find the minimum number of operation Snuke needs to perform in order to score at least x points in total.

Constraints

1 ≦ x ≦ 10^{15}

x is an integer.

Input

The input is given from Standard Input in the following format:

x

Output

Print the answer.

Sample Input 1

7

Sample Output 1

2

Sample Input 2

149696127901

Sample Output 2

27217477801


"use strict";
const main = arg => {
  let info = arg.split("\n");
  let max = 0;
  let tmp = 0;
  for(let t of info[1]){
    if(t == "I"){
      tmp += 1;
    } else {
      tmp -= 1;
    }
    if(max < tmp){
    	max = tmp;
    }
  }

  console.log(max);
}

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

Score : 200 points

Problem Statement

You have an integer variable x.
Initially, x=0.

Some person gave you a string S of length N, and using the string you performed the following operation N times.
In the i-th operation, you incremented the value of x by 1 if S_i=I, and decremented the value of x by 1 if S_i=D.

Find the maximum value taken by x during the operations (including before the first operation, and after the last operation).

Constraints

1≤N≤100

|S|=N

No characters except I and D occur in S.

Input

The input is given from Standard Input in the following format:

N
S

Output

Print the maximum value taken by x during the operations.

Sample Input 1

5
IIDID

Sample Output 1

2

After each operation, the value of x becomes 1, 2, 1, 2 and 1, respectively. Thus, the output should be 2, the maximum value.

Sample Input 2

7
DDIDDII

Sample Output 2

0

The initial value x=0 is the maximum value taken by x, thus the output should be 0.


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	//array = input[1].split(" ");
    array = input[1];

    var x = 0;
    var max = 0;
    for(var i=0; i < parseInt(input[0]); i++){
        if ("I" == array.charAt(i)) {
            x++;
            if(x > max) max = x;
        }else{
            x--;
        }
    }

	//出力
	console.log(max);

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


var input = require('fs').readFileSync('/dev/stdin', 'utf8').split("\n");
var n = Number(input[0]);
var ans = 0;
var tmp = 0;
var tx = input[1].split("");
for(var i in tx){
    if(tx[i] == 'I'){
        tmp++;
    }else{
        tmp--;
    }
    ans = Math.max(ans,tmp);
}
console.log(ans);


"use strict";
// inputに入力データ全体が入る
const main = (input) => {
  //分割代入,1行目がq,2行目がb,3行目がcに代入される
  const [a, b, c] = input.trim().split(",");
  console.log(a + " " + b + " " + c);
};

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

Score : 100 points

Problem Statement

As a New Year's gift, Dolphin received a string s of length 19.

The string s has the following format: [five lowercase English letters],[seven lowercase English letters],[five lowercase English letters].

Dolphin wants to convert the comma-separated string s into a space-separated string.

Write a program to perform the conversion for him.

Constraints

The length of s is 19.

The sixth and fourteenth characters in s are ,.

The other characters in s are lowercase English letters.

Input

The input is given from Standard Input in the following format:

s

Output

Print the string after the conversion.

Sample Input 1

happy,newyear,enjoy

Sample Output 1

happy newyear enjoy

Replace all the commas in happy,newyear,enjoy with spaces to obtain happy newyear enjoy.

Sample Input 2

haiku,atcoder,tasks

Sample Output 2

haiku atcoder tasks

Sample Input 3

abcde,fghihgf,edcba

Sample Output 3

abcde fghihgf edcba


function Main(input) {
	input = input.replace(/,/g ," ");
        console.log(input);
}

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


function main(input) {
  input = input.trim();
  const a = input.split(' ').map(Number);

  if(a[1]=='+'){
    console.log(parseInt(a[0])+parseInt(a[2]))
  }else if(a[1]=='-'){
    console.log(parseInt(a[0])-parseInt(a[2]))
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

Joisino wants to evaluate the formula "A op B".
Here, A and B are integers, and the binary operator op is either + or -.
Your task is to evaluate the formula instead of her.

Constraints

1≦A,B≦10^9

op is either + or -.

Input

The input is given from Standard Input in the following format:

A op B

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

Since 1 + 2 = 3, the output should be 3.

Sample Input 2

5 - 7

Sample Output 2

-2


let [a, op, b] = require("fs").readFileSync("/dev/stdin", "utf8").split(" ");
[a, b] = [a, b].map(Number);
console.log(op == "+" ? a + b : a - b);


function Main(input) {
 	input = input.trim()
	const a = parseInt(input.split('')[0],10);
	const op = input.split('')[1];
 	const b = parseInt(input.split('')[2],10);
	if (op == '+') {
      console.log(a + b);
    }
 	if (op == '-') {
      console.log(a - b);
    }
}

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


function main(input) {
  input = input.trim();
  const a = input.split(' ');
  if(a[0]=='a'||a[0]=='i'||a[0]=='u'||a[0]=='e'||a[0]=='o'){
    console.log('vowel');
  }else{
    console.log('consonant');
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

Given a lowercase English letter c, determine whether it is a vowel. Here, there are five vowels in the English alphabet: a, e, i, o and u.

Constraints

c is a lowercase English letter.

Input

The input is given from Standard Input in the following format:

c

Output

If c is a vowel, print vowel. Otherwise, print consonant.

Sample Input 1

a

Sample Output 1

vowel

Since a is a vowel, print vowel.

Sample Input 2

z

Sample Output 2

consonant

Sample Input 3

s

Sample Output 3

consonant


'use strict'

const main = input => {
	const c = input.trim()
	if (c === 'a') console.log('vowel')
	else if (c === 'e') console.log('vowel')
	else if (c === 'i') console.log('vowel')
	else if (c === 'o') console.log('vowel')
	else if (c === 'u') console.log('vowel')
	else console.log('consonant')
}

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


'use strict'
const main = arg => {
	const input = arg.trim().split("\n");
	let a = input[0].split(' ').map(n => BigInt(n))[0]
	let b = input[0].split(' ').map(num => BigInt(num))[1]
	let x = input[0].split(' ').map(num => BigInt(num))[2]
	let left = b / x * x / x
	let right = (divCeil(a, x) * x) / x
	if(a <= x) {
		console.log((b / x).toString())
		return
	}
	console.log( (left - right + BigInt(1)).toString())

	function divCeil (a, x) {
		if((a % x) * BigInt(2) >= x) {
			return a / x + BigInt(1)
		}
		return a / x
	}
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 200 points

Problem Statement

You are given nonnegative integers a and b (a ≤ b), and a positive integer x.
Among the integers between a and b, inclusive, how many are divisible by x?

Constraints

0 ≤ a ≤ b ≤ 10^{18}

1 ≤ x ≤ 10^{18}

Input

The input is given from Standard Input in the following format:

a b x

Output

Print the number of the integers between a and b, inclusive, that are divisible by x.

Sample Input 1

4 8 2

Sample Output 1

3

There are three integers between 4 and 8, inclusive, that are divisible by 2: 4, 6 and 8.

Sample Input 2

0 5 1

Sample Output 2

6

There are six integers between 0 and 5, inclusive, that are divisible by 1: 0, 1, 2, 3, 4 and 5.

Sample Input 3

9 9 2

Sample Output 3

0

There are no integer between 9 and 9, inclusive, that is divisible by 2.

Sample Input 4

1 1000000000000000000 3

Sample Output 4

333333333333333333

Watch out for integer overflows.


function myout(text){console.log(text);}//standard output
function Main(input) {
	input = parseInt(input);
	//input = input.split(" ");
	//input = input.split("\n");
	//input = input.split(" ").map((a)=>Number(a));
	//input = input.split("\n").map((a)=>Number(a));
  var list = [];
  var output = 0;
  for(var i = 1; i <= input; i++){
    output += i;
    list.push(i);
    if(output == input){
       myout(list.join("\n"));
      return;
    }else if(output > input){
      var diff = output - input;
      list.splice(list.indexOf(diff),1);
      myout(list.join("\n"));
      return;
    }
  }
}

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

Score : 300 points

Problem Statement

The problem set at CODE FESTIVAL 20XX Finals consists of N problems.

The score allocated to the i-th (1≦i≦N) problem is i points.

Takahashi, a contestant, is trying to score exactly N points. For that, he is deciding which problems to solve.

As problems with higher scores are harder, he wants to minimize the highest score of a problem among the ones solved by him.

Determine the set of problems that should be solved.

Constraints

1≦N≦10^7

Partial Score

200 points will be awarded for passing the test set satisfying 1≦N≦1000.

Additional 100 points will be awarded for passing the test set without additional constraints.

Input

The input is given from Standard Input in the following format:

N

Output

Among the sets of problems with the total score of N, find a set in which the highest score of a problem is minimum, then print the indices of the problems in the set in any order, one per line.

If there exists more than one such set, any of them will be accepted.

Sample Input 1

4

Sample Output 1

1
3

Solving only the 4-th problem will also result in the total score of 4 points, but solving the 1-st and 3-rd problems will lower the highest score of a solved problem.

Sample Input 2

7

Sample Output 2

1
2
4

The set \{3,4\} will also be accepted.

Sample Input 3

1

Sample Output 3

1


'use strict'

const main = arg => {
  arg = arg.trim().split("\n");

  const w = ~~(arg[0].split(" ")[0]);
  const h = ~~(arg[0].split(" ")[1]);
  const n = ~~(arg[0].split(" ")[2]);

  const points = arg.slice(1, n + 1).map(l => l.split(" ").map(n => ~~n));
  const list = [...Array(h)].map(l => [...Array(w)].fill(0));

  for(const point of points) {
    const x = point[0];
    const y = point[1];
    const a = point[2] - 1;

    const fromH = [0, 0, 0, y];
    const toH   = [h, h, y, h];
    const fromW = [0, x, 0, 0];
    const toW   = [x, w, w, w];

    for(let i = fromH[a]; i < toH[a]; i++) {
      for(let j = fromW[a]; j < toW[a]; j++) {
        list[i][j] = 1;
      }
    }
  }

  let cnt = 0;

  for(let i = 0; i < h; i++) {
    for(let j = 0; j < w; j++) {
      if(list[i][j] === 0) cnt++;
    }
  }

  console.log(cnt);
}

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

Score : 200 points

Problem Statement

There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white.

Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) point was (x_i, y_i).

Then, he created an integer sequence a of length N, and for each 1 ≦ i ≦ N, he painted some region within the rectangle black, as follows:

If a_i = 1, he painted the region satisfying x < x_i within the rectangle.

If a_i = 2, he painted the region satisfying x > x_i within the rectangle.

If a_i = 3, he painted the region satisfying y < y_i within the rectangle.

If a_i = 4, he painted the region satisfying y > y_i within the rectangle.

Find the area of the white region within the rectangle after he finished painting.

Constraints

1 ≦ W, H ≦ 100

1 ≦ N ≦ 100

0 ≦ x_i ≦ W (1 ≦ i ≦ N)

0 ≦ y_i ≦ H (1 ≦ i ≦ N)

W, H (21:32, added), x_i and y_i are integers.

a_i (1 ≦ i ≦ N) is 1, 2, 3 or 4.

Input

The input is given from Standard Input in the following format:

W H N
x_1 y_1 a_1
x_2 y_2 a_2
:
x_N y_N a_N

Output

Print the area of the white region within the rectangle after Snuke finished painting.

Sample Input 1

5 4 2
2 1 1
3 3 4

Sample Output 1

9

The figure below shows the rectangle before Snuke starts painting.

First, as (x_1, y_1) = (2, 1) and a_1 = 1, he paints the region satisfying x < 2 within the rectangle:

Then, as (x_2, y_2) = (3, 3) and a_2 = 4, he paints the region satisfying y > 3 within the rectangle:

Now, the area of the white region within the rectangle is 9.

Sample Input 2

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

Sample Output 2

0

It is possible that the whole region within the rectangle is painted black.

Sample Input 3

10 10 5
1 6 1
4 1 3
6 9 4
9 4 2
3 1 3

Sample Output 3

64


// inputに入力データ全体が入る
function Main(input) {
var space_strinput = function(line){
	var arr= line.replace(/(^\s+)|(\s+$)/g, "").split(" ");
	for(var i=0;i<arr.length;++i){
		arr[i]=arr[i];
	}
	return arr;
};
var space_numinput = function(line){
	var arr= line.replace(/(^\s+)|(\s+$)/g, "").split(" ");
	for(var i=0;i<arr.length;++i){
		arr[i]=+arr[i];
	}
	return arr;
};

var getmin = function(a,b){return a>b?b:a;};
	lines = input.split("\n"); // 1行目がinput[0], 2行目がinput[1], …に入る
	var l0 = space_numinput(lines[0]);
	var n = l0[0];
	var t = l0[1];
	var a = space_numinput(lines[1]);
	var rieki = 0;
	var rieki_place_count = 0;
	var min = a[0];
	var max = a[0];
	for(var i=0;i<n;++i){
		var val = a[i];
		if(val-min>rieki){
			rieki=val-min;
			rieki_place_count = 1;
		}else if(val-min==rieki){
			rieki_place_count++;
		}

		min = val < min? val:min;
	}
	console.log(getmin(rieki_place_count,Math.floor(t/2)));
}

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

Score : 400 points

Problem Statement

There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.

Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:

Move: When at town i (i < N), move to town i + 1.

Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for A_i yen (the currency of Japan) at town i (1 ≦ i ≦ N), where A_i are distinct integers. Also, you can assume that he has an infinite supply of money.

For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most T. (Note that a single apple can be counted in both.)

During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel.

Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change A_i into another arbitrary non-negative integer A_i' for any town i, any number of times. The cost of performing this operation is |A_i - A_i'|. After performing this operation, different towns may have equal values of A_i.

Aoki's objective is to decrease Takahashi's expected profit by at least 1 yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least 1 yen.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

A_i are distinct.

2 ≦ T ≦ 10^9

In the initial state, Takahashi's expected profit is at least 1 yen.

Input

The input is given from Standard Input in the following format:

N T
A_1 A_2 ... A_N

Output

Print the minimum total cost to decrease Takahashi's expected profit by at least 1 yen.

Sample Input 1

3 2
100 50 200

Sample Output 1

1

In the initial state, Takahashi can achieve the maximum profit of 150 yen as follows:

Move from town 1 to town 2.

Buy one apple for 50 yen at town 2.

Move from town 2 to town 3.

Sell one apple for 200 yen at town 3.

If, for example, Aoki changes the price of an apple at town 2 from 50 yen to 51 yen, Takahashi will not be able to achieve the profit of 150 yen. The cost of performing this operation is 1, thus the answer is 1.

There are other ways to decrease Takahashi's expected profit, such as changing the price of an apple at town 3 from 200 yen to 199 yen.

Sample Input 2

5 8
50 30 40 10 20

Sample Output 2

2

Sample Input 3

10 100
7 10 4 5 9 3 6 8 2 1

Sample Output 3

2


"use strict";

const main = arg => {
    const colors = arg.split("\n")[0].split(" ");
    const set = new Set(colors);

    console.log(set.size);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c.
Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

1≦a,b,c≦100

Input

The input is given from Standard Input in the following format:

a b c

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: 1, 3, and 4.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: 3 and 33.


'use strict'

function Main(input) {
    const tmp = input.split('\n')[0].split(' ');
    const N = Number(tmp[0]);
    const K = Number(tmp[1]);
    console.log(N, K);

    let result = K;

    if (N === 1) {
        console.log(result);
        return;
    }

    for (let i = 0; i < (N - 1); i++) {
        result *= (K - 1);
    }
    console.log(result);
    return;

}

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

Score : 200 points

Problem Statement

There are N balls placed in a row.
AtCoDeer the deer is painting each of these in one of the K colors of his paint cans.
For aesthetic reasons, any two adjacent balls must be painted in different colors.

Find the number of the possible ways to paint the balls.

Constraints

1≦N≦1000

2≦K≦1000

The correct answer is at most 2^{31}-1.

Input

The input is given from Standard Input in the following format:

N K

Output

Print the number of the possible ways to paint the balls.

Sample Input 1

2 2

Sample Output 1

2

We will denote the colors by 0 and 1. There are two possible ways: we can either paint the left ball in color 0 and the right ball in color 1, or paint the left in color 1 and the right in color 0.

Sample Input 2

1 10

Sample Output 2

10

Since there is only one ball, we can use any of the ten colors to paint it. Thus, the answer is ten.


process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) {
    main(chunk.trim());
});

function main(chunk){
    var ans = chunk.length;

    var line = chunk.split("");

    var s_cnt = 0;
    for(var i in line){
        switch(line[i]){
        case 'S':
            s_cnt++;
            break;
        case 'T':
            if(s_cnt>0){
                s_cnt--;
                ans-=2;
            }
            break;
        }
    }
    console.log(ans);
}

Score : 300 points

Problem Statement

We have a string X, which has an even number of characters. Half the characters are S, and the other half are T.

Takahashi, who hates the string ST, will perform the following operation 10^{10000} times:

Among the occurrences of ST in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.

Find the eventual length of X.

Constraints

2 ≦ |X| ≦ 200,000

The length of X is even.

Half the characters in X are S, and the other half are T.

Partial Scores

In test cases worth 200 points, |X| ≦ 200.

Input

The input is given from Standard Input in the following format:

X

Output

Print the eventual length of X.

Sample Input 1

TSTTSS

Sample Output 1

4

In the 1-st operation, the 2-nd and 3-rd characters of TSTTSS are removed.
X becomes TTSS, and since it does not contain ST anymore, nothing is done in the remaining 10^{10000}-1 operations.
Thus, the answer is 4.

Sample Input 2

SSTTST

Sample Output 2

0

X will eventually become an empty string: SSTTST ⇒ STST ⇒ ST ⇒ ``.

Sample Input 3

TSSTTTSS

Sample Output 3

4

X will become: TSSTTTSS ⇒ TSTTSS ⇒ TTSS.


    'use strict'

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

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

    process.stdin.on('end', function() {
      const values = line.split(/\s+/)
      console.log(b(values.slice(1, values.length-1).map(x => parseInt(x))))
      process.exit(0)
    });

    function b(arr) {
  let total = 0
 let cache = new Array(arr.length)
 arr.reverse().forEach((num, index) => {
   let current = index - 1
   let cached = 0
   while (current !== -1) {
     if (arr[current] < num) {
       cached = cache[current]
       break;
     } else {
       current--
     }
   }
   const thisTotal = cached + num * (index - current)
   cache[index] = thisTotal
   total += thisTotal
 })
      return total
    }

Score : 400 points

Problem Statement

One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend.

Find the following:

Constraints

1 ≦ N ≦ 200,000

(a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N).

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the answer.

Note that the answer may not fit into a 32-bit integer.

Sample Input 1

3
2 1 3

Sample Output 1

9

Sample Input 2

4
1 3 2 4

Sample Output 2

19

Sample Input 3

8
5 4 8 1 2 6 7 3

Sample Output 3

85


// parameter "input" gets all data
function Main(input) {
	// the first line is assigned to input[0], the second line is assigned to input[1] similarly.

  var first_word = input.slice(0, 4);
  var second_word = input.slice(4);
	//output
	console.log(first_word + ' ' + second_word);
}
// Don't edit this line!
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

This contest is CODE FESTIVAL.
However, Mr. Takahashi always writes it CODEFESTIVAL, omitting the single space between CODE and FESTIVAL.

So he has decided to make a program that puts the single space he omitted.

You are given a string s with 12 letters.
Output the string putting a single space between the first 4 letters and last 8 letters in the string s.

Constraints

s contains exactly 12 letters.

All letters in s are uppercase English letters.

Input

The input is given from Standard Input in the following format:

s

Output

Print the string putting a single space between the first 4 letters and last 8 letters in the string s.
Put a line break at the end.

Sample Input 1

CODEFESTIVAL

Sample Output 1

CODE FESTIVAL

Putting a single space between the first 4 letters and last 8 letters in CODEFESTIVAL makes it CODE FESTIVAL.

Sample Input 2

POSTGRADUATE

Sample Output 2

POST GRADUATE

Sample Input 3

ABCDEFGHIJKL

Sample Output 3

ABCD EFGHIJKL


function Main(input) {
	var s = String(input);
	var s2 = s.slice(0, 4) + String(" ") + s.slice(-8);
	// s.splice(1, 4, " ");
	console.log('%s', s2);
}
// Don't edit this line!
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input){
 input = input.split("\n");
 if(input[0].length != 10){
  throw new Error("");
 }
 console.log(1);
}
main(require("fs").readFileSync("/dev/stdin"));

Score : 300 points

Problem Statement

You are given a string S consisting of digits between 1 and 9, inclusive.
You can insert the letter + into some of the positions (possibly none) between two letters in this string.
Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

1 \leq |S| \leq 10

All letters in S are digits between 1 and 9, inclusive.

Input

The input is given from Standard Input in the following format:

S

Output

Print the sum of the evaluated value over all possible formulas.

Sample Input 1

125

Sample Output 1

176

There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

125

1+25=26

12+5=17

1+2+5=8

Thus, the sum is 125+26+17+8=176.

Sample Input 2

9999999999

Sample Output 2

12656242944


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()){return "";}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 = new Array();
  var oddSet = new Set();
  var evenSet = new Set();
  for(var i = 0; i < N; i++){
    var tmp = nextInt();
    list[i] = tmp;
    if(i % 2 == 0){
      oddSet.add(tmp);
    }else{
      evenSet.add(tmp);
    }
  }
  list.sort(function(a,b){
  	return a - b;
  });
  var output = 0;
  for(var i = 0; i < N; i++){
    if(i % 2 == 0){
      if(!oddSet.has(list[i])){
        output++;
      }
    }else{
      if(!evenSet.has(list[i])){
        output++;
      }
    }
  }
  myout(output / 2);
}

Score : 600 points

Problem Statement

Snuke got an integer sequence of length N from his mother, as a birthday present. The i-th (1 ≦ i ≦ N) element of the sequence is a_i. The elements are pairwise distinct.
He is sorting this sequence in increasing order.
With supernatural power, he can perform the following two operations on the sequence in any order:

Operation 1: choose 2 consecutive elements, then reverse the order of those elements.

Operation 2: choose 3 consecutive elements, then reverse the order of those elements.

Snuke likes Operation 2, but not Operation 1. Find the minimum number of Operation 1 that he has to perform in order to sort the sequence in increasing order.

Constraints

1 ≦ N ≦ 10^5

0 ≦ A_i ≦ 10^9

If i ≠ j, then A_i ≠ A_j.

All input values are integers.

Input

The input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the minimum number of times Operation 1 that Snuke has to perform.

Sample Input 1

4
2
4
3
1

Sample Output 1

1

The given sequence can be sorted as follows:

First, reverse the order of the last three elements. The sequence is now: 2,1,3,4.

Then, reverse the order of the first two elements. The sequence is now: 1,2,3,4.

In this sequence of operations, Operation 1 is performed once. It is not possible to sort the sequence with less number of Operation 1, thus the answer is 1.

Sample Input 2

5
10
8
5
3
2

Sample Output 2

0


function Main(input) {
  const data = input.split("");
  var ans = [];
  for (var i = 0; i < data.length; i++) {
    if (data[i] === "1") {
      ans.push("1");
    } else if (data[i] === "0") {
      ans.push("0");
    } else if (data[i] === "B") {
      if (ans.length > 0) {
        ans.pop();
      } else {
        continue;
      }
    }
  }
  console.log(ans.join(""));
}

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

Score : 100 points

Problem Statement

There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?

Constraints

1≦N≦100

Input

The input is given from Standard Input in the following format:

N

Output

Print the necessary number of candies in total.

Sample Input 1

3

Sample Output 1

6

The answer is 1+2+3=6.

Sample Input 2

10

Sample Output 2

55

The sum of the integers from 1 to 10 is 55.

Sample Input 3

1

Sample Output 3

1

Only one child. The answer is 1 in this case.


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

    process.stdin.on('data', function (chunk) {
        var numbers = chunk.toString().split(' ');
        var a = parseInt(numbers.pop());
        var c = a*(a+1)/2;

        process.stdout.write(c.toString());

        process.exit();
    });


function Main(input) {
	input = input.trim();
  var N = parseInt(input.split("\n")[0].split(" ")[0]);
  var M = parseInt(input.split("\n")[0].split(" ")[1]);
  var list = new Array(N + 1).fill(1);//それぞれの箱の中にあるボールの個数
  var redVisited = new Set([0]);//赤が入った場所。赤が入ったことある場所の個数が0になるとbefore値がなくなる
  var lastRed = 0;//全ての操作で赤が可能な限り選ばれた場合の最後の場所
  for(var i = 1; i <= M; i++){
    var tmp = input.split("\n")[i].split(" ");
    list[tmp[0]]--;
    list[tmp[1]]++;
    if(redVisited.has(tmp[0])){
      	redVisited.add(tmp[1]);
    }
    if(list[tmp[0]] == 0){
       redVisited.delete(tmp[0]);
    }
  }
  //console.log(list);
  console.log(redVisited.size);
  //console.log(lastRed);
}

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

Problem Statement

We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball.

Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i.

Find the number of boxes that may contain the red ball after all operations are performed.

Constraints

2≤N≤10^5

1≤M≤10^5

1≤x_i,y_i≤N

x_i≠y_i

Just before the i-th operation is performed, box x_i contains at least 1 ball.

Input

The input is given from Standard Input in the following format:

N M
x_1 y_1
:
x_M y_M

Output

Print the number of boxes that may contain the red ball after all operations are performed.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

2

Just after the first operation, box 1 is empty, box 2 contains one red ball and one white ball, and box 3 contains one white ball.

Now, consider the second operation. If Snuke picks the red ball from box 2, the red ball will go into box 3. If he picks the white ball instead, the red ball will stay in box 2.
Thus, the number of boxes that may contain the red ball after all operations, is 2.

Sample Input 2

3 3
1 2
2 3
2 3

Sample Output 2

1

All balls will go into box 3.

Sample Input 3

4 4
1 2
2 3
4 1
3 4

Sample Output 3

3


function main(input) {
    const nums = input.split(" ");

    if(nums.indexOf('5') != -1) {
         nums.splice(nums.indexOf('5'),1);
    }
    if(nums.indexOf('5') != -1) {
         nums.splice(nums.indexOf('5'),1);
    }
    if(nums.indexOf('7') != -1) {
         nums.splice(nums.indexOf('7'),1);
    }
    console.log(nums[0] == null ? "YES" : "NO");
}

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

Score : 100 points

Problem Statement

Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.

To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of the phrases once, in some order.

Constraints

1≦A,B,C≦10

Input

The input is given from Standard Input in the following format:

A B C

Output

If it is possible to construct a Haiku by using each of the phrases once, print YES (case-sensitive). Otherwise, print NO.

Sample Input 1

5 5 7

Sample Output 1

YES

Using three phrases of length 5, 5 and 7, it is possible to construct a Haiku.

Sample Input 2

7 7 5

Sample Output 2

NO


function Main(input) {
  var A = parseInt(input.split(" ")[0]);
  var B = parseInt(input.split(" ")[1]);
  var C = parseInt(input.split(" ")[2]);

  var sevenCount = 0;
  var fiveCount = 0;

  if(A == 5){
     fiveCount++;
  }else if(A == 7){
     sevenCount++;
  }
  if(B == 5){
     fiveCount++;
  }else if(B == 7){
     sevenCount++;
  }
  if(C == 5){
     fiveCount++;
  }else if(C == 7){
     sevenCount++;
  }

  if(fiveCount == 2 && sevenCount == 1){
     console.log("YES");
     }else{
     console.log("NO");
     }
}

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


function main(input){
const texts = input.split(" ").join("");
if(texts==="575"||texts==="755"||texts==="557"){console.log("YES");}else{console.log("NO")}
}
main(require("fs").readFileSync('/dev/stdin','utf8'))


function main(input) {
    var arr = [];
    var rows = input.split(" ");
    rows = rows.sort();
    console.log(rows);
    if(rows[0] == 5 && rows[1] == 5 && rows[2] == 7){
    	console.log("YES");
    }else{
    	console.log("NO");
    }
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main() {
  const input = require("fs").readFileSync("/dev/stdin", "utf-8").trim();
  const lines = input.split('\n');
  const totalNum = lines[0].split(' ')[0].split('');
  const dislikeNum = lines[1].split(' ');
  const likeNum = [];
  for(let i = 0; i < 10; i++) {
    if(dislikeNum.indexOf(i + '') === -1) {
      likeNum.push(i + '');
    }
  }
  const res = getResult(totalNum, likeNum);
  if(res.flag) {
    console.log(likeNum[0] === '0' ? likeNum[1] + res.str : likeNum[0] + res.str);
  } else {
    console.log(res.str);
  }
}

function getResult(sourceNum, likeNum) {
  const item = sourceNum[0];
  const resObj = sourceNum.length - 1 ? getResult(sourceNum.slice(1), likeNum) : {};
  const resStr = resObj.str || '';
  const flag = resObj.flag;
  if(!flag) {
    if(likeNum.indexOf(item) > -1) {
      return {
        str: item + resStr,
        flag: false
      };
    } else {
      const bigger = getBigger(likeNum, item);
      if(bigger) {
        let str = '';
        for(let i = 0; i < resStr.length; i++) {
          str += likeNum[0];
        }
        return {
          str: bigger + str,
          flag: false
        };
      } else {
        let str = '';
        for(let i = 0; i < resStr.length; i++) {
          str += likeNum[0];
        }
        return {
          str: likeNum[0] + str,
          flag: true
        };
      }
    }
  } else {
    const bigger = getBigger(likeNum, item);
    if(bigger) {
      let str = '';
      for(let i = 0; i < resStr.length; i++) {
        str += likeNum[0];
      }
      return {
        str: bigger + str,
        flag: false
      };
    } else {
      let str = '';
      for(let i = 0; i < resStr.length; i++) {
        str += likeNum[0];
      }
      return {
        str: likeNum[0] + str,
        flag: true
      };
    }
  }
}

function getBigger(arr, num) {
  for(let i = 0; i < arr.length; i++) {
    if(arr[i] > num) {
      return arr[i] + ''
    }
  }
  return null;
}

main();

Score : 300 points

Problem Statement

Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.

She is shopping, and now paying at the cashier.
Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).

However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money.

Find the amount of money that she will hand to the cashier.

Constraints

1 ≦ N < 10000

1 ≦ K < 10

0 ≦ D_1 < D_2 < … < D_K≦9

\{D_1,D_2,...,D_K\} ≠ \{1,2,3,4,5,6,7,8,9\}

Input

The input is given from Standard Input in the following format:

N K
D_1 D_2 … D_K

Output

Print the amount of money that Iroha will hand to the cashier.

Sample Input 1

1000 8
1 3 4 5 6 7 8 9

Sample Output 1

2000

She dislikes all digits except 0 and 2.

The smallest integer equal to or greater than N=1000 whose decimal notation contains only 0 and 2, is 2000.

Sample Input 2

9999 1
0

Sample Output 2

9999