function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split(' ');
	//文字列から10進数に変換するときはparseIntを使います
	var a = parseInt(input[0], 10);
	var b = parseInt(input[1], 10);
	var c = parseInt(input[2], 10);
    var ans = "win";
	if(a + b + c > 21){
      ans = "bust";
    }
	console.log(ans);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

Given are three integers A_1, A_2, and A_3.

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Constraints

1 \leq A_i \leq 13 \ \ (i=1,2,3)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Sample Input 1

5 7 9

Sample Output 1

win

5+7+9=21, so print win.

Sample Input 2

13 7 2

Sample Output 2

bust

13+7+2=22, so print bust.


`use strict`

function Main(input) {
  const a = input.trim().split('')
  const N = a.length

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

  let c = 0
  for(let i = 0; i < Math.floor(N/2); ++i) {
    const t = a[i]
    const l = a[N - 1 - i]
    if (t !== l) c++
  }
  console.log(c)

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

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

Score : 200 points

Problem Statement

Takahashi loves palindromes. Non-palindromic strings are unacceptable to him. Each time he hugs a string, he can change one of its characters to any character of his choice.

Given is a string S. Find the minimum number of hugs needed to make S palindromic.

Constraints

S is a string consisting of lowercase English letters.

The length of S is between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of hugs needed to make S palindromic.

Sample Input 1

redcoder

Sample Output 1

1

For example, we can change the fourth character to o and get a palindrome redooder.

Sample Input 2

vvvvvv

Sample Output 2

0

We might need no hugs at all.

Sample Input 3

abcdabc

Sample Output 3

2

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) {
  const resrt = Math.floor(input / 1.08);
  const aaaa = Math.floor( resrt * 1.08);
  // console.log(aaaa + " aaaa");
  // console.log(resrt + " resrt");
  // console.log(input / 1.08 + " input / 1.08");

  if (aaaa == input) {
    console.log(aaaa);

  } else {
    console.log(':(');

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

Score: 200 points

Problem Statement

Takahashi bought a piece of apple pie at ABC Confiserie. According to his memory, he paid N yen (the currency of Japan) for it.

The consumption tax rate for foods in this shop is 8 percent. That is, to buy an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen (rounded down to the nearest integer).

Takahashi forgot the price of his apple pie before tax, X, and wants to know it again. Write a program that takes N as input and finds X. We assume X is an integer.

If there are multiple possible values for X, find any one of them. Also, Takahashi's memory of N, the amount he paid, may be incorrect. If no value could be X, report that fact.

Constraints

1 \leq N \leq 50000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If there are values that could be X, the price of the apple pie before tax, print any one of them.

If there are multiple such values, printing any one of them will be accepted.

If no value could be X, print :(.

Sample Input 1

432

Sample Output 1

400

If the apple pie is priced at 400 yen before tax, you have to pay 400 \times 1.08 = 432 yen to buy one.

Otherwise, the amount you have to pay will not be 432 yen.

Sample Input 2

1079

Sample Output 2

:(

There is no possible price before tax for which you have to pay 1079 yen with tax.

Sample Input 3

1001

Sample Output 3

927

If the apple pie is priced 927 yen before tax, by rounding down 927 \times 1.08 = 1001.16, you have to pay 1001 yen.


// inputに入力データ全体が入る

function Main(input) {
  const resrt = Math.round(input / 1.08);
  const aaaa = resrt * 1.08;

  if (aaaa = Math.round(Math.round)) {
    console.log(aaaa);

  } else {
    console.log(':(');

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


function Main(input) {
  input = input.split('\n');
	var n = Number(input[0]);
  var str = '';
  var stri = new Array();
  var retu = new Array(n);
  var frg = 0;
  var count = 0;
  for(var i=0; i<n; i++){
    retu[i] = Number(input[1].charAt(i));
  }
  for(var i=0; i<1000; i++){
	str = String(i);
    frg = 0;
    if(i > 99){
          stri[0] = str.charAt(0);
    stri[1] = str.charAt(1);
    stri[2] = str.charAt(2);
  }else if(i > 9){
      stri[0] = 0;
    stri[1] = str.charAt(0);
    stri[2] = str.charAt(1);
    }else{
            stri[0] = 0;
    stri[1] = 0;
    stri[2] = str.charAt(0);
    }
    for(var j=0; j<n; j++){
    	if(stri[frg] == retu[j] && frg != 3){
          frg++;
           }
    }
    if(frg == 3){
       count++;
       }
  }
  console.log(count);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score: 400 points

Problem Statement

AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code.

The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code.

How many different PIN codes can he set this way?

Both the lucky number and the PIN code may begin with a 0.

Constraints

4 \leq N \leq 30000

S is a string of length N consisting of digits.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of different PIN codes Takahashi can set.

Sample Input 1

4
0224

Sample Output 1

3

Takahashi has the following options:

Erase the first digit of S and set 224.

Erase the second digit of S and set 024.

Erase the third digit of S and set 024.

Erase the fourth digit of S and set 022.

Thus, he can set three different PIN codes: 022, 024, and 224.

Sample Input 2

6
123123

Sample Output 2

17

Sample Input 3

19
3141592653589793238

Sample Output 3

329


const arr = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']

function Main(input) {
  console.log(arr.length - arr.indexOf(input))
}

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

Score : 100 points

Problem Statement

Given is a string S representing the day of the week today.

S is SUN, MON, TUE, WED, THU, FRI, or SAT, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively.

After how many days is the next Sunday (tomorrow or later)?

Constraints

S is SUN, MON, TUE, WED, THU, FRI, or SAT.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of days before the next Sunday.

Sample Input 1

SAT

Sample Output 1

1

It is Saturday today, and tomorrow will be Sunday.

Sample Input 2

SUN

Sample Output 2

7

It is Sunday today, and seven days later, it will be Sunday again.


// inputに入力データ全体が入る
function Main(input) {
	if(input == 'SUN'){
      console.log(7);
    }else if(input == 'MON'){
      console.log(6);
    }else if(input == 'TUE'){
      console.log(5);
    }else if(input == 'WED'){
      console.log(4);
    }else if(input == 'THU'){
      console.log(3);
    }else if(input == 'FRI'){
      console.log(2);
    }else if(input == 'SAT'){
      console.log(1);
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


    function main(arg) {
        if(arg=="SUN"){console.log(7)}
        if(arg=="MON"){console.log(6)}
        if(arg=="TUE"){console.log(5)}
        if(arg=="WED"){console.log(4)}
        if(arg=="THU"){console.log(3)}
        if(arg=="FRI"){console.log(2)}
        if(arg=="SAT"){console.log(1)}
    }
    main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
  if (input == 'SUN') {
    console.log(7)
  }
  if (input == 'MON') {
    console.log(6)
  }
  if (input == 'TUE') {
    console.log(5)
  }
  if (input == 'WED') {
    console.log(4)
  }
  if (input == 'THU') {
    console.log(3)
  }
  if (input == 'FRI') {
    console.log(2)
  }
  if (input == 'SAT') {
    console.log(1)
  }
  // switch (input) {
  //   case 'SUN':
  //     console.log(parseInt(7).toString())
  //     break
  //   case 'MON':
  //     console.log(parseInt(6).toString())
  //     break
  //   case 'TUE':
  //     console.log(parseInt(5).toString())
  //     break
  //   case 'WED':
  //     console.log(parseInt(4).toString())
  //     break
  //   case 'THU':
  //     console.log(parseInt(3).toString())
  //     break
  //   case 'FRI':
  //     console.log(parseInt(2).toString())
  //     break
  //   default:
  //     console.log(parseInt(1).toString())
  //     break
  //   }
}

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


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

var lines = [];
var reader = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});
reader.on('line', (line) => {
    // ここで入力を処理する
    lines.push(line);
});
reader.on('close', () => {
    // ここで出力する
    for(var i =0; i<lines.length; i++){
      	switch(lines[i]){
    case 'SUN':
        console.log('1');
        break;

    case 'MON':
        console.log('2');
        break;

    case 'TUE':
        console.log('3');
        break;

    case 'WED':
        console.log('4');
        break;

    case 'THU':
        console.log('5');
        break;

    case 'FRI':
        console.log('6');
        break;

    case 'SAT':
        console.log('7');
        break;
	}
    }
});


function Main(input) {
    youbi = ["SUN","MON","TUE","WED","THU","FRI","SAT"]

    const index = youbi.findIndex(e=>{
        return e===input
    })

    console.log(7-index);
}

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


String.prototype.splitByIndention = function () {
        return this.split('\n');
};
String.prototype.splitBySpace = function () {
        return this.split(' ');
};
Array.prototype.parseIntToEach = function () {
        return this.map(x => Number(x));
};
const input = require('fs').readFileSync('/dev/stdin', 'utf8');

function main(input) {
  var result = {"SUN":7,"MON":6,"TUE":5,"WED":4,"THU":3,"FRI":2,"SAT":1};
  console.log(result[input]);
};

main(input);


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

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

  const data =
  {
    SUN: 7,
    MON: 6,
    TUE: 5,
    WED: 4,
    THU: 3,
    FRI: 2,
    SAT: 1
  }

  // //文字列から10進数に変換するときはparseIntを使います
  // // var a = parseInt(i[0], 10);
  // // var b = parseInt(i[1], 10);
  // // var c = parseInt(i[2], 10);
  // var i1 = i.map(v => parseInt(v, 10))

  // console.log(input1[0])
  // // console.log(input1[0], i, i1, i1.some(v => v % 2 !== 0))

  // var count1 = 0
  // while (!i1.some(v => v % 2 !== 0)) {
  //   i1 = i1.map(v => v / 2)
  //   count1++
  // }

  // console.log(a,b,a + b, (a + b) % 2)
  // var s = a + b + c

  //出力
  console.log(data[i]);
}

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


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        String a = scan.next();
        int ans=0;
        if(a.equals("MON"))ans=6;
        if(a.equals("TUE"))ans=5;
        if(a.equals("WED"))ans=4;
        if(a.equals("THU"))ans=3;
        if(a.equals("FRI"))ans=2;
        if(a.equals("SAT"))ans=1;
        if(a.equals("SUN"))ans=7;
        System.out.println(ans);
    }
}


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

let input_lines = [];
let reader = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

reader.on('line', (line) => {
    input_lines = line.split(' ');
});

let x = parseInt(input_lines[0]);
let y = parseInt(input_lines[1]);

if (x === 1 && y === 1) {
    reader.on('close', () => {
        console.log(300000 * 2 + 400000);
    })
}
else {
    reader.on('close', () => {
        console.log(100000 * ((4 - x) + (4 - y)));
    })
}

Score: 100 points

Problem Statement

We held two competitions: Coding Contest and Robot Maneuver.

In each competition, the contestants taking the 3-rd, 2-nd, and 1-st places receive 100000, 200000, and 300000 yen (the currency of Japan), respectively. Furthermore, a contestant taking the first place in both competitions receives an additional 400000 yen.

DISCO-Kun took the X-th place in Coding Contest and the Y-th place in Robot Maneuver.
Find the total amount of money he earned.

Constraints

1 \leq X \leq 205

1 \leq Y \leq 205

X and Y are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the amount of money DISCO-Kun earned, as an integer.

Sample Input 1

1 1

Sample Output 1

1000000

In this case, he earned 300000 yen in Coding Contest and another 300000 yen in Robot Maneuver. Furthermore, as he won both competitions, he got an additional 400000 yen.
In total, he made 300000 + 300000 + 400000 = 1000000 yen.

Sample Input 2

3 101

Sample Output 2

100000

In this case, he earned 100000 yen in Coding Contest.

Sample Input 3

4 4

Sample Output 3

0

In this case, unfortunately, he was the highest-ranked contestant without prize money in both competitions.


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0]);
    const A = arg[1].split(" ").map( str => parseInt(str, 10) );;
    let num = 0;
    for(var i=0;i<N;i++){
        num+=A[i];
    }
    let ans = Infinity;
    let mem = A[0];
    for(var i=1;i<N-1;i++){
        mem+=A[i];
        ans=Math.min(ans,Math.abs(num-mem*2));
    }
    console.log(ans);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score: 200 points

Problem Statement

Takahashi, who works at DISCO, is standing before an iron bar.
The bar has N-1 notches, which divide the bar into N sections. The i-th section from the left has a length of A_i millimeters.

Takahashi wanted to choose a notch and cut the bar at that point into two parts with the same length.
However, this may not be possible as is, so he will do the following operations some number of times before he does the cut:

Choose one section and expand it, increasing its length by 1 millimeter. Doing this operation once costs 1 yen (the currency of Japan).

Choose one section of length at least 2 millimeters and shrink it, decreasing its length by 1 millimeter. Doing this operation once costs 1 yen.

Find the minimum amount of money needed before cutting the bar into two parts with the same length.

Constraints

2 \leq N \leq 200000

1 \leq A_i \leq 2020202020

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 A_3 ... A_N

Output

Print an integer representing the minimum amount of money needed before cutting the bar into two parts with the same length.

Sample Input 1

3
2 4 3

Sample Output 1

3

The initial lengths of the sections are [2, 4, 3] (in millimeters). Takahashi can cut the bar equally after doing the following operations for 3 yen:

Shrink the second section from the left. The lengths of the sections are now [2, 3, 3].

Shrink the first section from the left. The lengths of the sections are now [1, 3, 3].

Shrink the second section from the left. The lengths of the sections are now [1, 2, 3], and we can cut the bar at the second notch from the left into two parts of length 3 each.

Sample Input 2

12
100 104 102 105 103 103 101 105 104 102 104 101

Sample Output 2

0


function Main(input) {

	console.log(x * x);
}

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

Score : 100 points

Problem Statement

Given is an integer r.

How many times is the area of a circle of radius r larger than the area of a circle of radius 1?

It can be proved that the answer is always an integer under the constraints given.

Constraints

1 \leq r \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r

Output

Print the area of a circle of radius r, divided by the area of a circle of radius 1, as an integer.

Sample Input 1

2

Sample Output 1

4

The area of a circle of radius 2 is 4 times larger than the area of a circle of radius 1.

Note that output must be an integer - for example, 4.0 will not be accepted.

Sample Input 2

100

Sample Output 2

10000


function Main(r) {
  input = r.split("\n");
  tmp = input[0].split(" ");
  var a = parseInt(tmp);
  return a*a;
}

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


function Main(r) {
  var r = parseInt(r.split('\n')[0])
  console.log(r * r)
}
Main.(require('fs').readFileSync("/dev/stdin", 'utf8'))


function Main(input) {
	input = input.split("\n");
	tmp = input[1].split(" ");
	var N = parseInt(input[0], 10);
	var S = input[1]
	if (N === 1) {
	  console.log('No');
	} else {
	  str = S.match(/.{3}/g);
	  if (str[0] === str[1]){
	    console.log('Yes');
	  } else {
	    console.log('No')
	  }
	}
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 200 points

Problem Statement

Given are a positive integer N and a string S of length N consisting of lowercase English letters.

Determine whether the string is a concatenation of two copies of some string.
That is, determine whether there is a string T such that S = T + T.

Constraints

1 \leq N \leq 100

S consists of lowercase English letters.

|S| = N

Input

Input is given from Standard Input in the following format:

N
S

Output

If S is a concatenation of two copies of some string, print Yes; otherwise, print No.

Sample Input 1

6
abcabc

Sample Output 1

Yes

Let T = abc, and S = T + T.

Sample Input 2

6
abcadc

Sample Output 2

No

Sample Input 3

1
z

Sample Output 3

No


'use strict';
const main = input => {
  const n = parseInt(input[0]);
  let p = [];
  for(let i=0; i<n; i++) {
    let k = input[i+1].split(' ').map(val => parseInt(val));
    p[i] = {x: k[0], y: k[1]};
  }
  let distanceSum = 0;
  for(let i=0; i<n-1; i++) {
    for(let j=i; j<n; j++) {
      distanceSum += Math.sqrt(Math.pow(p[i].x-p[j].x, 2)+Math.pow(p[i].y-p[j].y, 2));
    }
  }
  console.log(distanceSum/n*2);
}
main(require("fs").readFileSync("/dev/stdin", "utf8").split('\n'));

Score : 300 points

Problem Statement

There are N towns in a coordinate plane. Town i is located at coordinates (x_i, y_i). The distance between Town i and Town j is \sqrt{\left(x_i-x_j\right)^2+\left(y_i-y_j\right)^2}.

There are N! possible paths to visit all of these towns once. Let the length of a path be the distance covered when we start at the first town in the path, visit the second, third, \dots, towns, and arrive at the last town (assume that we travel in a straight line from a town to another). Compute the average length of these N! paths.

Constraints

2 \leq N \leq 8

-1000 \leq x_i \leq 1000

-1000 \leq y_i \leq 1000

\left(x_i, y_i\right) \neq \left(x_j, y_j\right) (if i \neq j)

(Added 21:12 JST) All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the average length of the paths.
Your output will be judges as correct when the absolute difference from the judge's output is at most 10^{-6}.

Sample Input 1

3
0 0
1 0
0 1

Sample Output 1

2.2761423749

There are six paths to visit the towns: 1 → 2 → 3, 1 → 3 → 2, 2 → 1 → 3, 2 → 3 → 1, 3 → 1 → 2, and 3 → 2 → 1.

The length of the path 1 → 2 → 3 is \sqrt{\left(0-1\right)^2+\left(0-0\right)^2} + \sqrt{\left(1-0\right)^2+\left(0-1\right)^2} = 1+\sqrt{2}.

By calculating the lengths of the other paths in this way, we see that the average length of all routes is:

\frac{\left(1+\sqrt{2}\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)}{6} = 2.276142...

Sample Input 2

2
-879 981
-866 890

Sample Output 2

91.9238815543

There are two paths to visit the towns: 1 → 2 and 2 → 1. These paths have the same length.

Sample Input 3

8
-406 10
512 859
494 362
-955 -475
128 553
-986 -885
763 77
449 310

Sample Output 3

7641.9817824387


"use strict"

const arg_str = require('fs').readFileSync('/dev/stdin', 'UTF-8')
const args = arg_str.split('\n')
const N = +args[0]
const cities = args.slice(1).map(x => x.split(' '))

let sum = 0

for(let i=0;i<N;i++){
  for(let j=0;j<N;j++){
    if(i != j){
      sum += Math.sqrt((cities[i][0] - cities[j][0]) * (cities[i][0] - cities[j][0]) + (cities[i][1] - cities[j][1]) * (cities[i][1] - cities[j][1]))
    }
  }
}

const fact = k =>
  k===0 ?  1
  : k * fact( k - 1 )

console.log(sum/fact(N))


module.exports=function(t){var e={};function r(n){if(e[n])return e[n].exports;var i=e[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)r.d(n,i,function(e){return t[e]}.bind(null,i));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=1)}([function(t,e,r){"use strict";t.exports=class{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];this.size=t.length,this.items=t,this.ind=0}enq(t){this.size+=1,this.items.push(t)}deq(){var t=this.items[this.ind];return this.size-=1,this.ind+=1,t}clear(){this.items=[],this.size=0,this.ind=0}}},function(t,e,r){"use strict";var n=r(2);r(3)(n.readFileSync("/dev/stdin","utf8"))},function(t,e){t.exports=require("fs")},function(t,e,r){"use strict";var n=r(4),i=r(5);t.exports=function(t){var e=new n(t);i(e)}},function(t,e,r){"use strict";var n=r(0);t.exports=class{constructor(t){var e=t.trim().split(/\s+/g);this.inp=new n(e)}inr(){return this.inp.deq()}in(){return parseInt(this.inp.deq(),10)}fin(){this.inp.clear()}}},function(t,e,r){"use strict";var n=r(0);t.exports=function(t){for(var e=t.in(),r=new Array(e),i=new Array(e),s=0;s<e;s++)r[s]=t.in(),i[s]=t.in();for(var o=0,u=0,a=new n,c=0;c<e;c++){var f=new Array(e).fill(0);f[c]=1,a.enq({d:0,dist:0,now:c,used:f})}for(;a.size>0;){var d=a.deq();if(d.d!=e-1){for(var l=0;l<e;l++)if(1!=d.used[l]){var p=d.used.concat();p[l]=1;var v=(r[d.now]-r[l])*(r[d.now]-r[l]),h=(i[d.now]-i[l])*(i[d.now]-i[l]),y=Math.sqrt(v+h),b=d.dist+y;a.enq({d:d.d+1,dist:b,now:l,used:p})}}else o+=d.dist,u++}var w=o/u;console.log(w)}}]);


'use strict'

const ncr = (n, r, mod) => {
  mod = mod || 1e9+7
  const a = Math.max(n, r)
  const b = Math.min(n, r)
  const p = Math.min(b, a-b)
  const nu = new Array(p + 1)
  const de = new Array(p + 1)
  let dest = 1
  if (p > 0) {
    for (let i = 1; i <= p; i++) {
      nu[i] = a - p + i
      de[i] = i
    }
    for (let k = 2; k <= p; k++) {
      const piv = de[k]
      const j = (piv > 1) ? -((a - p) % k) : 0
      for (let i = k; i <= p; i += k) {
        nu[i + j] /= piv; de[i] /= piv
      }
    }
    for (let i = 1; i <= p; i++) {
      if (nu[i] > 1) dest = dest * nu[i] % mod
    }
  }
  return dest
}

function main(inp) {
  inp = inp.trim().split(' ');
  const x = Number(inp[0])
  const y = Number(inp[1])

  let sum = 0
  for (let i = Math.floor(x / 2); i >= 0; i--) {
    const a = x - i * 2
    if (a * 2 + i === y) {
      sum = ncr(i+a, i)
    }
  }

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

Score : 400 points

Problem Statement

There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.

When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).

In how many ways can the knight reach the square (X, Y)?

Find the number of ways modulo 10^9 + 7.

Constraints

1 \leq X \leq 10^6

1 \leq Y \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the number of ways for the knight to reach (X, Y) from (0, 0), modulo 10^9 + 7.

Sample Input 1

3 3

Sample Output 1

2

There are two ways: (0,0) \to (1,2) \to (3,3) and (0,0) \to (2,1) \to (3,3).

Sample Input 2

2 2

Sample Output 2

0

The knight cannot reach (2,2).

Sample Input 3

999999 999999

Sample Output 3

151840682

Print the number of ways modulo 10^9 + 7.


const Main = input => {
  const N = +input;
  console.log(Math.ceil(input / 2));
}

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

Score : 100 points

Problem Statement

How many ways are there to choose two distinct positive integers totaling N, disregarding the order?

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

4

Sample Output 1

1

There is only one way to choose two distinct integers totaling 4: to choose 1 and 3. (Choosing 3 and 1 is not considered different from this.)

Sample Input 2

999999

Sample Output 2

499999


module.exports=function(e){var r={};function n(t){if(r[t])return r[t].exports;var i=r[t]={i:t,l:!1,exports:{}};return e[t].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=r,n.d=function(e,r,t){n.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,r){if(1&r&&(e=n(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(n.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var i in e)n.d(t,i,function(r){return e[r]}.bind(null,i));return t},n.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(r,"a",r),r},n.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},n.p="",n(n.s=1)}([function(e,r,n){var t;!function(i){"use strict";var o,s=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,u=Math.ceil,f=Math.floor,c="[BigNumber Error] ",l=c+"Number primitive has more than 15 significant digits: ",a=1e14,h=14,p=9007199254740991,g=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],d=1e7,m=1e9;function w(e){var r=0|e;return e>0||e===r?r:r-1}function v(e){for(var r,n,t=1,i=e.length,o=e[0]+"";t<i;){for(r=e[t++]+"",n=h-r.length;n--;r="0"+r);o+=r}for(i=o.length;48===o.charCodeAt(--i););return o.slice(0,i+1||1)}function b(e,r){var n,t,i=e.c,o=r.c,s=e.s,u=r.s,f=e.e,c=r.e;if(!s||!u)return null;if(n=i&&!i[0],t=o&&!o[0],n||t)return n?t?0:-u:s;if(s!=u)return s;if(n=s<0,t=f==c,!i||!o)return t?0:!i^n?1:-1;if(!t)return f>c^n?1:-1;for(u=(f=i.length)<(c=o.length)?f:c,s=0;s<u;s++)if(i[s]!=o[s])return i[s]>o[s]^n?1:-1;return f==c?0:f>c^n?1:-1}function y(e,r,n,t){if(e<r||e>n||e!==f(e))throw Error(c+(t||"Argument")+("number"==typeof e?e<r||e>n?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function O(e){var r=e.c.length-1;return w(e.e/h)==r&&e.c[r]%2!=0}function N(e,r){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(r<0?"e":"e+")+r}function E(e,r,n){var t,i;if(r<0){for(i=n+".";++r;i+=n);e=i+e}else if(++r>(t=e.length)){for(i=n,r-=t;--r;i+=n);e+=i}else r<t&&(e=e.slice(0,r)+"."+e.slice(r));return e}(o=function e(r){var n,t,i,o,A,x,S,_,P,R=k.prototype={constructor:k,toString:null,valueOf:null},D=new k(1),B=20,L=4,T=-7,I=21,M=-1e7,U=1e7,C=!1,j=1,q=0,G={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},F="0123456789abcdefghijklmnopqrstuvwxyz";function k(e,r){var n,o,u,c,a,g,d,m,w=this;if(!(w instanceof k))return new k(e,r);if(null==r){if(e&&!0===e._isBigNumber)return w.s=e.s,void(!e.c||e.e>U?w.c=w.e=null:e.e<M?w.c=[w.e=0]:(w.e=e.e,w.c=e.c.slice()));if((g="number"==typeof e)&&0*e==0){if(w.s=1/e<0?(e=-e,-1):1,e===~~e){for(c=0,a=e;a>=10;a/=10,c++);return void(c>U?w.c=w.e=null:(w.e=c,w.c=[e]))}m=String(e)}else{if(!s.test(m=String(e)))return i(w,m,g);w.s=45==m.charCodeAt(0)?(m=m.slice(1),-1):1}(c=m.indexOf("."))>-1&&(m=m.replace(".","")),(a=m.search(/e/i))>0?(c<0&&(c=a),c+=+m.slice(a+1),m=m.substring(0,a)):c<0&&(c=m.length)}else{if(y(r,2,F.length,"Base"),10==r)return V(w=new k(e),B+w.e+1,L);if(m=String(e),g="number"==typeof e){if(0*e!=0)return i(w,m,g,r);if(w.s=1/e<0?(m=m.slice(1),-1):1,k.DEBUG&&m.replace(/^0\.0*|\./,"").length>15)throw Error(l+e)}else w.s=45===m.charCodeAt(0)?(m=m.slice(1),-1):1;for(n=F.slice(0,r),c=a=0,d=m.length;a<d;a++)if(n.indexOf(o=m.charAt(a))<0){if("."==o){if(a>c){c=d;continue}}else if(!u&&(m==m.toUpperCase()&&(m=m.toLowerCase())||m==m.toLowerCase()&&(m=m.toUpperCase()))){u=!0,a=-1,c=0;continue}return i(w,String(e),g,r)}g=!1,(c=(m=t(m,r,10,w.s)).indexOf("."))>-1?m=m.replace(".",""):c=m.length}for(a=0;48===m.charCodeAt(a);a++);for(d=m.length;48===m.charCodeAt(--d););if(m=m.slice(a,++d)){if(d-=a,g&&k.DEBUG&&d>15&&(e>p||e!==f(e)))throw Error(l+w.s*e);if((c=c-a-1)>U)w.c=w.e=null;else if(c<M)w.c=[w.e=0];else{if(w.e=c,w.c=[],a=(c+1)%h,c<0&&(a+=h),a<d){for(a&&w.c.push(+m.slice(0,a)),d-=h;a<d;)w.c.push(+m.slice(a,a+=h));a=h-(m=m.slice(a)).length}else a-=d;for(;a--;m+="0");w.c.push(+m)}}else w.c=[w.e=0]}function z(e,r,n,t){var i,o,s,u,f;if(null==n?n=L:y(n,0,8),!e.c)return e.toString();if(i=e.c[0],s=e.e,null==r)f=v(e.c),f=1==t||2==t&&(s<=T||s>=I)?N(f,s):E(f,s,"0");else if(o=(e=V(new k(e),r,n)).e,u=(f=v(e.c)).length,1==t||2==t&&(r<=o||o<=T)){for(;u<r;f+="0",u++);f=N(f,o)}else if(r-=s,f=E(f,o,"0"),o+1>u){if(--r>0)for(f+=".";r--;f+="0");}else if((r+=o-u)>0)for(o+1==u&&(f+=".");r--;f+="0");return e.s<0&&i?"-"+f:f}function $(e,r){for(var n,t=1,i=new k(e[0]);t<e.length;t++){if(!(n=new k(e[t])).s){i=n;break}r.call(i,n)&&(i=n)}return i}function H(e,r,n){for(var t=1,i=r.length;!r[--i];r.pop());for(i=r[0];i>=10;i/=10,t++);return(n=t+n*h-1)>U?e.c=e.e=null:n<M?e.c=[e.e=0]:(e.e=n,e.c=r),e}function V(e,r,n,t){var i,o,s,c,l,p,d,m=e.c,w=g;if(m){e:{for(i=1,c=m[0];c>=10;c/=10,i++);if((o=r-i)<0)o+=h,s=r,d=(l=m[p=0])/w[i-s-1]%10|0;else if((p=u((o+1)/h))>=m.length){if(!t)break e;for(;m.length<=p;m.push(0));l=d=0,i=1,s=(o%=h)-h+1}else{for(l=c=m[p],i=1;c>=10;c/=10,i++);d=(s=(o%=h)-h+i)<0?0:l/w[i-s-1]%10|0}if(t=t||r<0||null!=m[p+1]||(s<0?l:l%w[i-s-1]),t=n<4?(d||t)&&(0==n||n==(e.s<0?3:2)):d>5||5==d&&(4==n||t||6==n&&(o>0?s>0?l/w[i-s]:0:m[p-1])%10&1||n==(e.s<0?8:7)),r<1||!m[0])return m.length=0,t?(r-=e.e+1,m[0]=w[(h-r%h)%h],e.e=-r||0):m[0]=e.e=0,e;if(0==o?(m.length=p,c=1,p--):(m.length=p+1,c=w[h-o],m[p]=s>0?f(l/w[i-s]%w[s])*c:0),t)for(;;){if(0==p){for(o=1,s=m[0];s>=10;s/=10,o++);for(s=m[0]+=c,c=1;s>=10;s/=10,c++);o!=c&&(e.e++,m[0]==a&&(m[0]=1));break}if(m[p]+=c,m[p]!=a)break;m[p--]=0,c=1}for(o=m.length;0===m[--o];m.pop());}e.e>U?e.c=e.e=null:e.e<M&&(e.c=[e.e=0])}return e}function W(e){var r,n=e.e;return null===n?e.toString():(r=v(e.c),r=n<=T||n>=I?N(r,n):E(r,n,"0"),e.s<0?"-"+r:r)}return k.clone=e,k.ROUND_UP=0,k.ROUND_DOWN=1,k.ROUND_CEIL=2,k.ROUND_FLOOR=3,k.ROUND_HALF_UP=4,k.ROUND_HALF_DOWN=5,k.ROUND_HALF_EVEN=6,k.ROUND_HALF_CEIL=7,k.ROUND_HALF_FLOOR=8,k.EUCLID=9,k.config=k.set=function(e){var r,n;if(null!=e){if("object"!=typeof e)throw Error(c+"Object expected: "+e);if(e.hasOwnProperty(r="DECIMAL_PLACES")&&(y(n=e[r],0,m,r),B=n),e.hasOwnProperty(r="ROUNDING_MODE")&&(y(n=e[r],0,8,r),L=n),e.hasOwnProperty(r="EXPONENTIAL_AT")&&((n=e[r])&&n.pop?(y(n[0],-m,0,r),y(n[1],0,m,r),T=n[0],I=n[1]):(y(n,-m,m,r),T=-(I=n<0?-n:n))),e.hasOwnProperty(r="RANGE"))if((n=e[r])&&n.pop)y(n[0],-m,-1,r),y(n[1],1,m,r),M=n[0],U=n[1];else{if(y(n,-m,m,r),!n)throw Error(c+r+" cannot be zero: "+n);M=-(U=n<0?-n:n)}if(e.hasOwnProperty(r="CRYPTO")){if((n=e[r])!==!!n)throw Error(c+r+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw C=!n,Error(c+"crypto unavailable");C=n}else C=n}if(e.hasOwnProperty(r="MODULO_MODE")&&(y(n=e[r],0,9,r),j=n),e.hasOwnProperty(r="POW_PRECISION")&&(y(n=e[r],0,m,r),q=n),e.hasOwnProperty(r="FORMAT")){if("object"!=typeof(n=e[r]))throw Error(c+r+" not an object: "+n);G=n}if(e.hasOwnProperty(r="ALPHABET")){if("string"!=typeof(n=e[r])||/^.$|[+-.\s]|(.).*\1/.test(n))throw Error(c+r+" invalid: "+n);F=n}}return{DECIMAL_PLACES:B,ROUNDING_MODE:L,EXPONENTIAL_AT:[T,I],RANGE:[M,U],CRYPTO:C,MODULO_MODE:j,POW_PRECISION:q,FORMAT:G,ALPHABET:F}},k.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!k.DEBUG)return!0;var r,n,t=e.c,i=e.e,o=e.s;e:if("[object Array]"=={}.toString.call(t)){if((1===o||-1===o)&&i>=-m&&i<=m&&i===f(i)){if(0===t[0]){if(0===i&&1===t.length)return!0;break e}if((r=(i+1)%h)<1&&(r+=h),String(t[0]).length==r){for(r=0;r<t.length;r++)if((n=t[r])<0||n>=a||n!==f(n))break e;if(0!==n)return!0}}}else if(null===t&&null===i&&(null===o||1===o||-1===o))return!0;throw Error(c+"Invalid BigNumber: "+e)},k.maximum=k.max=function(){return $(arguments,R.lt)},k.minimum=k.min=function(){return $(arguments,R.gt)},k.random=(o=9007199254740992*Math.random()&2097151?function(){return f(9007199254740992*Math.random())}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var r,n,t,i,s,l=0,a=[],p=new k(D);if(null==e?e=B:y(e,0,m),i=u(e/h),C)if(crypto.getRandomValues){for(r=crypto.getRandomValues(new Uint32Array(i*=2));l<i;)(s=131072*r[l]+(r[l+1]>>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),r[l]=n[0],r[l+1]=n[1]):(a.push(s%1e14),l+=2);l=i/2}else{if(!crypto.randomBytes)throw C=!1,Error(c+"crypto unavailable");for(r=crypto.randomBytes(i*=7);l<i;)(s=281474976710656*(31&r[l])+1099511627776*r[l+1]+4294967296*r[l+2]+16777216*r[l+3]+(r[l+4]<<16)+(r[l+5]<<8)+r[l+6])>=9e15?crypto.randomBytes(7).copy(r,l):(a.push(s%1e14),l+=7);l=i/7}if(!C)for(;l<i;)(s=o())<9e15&&(a[l++]=s%1e14);for(i=a[--l],e%=h,i&&e&&(s=g[h-e],a[l]=f(i/s)*s);0===a[l];a.pop(),l--);if(l<0)a=[t=0];else{for(t=-1;0===a[0];a.splice(0,1),t-=h);for(l=1,s=a[0];s>=10;s/=10,l++);l<h&&(t-=h-l)}return p.e=t,p.c=a,p}),k.sum=function(){for(var e=1,r=arguments,n=new k(r[0]);e<r.length;)n=n.plus(r[e++]);return n},t=function(){function e(e,r,n,t){for(var i,o,s=[0],u=0,f=e.length;u<f;){for(o=s.length;o--;s[o]*=r);for(s[0]+=t.indexOf(e.charAt(u++)),i=0;i<s.length;i++)s[i]>n-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(r,t,i,o,s){var u,f,c,l,a,h,p,g,d=r.indexOf("."),m=B,w=L;for(d>=0&&(l=q,q=0,r=r.replace(".",""),h=(g=new k(t)).pow(r.length-d),q=l,g.c=e(E(v(h.c),h.e,"0"),10,i,"0123456789"),g.e=g.c.length),c=l=(p=e(r,t,i,s?(u=F,"0123456789"):(u="0123456789",F))).length;0==p[--l];p.pop());if(!p[0])return u.charAt(0);if(d<0?--c:(h.c=p,h.e=c,h.s=o,p=(h=n(h,g,m,w,i)).c,a=h.r,c=h.e),d=p[f=c+m+1],l=i/2,a=a||f<0||null!=p[f+1],a=w<4?(null!=d||a)&&(0==w||w==(h.s<0?3:2)):d>l||d==l&&(4==w||a||6==w&&1&p[f-1]||w==(h.s<0?8:7)),f<1||!p[0])r=a?E(u.charAt(1),-m,u.charAt(0)):u.charAt(0);else{if(p.length=f,a)for(--i;++p[--f]>i;)p[f]=0,f||(++c,p=[1].concat(p));for(l=p.length;!p[--l];);for(d=0,r="";d<=l;r+=u.charAt(p[d++]));r=E(r,c,u.charAt(0))}return r}}(),n=function(){function e(e,r,n){var t,i,o,s,u=0,f=e.length,c=r%d,l=r/d|0;for(e=e.slice();f--;)u=((i=c*(o=e[f]%d)+(t=l*o+(s=e[f]/d|0)*c)%d*d+u)/n|0)+(t/d|0)+l*s,e[f]=i%n;return u&&(e=[u].concat(e)),e}function r(e,r,n,t){var i,o;if(n!=t)o=n>t?1:-1;else for(i=o=0;i<n;i++)if(e[i]!=r[i]){o=e[i]>r[i]?1:-1;break}return o}function n(e,r,n,t){for(var i=0;n--;)e[n]-=i,i=e[n]<r[n]?1:0,e[n]=i*t+e[n]-r[n];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(t,i,o,s,u){var c,l,p,g,d,m,v,b,y,O,N,E,A,x,S,_,P,R=t.s==i.s?1:-1,D=t.c,B=i.c;if(!(D&&D[0]&&B&&B[0]))return new k(t.s&&i.s&&(D?!B||D[0]!=B[0]:B)?D&&0==D[0]||!B?0*R:R/0:NaN);for(y=(b=new k(R)).c=[],R=o+(l=t.e-i.e)+1,u||(u=a,l=w(t.e/h)-w(i.e/h),R=R/h|0),p=0;B[p]==(D[p]||0);p++);if(B[p]>(D[p]||0)&&l--,R<0)y.push(1),g=!0;else{for(x=D.length,_=B.length,p=0,R+=2,(d=f(u/(B[0]+1)))>1&&(B=e(B,d,u),D=e(D,d,u),_=B.length,x=D.length),A=_,N=(O=D.slice(0,_)).length;N<_;O[N++]=0);P=B.slice(),P=[0].concat(P),S=B[0],B[1]>=u/2&&S++;do{if(d=0,(c=r(B,O,_,N))<0){if(E=O[0],_!=N&&(E=E*u+(O[1]||0)),(d=f(E/S))>1)for(d>=u&&(d=u-1),v=(m=e(B,d,u)).length,N=O.length;1==r(m,O,v,N);)d--,n(m,_<v?P:B,v,u),v=m.length,c=1;else 0==d&&(c=d=1),v=(m=B.slice()).length;if(v<N&&(m=[0].concat(m)),n(O,m,N,u),N=O.length,-1==c)for(;r(B,O,_,N)<1;)d++,n(O,_<N?P:B,N,u),N=O.length}else 0===c&&(d++,O=[0]);y[p++]=d,O[0]?O[N++]=D[A]||0:(O=[D[A]],N=1)}while((A++<x||null!=O[0])&&R--);g=null!=O[0],y[0]||y.splice(0,1)}if(u==a){for(p=1,R=y[0];R>=10;R/=10,p++);V(b,o+(b.e=p+l*h-1)+1,s,g)}else b.e=l,b.r=+g;return b}}(),A=/^(-?)0([xbo])(?=\w[\w.]*$)/i,x=/^([^.]+)\.$/,S=/^\.([^.]+)$/,_=/^-?(Infinity|NaN)$/,P=/^\s*\+(?=[\w.])|^\s+|\s+$/g,i=function(e,r,n,t){var i,o=n?r:r.replace(P,"");if(_.test(o))e.s=isNaN(o)?null:o<0?-1:1;else{if(!n&&(o=o.replace(A,function(e,r,n){return i="x"==(n=n.toLowerCase())?16:"b"==n?2:8,t&&t!=i?e:r}),t&&(i=t,o=o.replace(x,"$1").replace(S,"0.$1")),r!=o))return new k(o,i);if(k.DEBUG)throw Error(c+"Not a"+(t?" base "+t:"")+" number: "+r);e.s=null}e.c=e.e=null},R.absoluteValue=R.abs=function(){var e=new k(this);return e.s<0&&(e.s=1),e},R.comparedTo=function(e,r){return b(this,new k(e,r))},R.decimalPlaces=R.dp=function(e,r){var n,t,i,o=this;if(null!=e)return y(e,0,m),null==r?r=L:y(r,0,8),V(new k(o),e+o.e+1,r);if(!(n=o.c))return null;if(t=((i=n.length-1)-w(this.e/h))*h,i=n[i])for(;i%10==0;i/=10,t--);return t<0&&(t=0),t},R.dividedBy=R.div=function(e,r){return n(this,new k(e,r),B,L)},R.dividedToIntegerBy=R.idiv=function(e,r){return n(this,new k(e,r),0,1)},R.exponentiatedBy=R.pow=function(e,r){var n,t,i,o,s,l,a,p,g=this;if((e=new k(e)).c&&!e.isInteger())throw Error(c+"Exponent not an integer: "+W(e));if(null!=r&&(r=new k(r)),s=e.e>14,!g.c||!g.c[0]||1==g.c[0]&&!g.e&&1==g.c.length||!e.c||!e.c[0])return p=new k(Math.pow(+W(g),s?2-O(e):+W(e))),r?p.mod(r):p;if(l=e.s<0,r){if(r.c?!r.c[0]:!r.s)return new k(NaN);(t=!l&&g.isInteger()&&r.isInteger())&&(g=g.mod(r))}else{if(e.e>9&&(g.e>0||g.e<-1||(0==g.e?g.c[0]>1||s&&g.c[1]>=24e7:g.c[0]<8e13||s&&g.c[0]<=9999975e7)))return o=g.s<0&&O(e)?-0:0,g.e>-1&&(o=1/o),new k(l?1/o:o);q&&(o=u(q/h+2))}for(s?(n=new k(.5),l&&(e.s=1),a=O(e)):a=(i=Math.abs(+W(e)))%2,p=new k(D);;){if(a){if(!(p=p.times(g)).c)break;o?p.c.length>o&&(p.c.length=o):t&&(p=p.mod(r))}if(i){if(0===(i=f(i/2)))break;a=i%2}else if(V(e=e.times(n),e.e+1,1),e.e>14)a=O(e);else{if(0==(i=+W(e)))break;a=i%2}g=g.times(g),o?g.c&&g.c.length>o&&(g.c.length=o):t&&(g=g.mod(r))}return t?p:(l&&(p=D.div(p)),r?p.mod(r):o?V(p,q,L,void 0):p)},R.integerValue=function(e){var r=new k(this);return null==e?e=L:y(e,0,8),V(r,r.e+1,e)},R.isEqualTo=R.eq=function(e,r){return 0===b(this,new k(e,r))},R.isFinite=function(){return!!this.c},R.isGreaterThan=R.gt=function(e,r){return b(this,new k(e,r))>0},R.isGreaterThanOrEqualTo=R.gte=function(e,r){return 1===(r=b(this,new k(e,r)))||0===r},R.isInteger=function(){return!!this.c&&w(this.e/h)>this.c.length-2},R.isLessThan=R.lt=function(e,r){return b(this,new k(e,r))<0},R.isLessThanOrEqualTo=R.lte=function(e,r){return-1===(r=b(this,new k(e,r)))||0===r},R.isNaN=function(){return!this.s},R.isNegative=function(){return this.s<0},R.isPositive=function(){return this.s>0},R.isZero=function(){return!!this.c&&0==this.c[0]},R.minus=function(e,r){var n,t,i,o,s=this,u=s.s;if(r=(e=new k(e,r)).s,!u||!r)return new k(NaN);if(u!=r)return e.s=-r,s.plus(e);var f=s.e/h,c=e.e/h,l=s.c,p=e.c;if(!f||!c){if(!l||!p)return l?(e.s=-r,e):new k(p?s:NaN);if(!l[0]||!p[0])return p[0]?(e.s=-r,e):new k(l[0]?s:3==L?-0:0)}if(f=w(f),c=w(c),l=l.slice(),u=f-c){for((o=u<0)?(u=-u,i=l):(c=f,i=p),i.reverse(),r=u;r--;i.push(0));i.reverse()}else for(t=(o=(u=l.length)<(r=p.length))?u:r,u=r=0;r<t;r++)if(l[r]!=p[r]){o=l[r]<p[r];break}if(o&&(i=l,l=p,p=i,e.s=-e.s),(r=(t=p.length)-(n=l.length))>0)for(;r--;l[n++]=0);for(r=a-1;t>u;){if(l[--t]<p[t]){for(n=t;n&&!l[--n];l[n]=r);--l[n],l[t]+=a}l[t]-=p[t]}for(;0==l[0];l.splice(0,1),--c);return l[0]?H(e,l,c):(e.s=3==L?-1:1,e.c=[e.e=0],e)},R.modulo=R.mod=function(e,r){var t,i,o=this;return e=new k(e,r),!o.c||!e.s||e.c&&!e.c[0]?new k(NaN):!e.c||o.c&&!o.c[0]?new k(o):(9==j?(i=e.s,e.s=1,t=n(o,e,0,3),e.s=i,t.s*=i):t=n(o,e,0,j),(e=o.minus(t.times(e))).c[0]||1!=j||(e.s=o.s),e)},R.multipliedBy=R.times=function(e,r){var n,t,i,o,s,u,f,c,l,p,g,m,v,b,y,O=this,N=O.c,E=(e=new k(e,r)).c;if(!(N&&E&&N[0]&&E[0]))return!O.s||!e.s||N&&!N[0]&&!E||E&&!E[0]&&!N?e.c=e.e=e.s=null:(e.s*=O.s,N&&E?(e.c=[0],e.e=0):e.c=e.e=null),e;for(t=w(O.e/h)+w(e.e/h),e.s*=O.s,(f=N.length)<(p=E.length)&&(v=N,N=E,E=v,i=f,f=p,p=i),i=f+p,v=[];i--;v.push(0));for(b=a,y=d,i=p;--i>=0;){for(n=0,g=E[i]%y,m=E[i]/y|0,o=i+(s=f);o>i;)n=((c=g*(c=N[--s]%y)+(u=m*c+(l=N[s]/y|0)*g)%y*y+v[o]+n)/b|0)+(u/y|0)+m*l,v[o--]=c%b;v[o]=n}return n?++t:v.splice(0,1),H(e,v,t)},R.negated=function(){var e=new k(this);return e.s=-e.s||null,e},R.plus=function(e,r){var n,t=this,i=t.s;if(r=(e=new k(e,r)).s,!i||!r)return new k(NaN);if(i!=r)return e.s=-r,t.minus(e);var o=t.e/h,s=e.e/h,u=t.c,f=e.c;if(!o||!s){if(!u||!f)return new k(i/0);if(!u[0]||!f[0])return f[0]?e:new k(u[0]?t:0*i)}if(o=w(o),s=w(s),u=u.slice(),i=o-s){for(i>0?(s=o,n=f):(i=-i,n=u),n.reverse();i--;n.push(0));n.reverse()}for((i=u.length)-(r=f.length)<0&&(n=f,f=u,u=n,r=i),i=0;r;)i=(u[--r]=u[r]+f[r]+i)/a|0,u[r]=a===u[r]?0:u[r]%a;return i&&(u=[i].concat(u),++s),H(e,u,s)},R.precision=R.sd=function(e,r){var n,t,i,o=this;if(null!=e&&e!==!!e)return y(e,1,m),null==r?r=L:y(r,0,8),V(new k(o),e,r);if(!(n=o.c))return null;if(t=(i=n.length-1)*h+1,i=n[i]){for(;i%10==0;i/=10,t--);for(i=n[0];i>=10;i/=10,t++);}return e&&o.e+1>t&&(t=o.e+1),t},R.shiftedBy=function(e){return y(e,-p,p),this.times("1e"+e)},R.squareRoot=R.sqrt=function(){var e,r,t,i,o,s=this,u=s.c,f=s.s,c=s.e,l=B+4,a=new k("0.5");if(1!==f||!u||!u[0])return new k(!f||f<0&&(!u||u[0])?NaN:u?s:1/0);if(0==(f=Math.sqrt(+W(s)))||f==1/0?(((r=v(u)).length+c)%2==0&&(r+="0"),f=Math.sqrt(+r),c=w((c+1)/2)-(c<0||c%2),t=new k(r=f==1/0?"1e"+c:(r=f.toExponential()).slice(0,r.indexOf("e")+1)+c)):t=new k(f+""),t.c[0])for((f=(c=t.e)+l)<3&&(f=0);;)if(o=t,t=a.times(o.plus(n(s,o,l,1))),v(o.c).slice(0,f)===(r=v(t.c)).slice(0,f)){if(t.e<c&&--f,"9999"!=(r=r.slice(f-3,f+1))&&(i||"4999"!=r)){+r&&(+r.slice(1)||"5"!=r.charAt(0))||(V(t,t.e+B+2,1),e=!t.times(t).eq(s));break}if(!i&&(V(o,o.e+B+2,0),o.times(o).eq(s))){t=o;break}l+=4,f+=4,i=1}return V(t,t.e+B+1,L,e)},R.toExponential=function(e,r){return null!=e&&(y(e,0,m),e++),z(this,e,r,1)},R.toFixed=function(e,r){return null!=e&&(y(e,0,m),e=e+this.e+1),z(this,e,r)},R.toFormat=function(e,r,n){var t,i=this;if(null==n)null!=e&&r&&"object"==typeof r?(n=r,r=null):e&&"object"==typeof e?(n=e,e=r=null):n=G;else if("object"!=typeof n)throw Error(c+"Argument not an object: "+n);if(t=i.toFixed(e,r),i.c){var o,s=t.split("."),u=+n.groupSize,f=+n.secondaryGroupSize,l=n.groupSeparator||"",a=s[0],h=s[1],p=i.s<0,g=p?a.slice(1):a,d=g.length;if(f&&(o=u,u=f,f=o,d-=o),u>0&&d>0){for(o=d%u||u,a=g.substr(0,o);o<d;o+=u)a+=l+g.substr(o,u);f>0&&(a+=l+g.slice(o)),p&&(a="-"+a)}t=h?a+(n.decimalSeparator||"")+((f=+n.fractionGroupSize)?h.replace(new RegExp("\\d{"+f+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):h):a}return(n.prefix||"")+t+(n.suffix||"")},R.toFraction=function(e){var r,t,i,o,s,u,f,l,a,p,d,m,w=this,b=w.c;if(null!=e&&(!(f=new k(e)).isInteger()&&(f.c||1!==f.s)||f.lt(D)))throw Error(c+"Argument "+(f.isInteger()?"out of range: ":"not an integer: ")+W(f));if(!b)return new k(w);for(r=new k(D),a=t=new k(D),i=l=new k(D),m=v(b),s=r.e=m.length-w.e-1,r.c[0]=g[(u=s%h)<0?h+u:u],e=!e||f.comparedTo(r)>0?s>0?r:a:f,u=U,U=1/0,f=new k(m),l.c[0]=0;p=n(f,r,0,1),1!=(o=t.plus(p.times(i))).comparedTo(e);)t=i,i=o,a=l.plus(p.times(o=a)),l=o,r=f.minus(p.times(o=r)),f=o;return o=n(e.minus(t),i,0,1),l=l.plus(o.times(a)),t=t.plus(o.times(i)),l.s=a.s=w.s,d=n(a,i,s*=2,L).minus(w).abs().comparedTo(n(l,t,s,L).minus(w).abs())<1?[a,i]:[l,t],U=u,d},R.toNumber=function(){return+W(this)},R.toPrecision=function(e,r){return null!=e&&y(e,1,m),z(this,e,r,2)},R.toString=function(e){var r,n=this,i=n.s,o=n.e;return null===o?i?(r="Infinity",i<0&&(r="-"+r)):r="NaN":(null==e?r=o<=T||o>=I?N(v(n.c),o):E(v(n.c),o,"0"):10===e?r=E(v((n=V(new k(n),B+o+1,L)).c),n.e,"0"):(y(e,2,F.length,"Base"),r=t(E(v(n.c),o,"0"),10,e,i,!0)),i<0&&n.c[0]&&(r="-"+r)),r},R.valueOf=R.toJSON=function(){return W(this)},R._isBigNumber=!0,null!=r&&k.set(r),k}()).default=o.BigNumber=o,void 0===(t=function(){return o}.call(r,n,r,e))||(e.exports=t)}()},function(e,r,n){"use strict";var t=n(2);n(3)(t.readFileSync("/dev/stdin","utf8"))},function(e,r){e.exports=require("fs")},function(e,r,n){"use strict";var t=n(4),i=n(6);e.exports=function(e){var r=new t(e);i(r)}},function(e,r,n){"use strict";var t=n(5);e.exports=class{constructor(e){var r=e.trim().split(/\s+/g);this.inp=new t(r)}inr(){return this.inp.deq()}in(){return parseInt(this.inp.deq(),10)}fin(){this.inp.clear()}}},function(e,r,n){"use strict";e.exports=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];this.size=e.length,this.items=e,this.ind=0}enq(e){this.size+=1,this.items.push(e)}deq(){var e=this.items[this.ind];return this.size-=1,this.ind+=1,e}clear(){this.items=[],this.size=0,this.ind=0}}},function(e,r,n){"use strict";var t=n(0),i=n(7);e.exports=function(e){for(var r=e.in(),n=new Array(r),o=0;o<r;o++)n[o]=e.in();if(0==n[0])if(n.sort(function(e,r){return e-r}),0!=n[1]){for(var s=0,u=1,f=[],c=1;c<r;c++)if(n[c]==s)u++;else{if(n[c]!=s+1)return void console.log(0);s++,f.push(u),u=1}f.push(u);for(var l=new t(1),a=f.length,h=1;h<a;h++){var p=i(new t(f[h-1]),new t(f[h]),998244353);l=l.times(p).mod(998244353)}console.log(l.toString())}else console.log(0);else console.log(0)}},function(e,r,n){"use strict";var t=n(0);e.exports=function e(r,n,i){if(0==n.comparedTo(0))return new t(1);if(0==n.mod(2)){var o=e(r,n.idiv(2),i);return o.times(o).mod(i)}return r.times(e(r,n.minus(1),i)).mod(i)}}]);

Score : 300 points

Problem Statement

Given is an integer sequence D_1,...,D_N of N elements. Find the number, modulo 998244353, of trees with N vertices numbered 1 to N that satisfy the following condition:

For every integer i from 1 to N, the distance between Vertex 1 and Vertex i is D_i.

Notes

A tree of N vertices is a connected undirected graph with N vertices and N-1 edges, and the distance between two vertices are the number of edges in the shortest path between them.

Two trees are considered different if and only if there are two vertices x and y such that there is an edge between x and y in one of those trees and not in the other.

Constraints

1 \leq N \leq 10^5

0 \leq D_i \leq N-1

Input

Input is given from Standard Input in the following format:

N
D_1 D_2 ... D_N

Output

Print the answer.

Sample Input 1

4
0 1 1 2

Sample Output 1

2

For example, a tree with edges (1,2), (1,3), and (2,4) satisfies the condition.

Sample Input 2

4
1 1 1 1

Sample Output 2

0

Sample Input 3

7
0 3 2 1 2 2 1

Sample Output 3

24


'use strict'
function main(input) {
  for(let i = 1; i < 10; i++) {
    for (let j = 1; j < 10; j++) {
      if(i * j == input) {
        console.log('Yes')
        return true
      }
    }
  }
  console.log('No')
  return true

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

Score : 200 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together.

Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print Yes; if it cannot, print No.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N can be represented as the product of two integers between 1 and 9 (inclusive), print Yes; if it cannot, print No.

Sample Input 1

10

Sample Output 1

Yes

10 can be represented as, for example, 2 \times 5.

Sample Input 2

50

Sample Output 2

No

50 cannot be represented as the product of two integers between 1 and 9.

Sample Input 3

81

Sample Output 3

Yes


'use strict';
const main = input => {
  const n = parseInt(input[0]);
  let check = 0
  for(let i=1; i<=9; i++) {
    if (n%i == 0 && n/i <= 9) {
      check = 1;
      break;
    }
  }
  console.log(check==1?'Yes':'No');

}
main(require("fs").readFileSync("/dev/stdin", "utf8").split('\n'));


var GET = (function () {function f(s) {return new g(s);}function g(s) {this._s = s.trim().split("\n");}g.prototype.getValue = function (n) {return this._s[n];};g.prototype.getArray = function (n) {return this.stoa(this._s[n]);};g.prototype.slice = function (s, limit) {return this._s.slice(s, +limit + s || undefined).map(v => this.stox(v));};g.prototype.sliceArray = function (s, limit) {return this._s.slice(s, +limit + s || undefined).map(v => this.stoa(v));};g.prototype.stoa = function (s) {return s.split(" ").map(v => this.stox(v));};g.prototype.stox = function (v) {var i = +v;return (i === i) ? i : v;};return f;})();
var o = GET(require("fs").readFileSync("/dev/stdin", "utf8"));
function PriorityQueue(){this.heap = [];}PriorityQueue.prototype = {push : function(x){var h = this.heap, i = h.length++, j;while(i){j = i-1 >> 1;if(h[j] <= x)break;h[i] = h[j];i = j;}h[i] = x;}, pop : function(){var h = this.heap, r = h[0], x = h.pop();var i = 0, k = h.length >> 1, j;while (i < k) {j = (i << 1) + 1;if(h[j+1] < h[j])++j;if(x <= h[j])break;h[i] = h[j];i = j;}if(h.length)h[i] = x;return r;}, size : function(){return this.heap.length;}, top : function(){return this.heap[0];},};

console.log(main());
function main(){
    var N = o.getValue(0);

    var ans = 0;
    for (var i = 1; i * i < N; i++) {
        if (N % i !== 0) continue;
        var j = N / i;
        if (ans === 0) {
            ans = i+j-2;
        } else {
            ans = Math.min(ans, i + j - 2);
        }
    }

    return ans;
}

Score : 300 points

Problem Statement

Takahashi is standing on a multiplication table with infinitely many rows and columns.

The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).

In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).

Given an integer N, find the minimum number of moves needed to reach a square that contains N.

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum number of moves needed to reach a square that contains the integer N.

Sample Input 1

10

Sample Output 1

5

(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves.

Sample Input 2

50

Sample Output 2

13

(5, 10) can be reached in 13 moves.

Sample Input 3

10000000019

Sample Output 3

10000000018

Both input and output may be enormous.


//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");
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr("time : " + end + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return 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 one = nextIntArray();
  var a = one[0];
  var b = one[1];
  var x = one[2] / a;
  if(a * b / 2 > x){
    var diffA = x * 2 / b;
    var kakudo = Math.atan(b / diffA) * 180 / Math.PI;
    myout(kakudo);
  }else{
    var diffB = b - (2 * x / a - b);
    var kakudo = Math.atan(diffB / a) * 180 / Math.PI;
    myout(kakudo);
  }
}

Score : 400 points

Problem Statement

Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)

We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.

When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.

Constraints

All values in input are integers.

1 \leq a \leq 100

1 \leq b \leq 100

1 \leq x \leq a^2b

Input

Input is given from Standard Input in the following format:

a b x

Output

Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

2 2 4

Sample Output 1

45.0000000000

This bottle has a cubic shape, and it is half-full. The water gets spilled when we tilt the bottle more than 45 degrees.

Sample Input 2

12 21 10

Sample Output 2

89.7834636934

This bottle is almost empty. When the water gets spilled, the bottle is nearly horizontal.

Sample Input 3

3 1 8

Sample Output 3

4.2363947991

This bottle is almost full. When the water gets spilled, the bottle is still nearly vertical.


"use strict";

const main = args => {

    const input = args.trim().split(" ");
    const a = parseInt(input[0]);
    const b = parseInt(input[1]);

    console.log(Math.max(0, a - 2 * b));
}

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

Score : 100 points

Problem Statement

The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)

We will close the window so as to minimize the total horizontal length of the uncovered part of the window.
Find the total horizontal length of the uncovered parts of the window then.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the total horizontal length of the uncovered parts of the window.

Sample Input 1

12 4

Sample Output 1

4

We have a window with a horizontal length of 12, and two curtains, each of length 4, that cover both ends of the window, for example. The uncovered part has a horizontal length of 4.

Sample Input 2

20 15

Sample Output 2

0

If the window is completely covered, print 0.

Sample Input 3

20 30

Sample Output 3

0

Each curtain may be longer than the window.


'use strict'

const main = input => {
	const args = input.split('\n').map(arg => arg.split(' '))
	const A = parseInt(args[0][0], 10)
	const B = parseInt(args[0][1], 10)

	const t1 = A - (B * 2)

	if (t1 < 0) console.log(0)
	else console.log(t1)
}

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


function Main(input){
  inputs=input.split("\n");
  takos=inputs[1].split(" ");
  sums=takos.map(x=>parseInt(x)).reduce((sum,value)=>sum+value);
  points=takos.map(value=>{
    sums-=value;
    return value*sums;
  });
  console.log(points.reduce((sum,value)=>sum+value));
}
Main(require('fs').readFileSync('/dev/stdin','utf8'));

Score : 200 points

Problem Statement

It's now the season of TAKOYAKI FESTIVAL!

This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i.

As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points.

There are \frac{N \times (N - 1)}{2} ways to choose two from the N takoyaki served in the festival. For each of these choices, find the health points restored from eating the two takoyaki, then compute the sum of these \frac{N \times (N - 1)}{2} values.

Constraints

All values in input are integers.

2 \leq N \leq 50

0 \leq d_i \leq 100

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the sum of the health points restored from eating two takoyaki over all possible choices of two takoyaki from the N takoyaki served.

Sample Input 1

3
3 1 2

Sample Output 1

11

There are three possible choices:

Eat the first and second takoyaki. You will restore 3 health points.

Eat the second and third takoyaki. You will restore 2 health points.

Eat the first and third takoyaki. You will restore 6 health points.

The sum of these values is 11.

Sample Input 2

7
5 0 7 8 3 3 2

Sample Output 2

312


function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim();}
function myout(t){console.log(t);}//standard output
//[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,3);
  var list = myconv(input[1],6);
  var tmpList = [list[0]];
  for(var i = 1; i < list.length; i++){
    var mae = list[i-1];
    var ato = list[i];
    if(mae == ato){

       }else{
        tmpList.push(list[i]);
       }
  }
  myout(tmpList.length);
}

Main(myin());

Score : 300 points

Problem Statement

There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S.

Adjacent slimes with the same color will fuse into one larger slime without changing the color. If there were a slime adjacent to this group of slimes before fusion, that slime is now adjacent to the new larger slime.

Ultimately, how many slimes will be there?

Constraints

1 \leq N \leq 10^5

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the final number of slimes.

Sample Input 1

10
aabbbbaaca

Sample Output 1

5

Ultimately, these slimes will fuse into abaca.

Sample Input 2

5
aaaaa

Sample Output 2

1

All the slimes will fuse into one.

Sample Input 3

20
xxzaffeeeeddfkkkkllq

Sample Output 3

10


function Main(input) {
  input = input.split("\n");
var p = input[0];
var line2 = input[1].split(" ");
var tyoubo = (new Array(p-1+1)).fill('0');
  for (var j = 0; j < input[0]; j++) {
  tyoubo.splice(line2[j], 1, j);
    }
   tyoubo.splice(0, 1);
console.log(tyoubo.join(" "))
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

Given is an integer N.

Takahashi chooses an integer a from the positive integers not greater than N with equal probability.

Find the probability that a is odd.

Constraints

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the probability that a is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

4

Sample Output 1

0.5000000000

There are four positive integers not greater than 4: 1, 2, 3, and 4. Among them, we have two odd numbers: 1 and 3. Thus, the answer is \frac{2}{4} = 0.5.

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000


public class some_thing1 {
	public  static void main(String[] args) {
	int a = 5;
	double kisu = 1/a;
	double kikazu = Math.ceil(a/2);
	double kakuritu = kisu * kikazu;
	System.out.println( kakuritu );
	}
}


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	s = input[0].split(' ').map((n) => (parseInt(n)))[1]
	input = input[1].split(' ').map((n) => (parseInt(n)))
	ans = input.filter((n) => (s <= n)).length

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

Score : 200 points

Problem Statement

N friends of Takahashi has come to a theme park.

To ride the most popular roller coaster in the park, you must be at least K centimeters tall.

The i-th friend is h_i centimeters tall.

How many of the Takahashi's friends can ride the roller coaster?

Constraints

1 \le N \le 10^5

1 \le K \le 500

1 \le h_i \le 500

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the number of people among the Takahashi's friends who can ride the roller coaster.

Sample Input 1

4 150
150 140 100 200

Sample Output 1

2

Two of them can ride the roller coaster: the first and fourth friends.

Sample Input 2

1 500
499

Sample Output 2

0

Sample Input 3

5 1
100 200 300 400 500

Sample Output 3

5


function Main(input) {
    input = input.split("\n");
    var N = input[0].split(" ")[0];
    var K = input[0].split(" ")[1];
    var h = input[1].split(" ");
    var res = 0;

    for(var i = 0; i < N; i++){
        h[i] = parseInt(h[i]);
        if(K <= h[i]){
            res++
        }
    }
    console.log(res);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(arg) {

    var N = arg.split("\n")[0].split(" ")[0]-0;
    var K = arg.split("\n")[0].split(" ")[1]-0;

    var h = arg.split("\n")[1].split(" ").map(v => v - 0);

    var ans = h.filter(val => val >= K).length;

    console.log(ans);
}

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


Main = input => {
  input = input.split("\n");
  const n = Number(input[0]);
  const a = input[1].split(" ").map(x => Number(x));

  const ans = new Array(n);
  a.forEach((x, id) => {
    ans[x-1] = id+1;
  });

  const result = [];
  ans.forEach(x => result.push(x));

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

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

Score : 300 points

Problem Statement

Takahashi is a teacher responsible for a class of N students.

The students are given distinct student numbers from 1 to N.

Today, all the students entered the classroom at different times.

According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including student number i).

From these records, reconstruct the order in which the students entered the classroom.

Constraints

1 \le N \le 10^5

1 \le A_i \le N

A_i \neq A_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print the student numbers of the students in the order the students entered the classroom.

Sample Input 1

3
2 3 1

Sample Output 1

3 1 2

First, student number 3 entered the classroom.

Then, student number 1 entered the classroom.

Finally, student number 2 entered the classroom.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

1 2 3 4 5

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

8 2 4 5 6 7 3 1


"use strict";

main(require("fs").readFileSync("/dev/stdin", "UTF-8"));

function main(input) {
  let students_num = parseInt(input.split("\n")[0]); //生徒数
  let arrive_num_order_by_student_num = input.split("\n")[1].split(" "); //学番の順の到着順(配列)

  let result = new Array(students_num); //出力

  for (let i = 0; i < students_num; i++) {
    result[parseInt(arrive_num_order_by_student_num[i]) - 1] = i + 1;
  }

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


function main(stdin) {
  var splitByN = stdin.split('\n');
  var N = Number(splitByN[0]) //生徒数
  var order = splitByN[1]; //登校順の記録
  var orderArray = order.split(' ');
  var array = new Array(N); //入れ子をまず準備
  for (let i = 0; i < orderArray.length; i++) {
    array[orderArray[i] - 1] = i + 1;
  }
  return array;
}

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


function getPrimeFactors(n) {
    if (n < 2) return [];
    if (n === 2 || n === 3 || n === 5) return [n];
    if (n % 2 === 0) return [2].concat(getPrimeFactors(n/2));
    if (n % 3 === 0) return [3].concat(getPrimeFactors(n/3));
    if (n % 5 === 0) return [5].concat(getPrimeFactors(n/5));
    let prime = 7;
    let step = 4;
    const limit = Math.sqrt(n);
    while (prime <= limit) {
      if (n % prime === 0) return [prime].concat(getPrimeFactors(n/prime));
      prime += step;
      step = 6 - step;
    }
    return [n];
};

function main(input) {
    const args = input.split(' ')
    const n1 = args[0], n2 = args[1]
    const a = Array.from(new Set(getPrimeFactors(n1)))
    const b = Array.from(new Set(getPrimeFactors(n2)))
    console.log(a.map( x => b.find( y => x == y)).filter(Boolean).length + 1)
}

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

Score : 400 points

Problem Statement

Given are positive integers A and B.

Let us choose some number of positive common divisors of A and B.

Here, any two of the chosen divisors must be coprime.

At most, how many divisors can we choose?

Definition of common divisor

An integer d is said to be a common divisor of integers x and y when d divides both x and y.

Definition of being coprime

Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.

Definition of dividing

An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.

Constraints

All values in input are integers.

1 \leq A, B \leq 10^{12}

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of divisors that can be chosen to satisfy the condition.

Sample Input 1

12 18

Sample Output 1

3

12 and 18 have the following positive common divisors: 1, 2, 3, and 6.

1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.

Sample Input 2

420 660

Sample Output 2

4

Sample Input 3

1 2019

Sample Output 3

1

1 and 2019 have no positive common divisors other than 1.


'use strict'

class Main {
  solve() {
    const arr = input.nextIntArr();
    const a = arr[0];
    const b = arr[1];
    if (a == 1 && b == 1) { return 1; }
    const prime = new Prime();
    const f1 = prime.getFactor(a);
    const f2 = prime.getFactor(b);
    const arr1 = _.sort(_.uniq(f1));
    const arr2 = _.sort(_.uniq(f2));
    let i = 0,j = 0;
    let counter = 0;
    while (i < arr1.length && j < arr2.length) {
      if (arr1[i] == arr2[j]) { ++counter; ++i; ++j; }
      else if (arr1[i] < arr2[j]) { ++i; }
      else { ++j; }
    }
    return counter + 1;
  }
}

class Prime {
  /* 初期化と素数テーブル生成 */
  constructor(n) {
    if (n == null) { n = 1e6; }
    const primeTable = [...((new Array(n)).keys())];
    primeTable[0] = false;
    primeTable[1] = false;
    let max = Math.sqrt(n);
    for(let i = 2;i <= max;++i) {
      if (primeTable[i] !== i) continue;
      for (let j = i * i; j < n; j += i) {
        if (primeTable[j] !== j) continue;
        primeTable[j] = i;
      }
    }
    this.size = n;
    this.primeTable = primeTable;
    this.primeList = primeTable.filter((e,i) => e === i);
  }

  /* テーブルに生成した素数の2乗までの素数判定 */
  isPrime(n) {
    if (n < this.size) return this.primeTable[n] === n;
    let max = Math.sqrt(n);
    for (let i = 0; this.primeList[i] <= max; ++i) {
      if (n % this.primeList[i] === 0) return false;
    }
    return true;
  }

  /* 最小の素因数 */
  getMinimumFactor(n) {
    if (n < this.size) return this.primeTable[n];
    let max = Math.sqrt(n);
    for (let i = 0; this.primeList[i] <= max; ++i) {
      if (n % this.primeList[i] === 0) return this.primeList[i];
    }
    return n;
  }

  /* 素因数の取得
   * 上限: テーブルサイズの二乗*/
  getFactor(n) {
    const ret = [];
    let k = n;
    while(!this.isPrime(k)) {
      const p = this.getMinimumFactor(k)
      ret.push(p);
      k /= p;
    }
    ret.push(k);
    return ret;
  }

  /* 上限: テーブルサイズ*/
  getFactorTable(n) {
    const factor = this.getFactor(n);
    const maxFactor = factor[factor.length - 1];
    const ret = [];
    for (let i = 0;this.primeList[i] <= maxFactor; ++i) {
      ret[this.primeList[i]] = 0;
    }
    for (const e of factor) { ++ret[e]; }
    return ret;
  }

  /* 約数の個数 */
  getDivisorCount(n) {
    const factor = this.getFactor(n);
    let count = 1;
    let prev = factor[0];
    let factorCount = [];
    for (let i = 1; i < factor.length; ++i) {
      if (factor[i] != prev) {
        factorCount.push(count);
        count = 1;
      }
      else {
        ++count;
      }
      prev = factor[i];
    }
    factorCount.push(count);
    return factorCount.reduce((a,b)=>a * (b+1),1);
  }

  /* 約数の一覧の取得(未ソート) O(√n)*/
  static getDivisors(n) {
    let max = Math.sqrt(n);
    let ret = [];
    if (n % max === 0) {ret.push(max);}
    for(let i = 0; i < max; ++i) {
      if (n % i == 0) {
        ret.push(i);
        ret.push(n / i);
      }
    }
    return ret;
  }
}

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; }
   /* 二分探索による配列検索 */
   binarySearch (array, key, iteratee) {
     const itr = (obj) => (typeof obj === 'object') ? obj[iteratee] : obj;
     const value = itr(obj);
     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)));
  }
}

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();
const input = new Input();
out.write(new Main().solve());


//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');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
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 one = nextIntArray();
  var N = one[0];
  var M = one[1];
  var dp = new Array(1 << N);
  dp[0] = 0;
  for(var i = 0; i < M; i++){
  	var tmp = nextIntArray();
  	var cost = tmp[0];
  	var size = tmp[1];
  	var keys = nextIntArray();
  	var sumKeys = 0;
  	for(var j = 0; j < size; j++){
  		sumKeys += Math.pow(2, keys[j] - 1);
  	}
  	var ato = makeClone(dp);
  	for(var j = 0; j < (1 << N); j++){
  		if(dp[j] != null){
  			if(dp[j | sumKeys] == null){
  				ato[j | sumKeys] = dp[j] + cost;
  			}else{
  				ato[j | sumKeys] = Math.min((dp[j] + cost), ato[j | sumKeys]);
  			}
  		}
  	}
  	dp = ato;
  }
  myout((dp[(1 << N) - 1] == null) ? "-1" : dp[(1 << N) - 1]);
}

Score : 500 points

Problem Statement

We have N locked treasure boxes, numbered 1 to N.

A shop sells M keys. The i-th key is sold for a_i yen (the currency of Japan), and it can unlock b_i of the boxes: Box c_{i1}, c_{i2}, ..., c_{i{b_i}}. Each key purchased can be used any number of times.

Find the minimum cost required to unlock all the treasure boxes. If it is impossible to unlock all of them, print -1.

Constraints

All values in input are integers.

1 \leq N \leq 12

1 \leq M \leq 10^3

1 \leq a_i \leq 10^5

1 \leq b_i \leq N

1 \leq c_{i1} < c_{i2} < ... < c_{i{b_i}} \leq N

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
c_{11} c_{12} ... c_{1{b_1}}
:
a_M b_M
c_{M1} c_{M2} ... c_{M{b_M}}

Output

Print the minimum cost required to unlock all the treasure boxes.
If it is impossible to unlock all of them, print -1.

Sample Input 1

2 3
10 1
1
15 1
2
30 2
1 2

Sample Output 1

25

We can unlock all the boxes by purchasing the first and second keys, at the cost of 25 yen, which is the minimum cost required.

Sample Input 2

12 1
100000 1
2

Sample Output 2

-1

We cannot unlock all the boxes.

Sample Input 3

4 6
67786 3
1 3 4
3497 1
2
44908 3
2 3 4
2156 3
2 3 4
26230 1
2
86918 1
3

Sample Output 3

69942


var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}
var n,m,g;

console.log(main());
function main(){
  n = o.a();
  m = o.a();
  var a = o.m(m);
  g = xArray("[]",n);
  for(var i = 0; i < m; i++){
    g[a[i][0]-1].push(a[i][1]-1);
  }
  var ans = Array(n+1);
  for(i = 0; i < n; i++){
    var u = solve(i);
    if(u && u.length < ans.length)ans = u;
  }
  if(ans.length === n+1)return -1;
  console.log(ans.length);
  return ans.join("\n");
}

function solve(v){
  var map = xArray(-1,n);
  var q = [v];
  while(q.length){
    var q2 = [];
    while(q.length){
      var t = q.pop();
      for(var V of g[t]){
        if(V === v){
          var res = [V+1];
          V = t;
          while(V !== v){
            res.push(V+1);
            V = map[V];
          }
          return res;
        }
        if(map[V] !== -1)continue;
        map[V] = t;
        q2.push(V);
      }
    }
    q = q2;
  }
}

Score : 600 points

Problem Statement

Given is a directed graph G with N vertices and M edges.

The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i.

It is guaranteed that the graph contains no self-loops or multiple edges.

Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph.

Here the null graph is not considered as a subgraph.

Notes

For a directed graph G = (V, E), we call a directed graph G' = (V', E') satisfying the following conditions an induced subgraph of G:

V' is a (non-empty) subset of V.

E' is the set of all the edges in E that have both endpoints in V'.

Constraints

1 \leq N \leq 1000

0 \leq M \leq 2000

1 \leq A_i,B_i \leq N

A_i \neq B_i

All pairs (A_i, B_i) are distinct.

All values in input are integers.

Input

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

If there is no induced subgraph of G that satisfies the condition, print -1.
Otherwise, print an induced subgraph of G that satisfies the condition, in the following format:

K
v_1
v_2
:
v_K

This represents the induced subgraph of G with K vertices whose vertex set is \{v_1, v_2, \ldots, v_K\}. (The order of v_1, v_2, \ldots, v_K does not matter.)
If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted.

Sample Input 1

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

Sample Output 1

3
1
2
4

The induced subgraph of G whose vertex set is \{1, 2, 4\} has the edge set \{(1, 2), (2, 4), (4, 1)\}. The in-degree and out-degree of every vertex in this graph are both 1.

Sample Input 2

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

Sample Output 2

-1

There is no induced subgraph of G that satisfies the condition.

Sample Input 3

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

Sample Output 3

4
2
3
4
5


function Main(arg) {

    var N = arg.split("\n")[0].split(" ")[0]-0;
    var K = arg.split("\n")[0].split(" ")[1]-0;
    var P = arg.split("\n")[1].split(" ").map(v => v-0);

    var ans = [];
    for (var i = 0; i < N - K + 1; i++){
        var tmp = P.slice(i, i + K);
        tmp.sort(compareNumbers);
        ans[i] = P.slice(0, i).concat(tmp).concat(P.slice(i + K)).toString();
    }

    var aa = new Set(ans);

    console.log(aa.size);
}

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

Score : 700 points

Problem Statement

Snuke has a permutation (P_0,P_1,\cdots,P_{N-1}) of (0,1,\cdots,N-1).

Now, he will perform the following operation exactly once:

Choose K consecutive elements in P and sort them in ascending order.

Find the number of permutations that can be produced as P after the operation.

Constraints

2 \leq N \leq 200000

2 \leq K \leq N

0 \leq P_i \leq N-1

P_0,P_1,\cdots,P_{N-1} are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_0 P_1 \cdots P_{N-1}

Output

Print the number of permutations that can be produced as P after the operation.

Sample Input 1

5 3
0 2 1 4 3

Sample Output 1

2

Two permutations can be produced as P after the operation: (0,1,2,4,3) and (0,2,1,3,4).

Sample Input 2

4 4
0 1 2 3

Sample Output 2

1

Sample Input 3

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

Sample Output 3

6


function Main(arg) {

    var N = arg.split("\n")[0].split(" ")[0]-0;
    var K = arg.split("\n")[0].split(" ")[1]-0;
    var P = arg.split("\n")[1].split(" ").map(v => v-0);

    var ans = [];
    for (var i = 0; i < N - K + 1; i++){
        var tmp = P.slice(i, i + K);
        tmp.sort(compareNumbers);
        ans[i] = P.slice(0, i).concat(tmp).concat(P.slice(i + K)).toString();
    }

    var aa = new Set(ans);

    console.log(aa.length);
}

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


function Main(input) {
	input =  input.split("\n");
	var turn = ['Sunny','Cloudy','Rainy'];
	var nextnum = 0;

  	for (var i = 0; i < turn.length; i++){
		if (input[0] === turn[i]) {
			nextnum = i + 1;
			if (nextnum === turn.length) {
				nextnum = 0;
			}
			break;
		}
	}

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

Score: 100 points

Problem Statement

The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...

Given is a string S representing the weather in the town today. Predict the weather tomorrow.

Constraints

S is Sunny, Cloudy, or Rainy.

Input

Input is given from Standard Input in the following format:

S

Output

Print a string representing the expected weather tomorrow, in the same format in which input is given.

Sample Input 1

Sunny

Sample Output 1

Cloudy

In Takahashi's town, a sunny day is followed by a cloudy day.

Sample Input 2

Rainy

Sample Output 2

Sunny


let input = "Sunny"
let weList = {
    "Sunny" :1,
    "Cloudy":2,
    "Rainy":3
}
let wetList = {
    1:"Sunny",
    2:"Cloudy",
    3:"Rainy"
}

function main (input) {
    let num = weList[input]%3
    console.log(wetList[num+1])
}

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 tenki = ["Sunny","Cloudy","Rainy","Sunny"];
  tenki.for(i = 0; i > 3;i++){
    if(inputs[0] == tenki[i]){console.log(tenki[i+1])}
  })
}


function main(arg) {
	arg = arg.trim();
  	var s = arg.length;
  	var out = 'Yes';
 	for (var i = 0; i < s; i++) {
    	var num = arg[i];
      	var index = i + 1;
      	if (index%2 === 0 && num === 'R') {
              	return console.log('No');
        } else if (index%2 === 1 && num === 'L'){
        		return console.log('No');
        }
    }
  	console.log(out)
}

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

Score: 200 points

Problem Statement

Takahashi will do a tap dance. The dance is described by a string S where each character is L, R, U, or D. These characters indicate the positions on which Takahashi should step. He will follow these instructions one by one in order, starting with the first character.

S is said to be easily playable if and only if it satisfies both of the following conditions:

Every character in an odd position (1-st, 3-rd, 5-th, \ldots) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th, \ldots) is L, U, or D.

Your task is to print Yes if S is easily playable, and No otherwise.

Constraints

S is a string of length between 1 and 100 (inclusive).

Each character of S is L, R, U, or D.

Input

Input is given from Standard Input in the following format:

S

Output

Print Yes if S is easily playable, and No otherwise.

Sample Input 1

RUDLUDR

Sample Output 1

Yes

Every character in an odd position (1-st, 3-rd, 5-th, 7-th) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th) is L, U, or D.

Thus, S is easily playable.

Sample Input 2

DULL

Sample Output 2

No

The 3-rd character is not R, U, nor D, so S is not easily playable.

Sample Input 3

UUUUUUUUUUUUUUU

Sample Output 3

Yes

Sample Input 4

ULURU

Sample Output 4

No

Sample Input 5

RDULULDURURLRDULRLR

Sample Output 5

Yes


function main(arg) {
	arg = arg.trim();
  	var s = arg.length;
  	var out = '';
  for (var i = 0; i < s; i++) {
    var num = arg[i];
  	if (i%2 === 0) {
    	if (num === 'R' || num === 'U' || num === 'D') {
        	out = 'Yes'
        } else {
        	out = 'No'
        }
    } else if (i%2 === 1) {
    	if (num === 'R' || num === 'U' || num === 'D') {
        	out = 'Yes'
        } else {
        	out = 'No'
        }
    }
  }

	console.log(out)
}

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


"use strict";

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

    let answer = "Yes";

    for(let i in S) {
        if(i % 2 === 0 && S[i] === "L") {
            answer = "No";
            break;
        }

        if(i % 2 !== 0 && S[i] === "R") {
            answer = "No";
            break;
        }
    }

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


const main = (inputs) => {
  var array = String(inputs[0]).split('');
  for(var i = 0; i < array.length; i++){
    if((i+1)%2 === 0){
      if(array[i] === 'R' || array[i] === 'U' || array[i] === 'D'){

      }
      else{
        console.log('No');
        return false;
      }
    }
    else{
      if(array[i] === 'L' || array[i] === 'U' || array[i] === 'D'){

      }

      else{
        console.log('No');
        return false;
      }
    }
  }
  console.log('Yes');
}

main(require('fs').readFileSync('/dev/stdin', 'UTF-8').trim().split("\n"));


function myout(text){console.log(text);}//standard output
function Main(input) {
	input = input.trim();
	//input = parseInt(input.trim());
	//input = input.trim().split(" ");
	input = input.trim().split("\n");
	//input = input.trim().split(" ").map((a)=>Number(a));
	//input = input.trim().split("\n").map((a)=>Number(a));
  var N = parseInt(input[0].split(" ")[0]);
  var K = parseInt(input[0].split(" ")[1]);
  var Q = parseInt(input[0].split(" ")[2]);
  input.shift();
  input = input.map((a)=>Number(a));
  var pointList = new Array(N);
  pointList.fill(0);
  for(var i = 0; i < input.length; i++){
    pointList[input[i] - 1]++;
  }
  for(var i = 0; i < pointList.length; i++){
    if(Q - pointList[i] < K){
       myout("Yes");
       }else{
       myout("No");
       }
  }
}

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

Score: 300 points

Problem Statement

Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.

A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K points.

When a player correctly answers a question, each of the other N-1 players receives minus one (-1) point. There is no other factor that affects the players' scores.

At the end of a game, the players with 0 points or lower are eliminated, and the remaining players survive.

In the last game, the players gave a total of Q correct answers, the i-th of which was given by Player A_i.
For Kizahashi, write a program that determines whether each of the N players survived this game.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 10^9

1 \leq Q \leq 10^5

1 \leq A_i \leq N\ (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N K Q
A_1
A_2
.
.
.
A_Q

Output

Print N lines. The i-th line should contain Yes if Player i survived the game, and No otherwise.

Sample Input 1

6 3 4
3
1
3
2

Sample Output 1

No
No
Yes
No
No
No

In the beginning, the players' scores are (3, 3, 3, 3, 3, 3).

Player 3 correctly answers a question. The players' scores are now (2, 2, 3, 2, 2, 2).

Player 1 correctly answers a question. The players' scores are now (2, 1, 2, 1, 1, 1).

Player 3 correctly answers a question. The players' scores are now (1, 0, 2, 0, 0, 0).

Player 2 correctly answers a question. The players' scores are now (0, 0, 1, -1, -1, -1).

Players 1, 2, 4, 5 and 6, who have 0 points or lower, are eliminated, and Player 3 survives this game.

Sample Input 2

6 5 4
3
1
3
2

Sample Output 2

Yes
Yes
Yes
Yes
Yes
Yes

Sample Input 3

10 13 15
3
1
4
1
5
9
2
6
5
3
5
8
9
7
9

Sample Output 3

No
No
No
No
Yes
No
No
No
Yes
No


var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}

console.log(main());
function main(){
  var n = o.a();
  var k = o.a();
  var q = o.a();
  var a = o.r(q);
  var b = xArray(0,n);
  for(var i = 0; i < q; i++){
    b[a[i]-1]++;
  }
  var ans = [];
  for(var i = 0; i < n; i++){
    var s = "No";
    if(k+b[i]>q)s = "Yes";
    ans.push(s);
  }
  return ans.join("\n");
}


function Main(input) {
	var S = input;

	console.log(Math.pow(S, 3));

}

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

Score : 100 points

Problem Statement

Takahashi is going to set a 3-character password.

How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?

Constraints

1 \leq N \leq 9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of possible passwords.

Sample Input 1

2

Sample Output 1

8

There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.

Sample Input 2

1

Sample Output 2

1

There is only one possible password if you can only use one kind of character.


function Main(input) {
    var N = parseInt(input[0], 10);

    console.log(N*N*N);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8").trim().split(/\n|\s/));


"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function() {return this.index < this.max},
        "next": function() { if (!this.hasNext()) {throw "ArrayIndexOutOfBoundsException";}else{return this.list[this.index++];}}
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    let n = nextInt()
    let a = nextIntArray()
    let b = nextIntArray()
    let c = nextIntArray()
    let ans = 0
    for(let i = 0;i<a.length; i++){
        ans += b[a[i]-1]
        if(a[i]+1 == a[i+1]) ans += c[a[i]-1]
    }
    console.log(ans)
}
Main()

Score : 200 points

Problem Statement

Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once.

The i-th dish (1 \leq i \leq N) he ate was Dish A_i.

When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points.

Additionally, when he eats Dish i+1 just after eating Dish i (1 \leq i \leq N - 1), he gains C_i more satisfaction points.

Find the sum of the satisfaction points he gained.

Constraints

All values in input are integers.

2 \leq N \leq 20

1 \leq A_i \leq N

A_1, A_2, ..., A_N are all different.

1 \leq B_i \leq 50

1 \leq C_i \leq 50

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N
C_1 C_2 ... C_{N-1}

Output

Print the sum of the satisfaction points Takahashi gained, as an integer.

Sample Input 1

3
3 1 2
2 5 4
3 6

Sample Output 1

14

Takahashi gained 14 satisfaction points in total, as follows:

First, he ate Dish 3 and gained 4 satisfaction points.

Next, he ate Dish 1 and gained 2 satisfaction points.

Lastly, he ate Dish 2 and gained 5 + 3 = 8 satisfaction points.

Sample Input 2

4
2 3 4 1
13 5 8 24
45 9 15

Sample Output 2

74

Sample Input 3

2
1 2
50 50
50

Sample Output 3

150


// inputに入力データ全体が入る

function Main(input) {
    input = input.split("\n")
    N = input[0]
    inputA = input[1].split('\r')[0].split(' ')
    inputB = input[2].split('\r')[0].split(' ')
    inputC = input[3].split('\r')[0].split(' ')
    var count = 0

    for(var i=0; i < N;i++){
//        console.log( " inputB[ inputA[i] - 1 ]:::" ,  inputB[ inputA[i] - 1 ]  )
        count += parseInt( inputB[ inputA[i] - 1 ] );
        if( i > 0   ){
         //   console.log( inputA[i-1]  ,inputA[i]  )

            if( inputA[i-1] == inputA[i] -1  ){
                count += parseInt( inputC[  inputA[i-1] -1  ])
//console.log("inputC[i-1]:::",inputC[  inputA[i-1] -1   ])
            }
        }
    }
    console.log(count)
}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）

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


"use strict"

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

  let cnt = N-2;
  let ret = B[0] + B[cnt];
  for(let i=0; i<cnt; i++){
    ret += Math.min(B[i], B[i+1])
  }
  console.log(ret);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

There is an integer sequence A of length N whose values are unknown.

Given is an integer sequence B of length N-1 which is known to satisfy the following:

B_i \geq \max(A_i, A_{i+1})

Find the maximum possible sum of the elements of A.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq B_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
B_1 B_2 ... B_{N-1}

Output

Print the maximum possible sum of the elements of A.

Sample Input 1

3
2 5

Sample Output 1

9

A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum.

Sample Input 2

2
3

Sample Output 2

6

Sample Input 3

6
0 153 10 10 23

Sample Output 3

53


const lineList = require('fs').readFileSync('/dev/stdin','utf8').trim().split('\n')

const n = parseInt(lineList[0])
const b = lineList[1].split(' ').map(e => parseInt(e))
var a = 0

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

  if(b[i-1] > b[i]) {
    a -= b[i-1]
    a += b[i]
  }
}

console.log(a)


'use strict'

const main = input => {
	const args = input.split('\n').map(arg => arg.split(' '))
	const N = parseInt(args[0][0], 10)
	const B = args[1].map(arg => parseInt(arg, 10))
	const A = new Array(N).fill(0)
	let ans = 0

	A[0] = B[0]

	for (let i = 1; i < N - 1; i++) {
		A[i] = Math.min(B[i - 1], B[i])
	}

	A[N - 1] = B[N - 2]

	for (let i = 0; i < N; i++) {
		ans += A[i]
	}

	console.log(ans)
}

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