'use strict';

function Main(input) {
  const tmp = input.split('\n');
  const A = tmp[0].split('').reverse();
  const B = tmp[1].split('').reverse();
  const C = tmp[2].split('').reverse();

  let winner;
  let turn = 1;
  let next = A.pop();
  while (turn) {
    switch (next) {
      case 'a':
        next = A.pop();
        if (next == undefined) {
          winner = 'A';
          turn = 0;
        }
        break;
      case 'b':
        next = B.pop();
        if (next == undefined) {
          winner = 'B';
          turn = 0;
        }
      case 'c':
        next = C.pop();
        if (next == undefined) {
          winner = 'C';
          turn = 0;
        }
      default:
        break;
    }
  }
  console.log(winner);
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 200 points

Problem Statement

Alice, Bob and Charlie are playing Card Game for Three, as below:

At first, each of the three players has a deck consisting of some number of cards. Each card has a letter a, b or c written on it. The orders of the cards in the decks cannot be rearranged.

The players take turns. Alice goes first.

If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says a, Alice takes the next turn.)

If the current player's deck is empty, the game ends and the current player wins the game.

You are given the initial decks of the players.
More specifically, you are given three strings S_A, S_B and S_C. The i-th (1≦i≦|S_A|) letter in S_A is the letter on the i-th card in Alice's initial deck. S_B and S_C describes Bob's and Charlie's initial decks in the same way.

Determine the winner of the game.

Constraints

1≦|S_A|≦100

1≦|S_B|≦100

1≦|S_C|≦100

Each letter in S_A, S_B, S_C is a, b or c.

Input

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

S_A
S_B
S_C

Output

If Alice will win, print A. If Bob will win, print B. If Charlie will win, print C.

Sample Input 1

aca
accc
ca

Sample Output 1

A

The game will progress as below:

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice discards the top card in her deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, a. Alice takes the next turn.

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice's deck is empty. The game ends and Alice wins the game.

Sample Input 2

abcb
aacb
bccc

Sample Output 2

C


'use strict'

const main = arg => {
  const str = arg.trim().split("\n")[0].split('');
  const n = str.length - 1;

  const dfs = (i, sum, order) => {
    if (i === n) return eval(order + arg[n]);

    sum += dfs(i + 1, sum, order + arg[i] + '+') + dfs(i + 1, sum, order + arg[i]);

    return sum;
  }

  const ans = dfs(0, 0, '');
  console.log(ans);
}

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

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

Score : 300 points

Problem Statement

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

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

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

Constraints

1 \leq |S| \leq 10

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

Input

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

S

Output

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

Sample Input 1

125

Sample Output 1

176

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

125

1+25=26

12+5=17

1+2+5=8

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

Sample Input 2

9999999999

Sample Output 2

12656242944

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.


//↓見なくていいよ！ここから--------------------------------------------------
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 = new Date();
  Main();
  var end = new Date() - 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){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(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;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var one = nextIntArray();
	var N = one[0];
	var A = one[1];
	var list = nextIntArray();
	var dp = {0 : {0 : 0}};
	for(var i = 0; i < N; i++){
		var maiDp = makeClone(dp);
		var keys = Object.keys(dp).map(Number);
		for(var j = 0; j < keys.length; j++){
			var sumDp = dp[keys[j]];
			var sumKey = Object.keys(sumDp).map(Number);
			for(var k = 0; k < sumKey.length; k++){
				if(maiDp[j + 1] == null){
					maiDp[j + 1] = {};
				}
				if(maiDp[j + 1][sumKey[k] + list[i]] == null){
					maiDp[j + 1][sumKey[k] + list[i]] = 0;
				}
				maiDp[j + 1][sumKey[k] + list[i]] += dp[j][sumKey[k]];
			}
		}
		if(maiDp[1][list[i]] == null){
			maiDp[1][list[i]] = 1;
		}else{
			maiDp[1][list[i]]++;
		}
		dp = maiDp;
		//myerr(dp);
	}
	var output = 0;
	var keys = Object.keys(dp);
	for(var i = 1; i < keys.length; i++){
		if(dp[i][i * A] != null){
			output += dp[i][i * A];
		}
	}
	myout(output);
}

Score : 300 points

Problem Statement

Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i.
He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A.
In how many ways can he make his selection?

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

N,\,A,\,x_i are integers.

Partial Score

200 points will be awarded for passing the test set satisfying 1 \leq N \leq 16.

Input

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

N A
x_1 x_2 ... x_N

Output

Print the number of ways to select cards such that the average of the written integers is exactly A.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the 5 ways to select cards such that the average is 8:

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

Select the 1-st, 2-nd and 3-rd cards.

Select the 1-st, 3-rd and 4-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

The answer may not fit into a 32-bit integer.


function main(input) {
  input = input.split('\n');
  var tmp = input[0].split(' ');

  var N = Number(tmp[0]);
  var A = Number(tmp[1]);

  var x = [0];
  x = x.concat(input[1].split(' ').map(Number));

  var dp = new Array(N + 1);
  for (var i = 0; i <= N; ++i) {
    dp[i] = new Array(N + 1);
    for (var j = 0; j <= N; ++j) {
      dp[i][j] = new Array(A * N + 1).fill(0);
    }
  }

  for (var i = 0; i < N; ++i) dp[i][0][0] = 1;

  for (var i = 1; i <= N; ++i) {
    for (var j = 1; j <= i; ++j) {
      for (var k = 1; k <= A * N; ++k) {
        if (k < x[i]) {
          dp[i][j][k] = dp[i - 1][j][k];
        } else {
          dp[i][j][k] = dp[i - 1][j][k] + dp[i - 1][j - 1][k - x[i]];
        }
      }
    }
  }

  var ans = 0;
  for (var j = 1; j <= N; ++j) {
    ans += dp[N][j][j * A];
  }

  console.log(ans);
}

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


function main(input) {
  input = input.trim();
  const a = input.split(" ").map(Number);
  console.log((a*(a-1))/2);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

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

Constraints

1≦N≦100

Input

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

N

Output

Print the necessary number of candies in total.

Sample Input 1

3

Sample Output 1

6

The answer is 1+2+3=6.

Sample Input 2

10

Sample Output 2

55

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

Sample Input 3

1

Sample Output 3

1

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


(function (n) {
  console.log((1 + n) * n / 2);
}(Number(require('fs').readFileSync('/dev/stdin'))));


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

function main(cin){

let a = [];
for (let i = 0; i < cin.length; ++i){
    switch(cin[i]){
        case '0':
            a.push('0'); break;
        case '1':
            a.push('1'); break;
        case 'B':
            if (a.length > 0)
                a.pop();
            break;
    }
}
console.log(a.join(''));
}
main(cin);

Score : 200 points

Problem Statement

Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the 0 key, the 1 key and the backspace key.

To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string:

The 0 key: a letter 0 will be inserted to the right of the string.

The 1 key: a letter 1 will be inserted to the right of the string.

The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted.

Sig has launched the editor, and pressed these keys several times. You are given a string s, which is a record of his keystrokes in order. In this string, the letter 0 stands for the 0 key, the letter 1 stands for the 1 key and the letter B stands for the backspace key. What string is displayed in the editor now?

Constraints

1 ≦ |s| ≦ 10 (|s| denotes the length of s)

s consists of the letters 0, 1 and B.

The correct answer is not an empty string.

Input

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

s

Output

Print the string displayed in the editor in the end.

Sample Input 1

01B0

Sample Output 1

00

Each time the key is pressed, the string in the editor will change as follows: 0, 01, 0, 00.

Sample Input 2

0BB1

Sample Output 2

1

Each time the key is pressed, the string in the editor will change as follows: 0, (empty), (empty), 1.


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

console.log("1");


'use strict';
function Main(input) {

  const n = Number(input[0]);
  const ary = (input[1].split(" ")).map(str => Number(str));
  const sum = ary.reduce((a,b) => a+b);
  const average = Math.round(sum/n);

  let result = 0;
  for (let i=0; i<n; i++) {
    result += (ary[i]-average)*(ary[i]-average);
  }

  console.log(result);

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

Score : 200 points

Problem Statement

Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them.

He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (i≠j), he has to pay the cost separately for transforming each of them (See Sample 2).

Find the minimum total cost to achieve his objective.

Constraints

1≦N≦100

-100≦a_i≦100

Input

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

N
a_1 a_2 ... a_N

Output

Print the minimum total cost to achieve Evi's objective.

Sample Input 1

2
4 8

Sample Output 1

8

Transforming the both into 6s will cost (4-6)^2+(8-6)^2=8 dollars, which is the minimum.

Sample Input 2

3
1 1 3

Sample Output 2

3

Transforming the all into 2s will cost (1-2)^2+(1-2)^2+(3-2)^2=3 dollars. Note that Evi has to pay (1-2)^2 dollar separately for transforming each of the two 1s.

Sample Input 3

3
4 2 5

Sample Output 3

5

Leaving the 4 as it is and transforming the 2 and the 5 into 4s will achieve the total cost of (2-4)^2+(5-4)^2=5 dollars, which is the minimum.

Sample Input 4

4
-100 -100 -100 -100

Sample Output 4

0

Without transforming anything, Evi's objective is already achieved. Thus, the necessary cost is 0.


function Main() {
  var input = require("fs").readFileSync("/dev/stdin", "utf-8").trim();
  var items = input.split(" ").map(function(item) { return parseInt(item); });
  items.sort();
  var target = [5, 5, 7];
  var flag = true;
  for (var i = 0; i < 3; ++i) {
    if (items[i] != target[i]) {
      flag = false;
      break;
    }
  }
  console.log(flag ? "YES" : "NO");
}

Main();

Score : 100 points

Problem Statement

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

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

Constraints

1≦A,B,C≦10

Input

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

A B C

Output

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

Sample Input 1

5 5 7

Sample Output 1

YES

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

Sample Input 2

7 7 5

Sample Output 2

NO


"use strict"
function main(arg) {
    var data = arg.trim().split("\n")
    var n = (data.shift()).split(' ')[0]
    var n_str = n
    n = Number(n)
    var _d = data[0].split(' ').map(Number).sort()
    var d = []
    var i = 0
    for (i = 0; i < 10; i++) {
        var j = 0
        for (j = 0; j < _d.length; j++) {
            if (i === _d[j]) break
        }

        if (j === _d.length) {
            d.push(i)
        }
    }
    if (d.length === 1) {
        var s = d[0]
        var ss = pad_x(s, n_str.length, s)
        if (Number(ss) > n) {
            console.log(ss)
            return
        }
        console.log(pad_x(s, n_str.length + 1, s))
        return
    }
    i = 0
    for (i = 0; ; i++) {
        var map = i.toString(d.length)
        if (map.length > n_str.length + 1) {
            break
        }
        var map = pad(map, n_str.length )

        map = map.split('').map(Number)
        var row = ""
        for (var j = 0; j < map.length; j++) {
            var k = map[j]
            row += d[k]
        }
        // console.log(row)
        row = Number(row)
        if (row >= n) {
            console.log(row)
            return
        }
    }
    // console.log("--")
    for (; ; i++) {
        var map = i.toString(d.length)
        // if (map.length > n_str.length + 1) {
        //     break
        // }
        var map = pad(map, n_str.length + 1)

        map = map.split('').map(Number)
        var row = ""
        for (var j = 0; j < map.length; j++) {
            var k = map[j]
            row += d[k]
        }
        // console.log(row)
        row = Number(row)
        if (row >= n) {
            console.log(row)
            return
        }
    }
    // console.log(row)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

function pad(num, length) {
    var str = '0'
    return (new Array(length).fill(str).join('') + num).slice(-length);
}
function pad_x(num, length, str) {
    return (new Array(length).fill(str).join('') + num).slice(-length);
}

Score : 300 points

Problem Statement

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

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

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

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

Constraints

1 ≦ N < 10000

1 ≦ K < 10

0 ≦ D_1 < D_2 < … < D_K≦9

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

Input

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

N K
D_1 D_2 … D_K

Output

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

Sample Input 1

1000 8
1 3 4 5 6 7 8 9

Sample Output 1

2000

She dislikes all digits except 0 and 2.

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

Sample Input 2

9999 1
0

Sample Output 2

9999


"use strict"
function main(arg) {
    var data = arg.trim().split("\n")
    var n = (data.shift()).split(' ')[0]
    var n_str = n
    n = Number(n)
    var _d = data[0].split(' ').map(Number).sort()
    var d = []
    for (var i = 0; i < 10; i++) {
        var j = 0
        for (j = 0; j < _d.length; j++) {
            if (i === _d[j]) break
        }

        if (j === _d.length) {
            d.push(i)
        }
    }
    // for (var i = 0; i < n_str.length; i++) {
    //     for (var j = 0; j < d.length; j++) {
    //         console.log()
    //     }
    //     console.log(n_str[i])
    // }
    for (var i = 0; ; i++) {
        var map = i.toString(d.length)
        if (map.length > n_str.length) {
            break
        }
        var map = pad(map, n_str.length)
        map = map.split('').map(Number)
        var row = ""
        for (var j = 0; j < map.length; j++) {
            var k = map[j]
            row += d[k]
        }
        row = Number(row)
        if (row >= n) {
            console.log(row)
            return
        }
    }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

function pad(num, length) {
    var str='0'
    return (new Array(length).fill(str).join('') + num).slice(-length);
}


'use strict'

class Main {
  solve() {
    const nk = input.nextIntArr();
    const exclusion = input.nextIntArr();
    const digits = [0,1,2,3,4,5,6,7,8,9].filter(e=>exclusion.indexOf(e) == -1);
    for(let i = 0;;++i) {
      let d = i;
      let n = 0;
      let k = 1;
      while (d > 0) {
        n += k * digits[(d % digits.length)];
        k *= 10;
        d = digits.length == 1 ? d - 1 : (d/digits.length) | 0;
      }
      if (n >= nk[0]) {
        console.log(n);
        break;
      }
    }
  }
}

class Mod {
  constructor(mod) {
    if (mod == null) { mod = Combinatorics.DefaultMod; }
    this.mod = mod;
  }

  mult(a,b) {
    let ret = 0;
    a %= this.mod;
    b %= this.mod;
    while (b) {
      if (b&1) {
        ret += a;
        if (ret > this.mod) { ret -= this.mod; }
      }
      a <<= 1;
      if (a > this.mod) { a -= this.mod; }
      b >>= 1;
    }
    return ret;
  }

  pow(a,b) {
    let ret = 1;
    while(b) {
      if (b&1) { ret = this.mult(ret,a); }
      a = this.mult(a,a);
      b >>= 1;
    }
    return ret;
  }
  div(a,b) {
    return this.mult(a, power(b, this.mod-2))
  }
}
const MOD = new Mod(1e9+7);

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

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

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

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

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

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


function Main(input) {

  inputs = input.split('\n');

  let N, X;
  [N, X] = inputs[0].split(' ').map((e) => Number(e));
  return;

  let ans = N;
  let a = X, b = N - X;
  while (a % b != 0) {
    ans += 2 * Math.floor(a / b) * b;
    [a, b] = [b, a % b];
  }
  ans += 2 * a - b;

  console.log('%d', ans);

}

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

function debug() {

  let input = document.getElementById('input').value;
  Main(input);

}

Score : 500 points

Problem Statement

Snuke is conducting an optical experiment using mirrors and his new invention, the rifle of Mysterious Light.

Three mirrors of length N are set so that they form an equilateral triangle.
Let the vertices of the triangle be a, b and c.

Inside the triangle, the rifle is placed at the point p on segment ab such that ap = X.
(The size of the rifle is negligible.)
Now, the rifle is about to fire a ray of Mysterious Light in the direction of bc.

The ray of Mysterious Light will travel in a straight line, and will be reflected by mirrors, in the same ways as "ordinary" light.
There is one major difference, though: it will be also reflected by its own trajectory as if it is a mirror!
When the ray comes back to the rifle, the ray will be absorbed.

The following image shows the ray's trajectory where N = 5 and X = 2.

It can be shown that the ray eventually comes back to the rifle and is absorbed, regardless of the values of N and X.
Find the total length of the ray's trajectory.

Constraints

2≦N≦10^{12}

1≦X≦N-1

N and X are integers.

Partial Points

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

Another 200 points will be awarded for passing the test set without additional constraints.

Input

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

N X

Output

Print the total length of the ray's trajectory.

Sample Input 1

5 2

Sample Output 1

12

Refer to the image in the Problem Statement section.
The total length of the trajectory is 2+3+2+2+1+1+1 = 12.


//↓見なくていいよ！ここから--------------------------------------------------
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 = new Date();
  Main();
  var end = new Date() - start;

  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
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){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(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;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var one = nextIntArray();
	var N = one[0];
	var K = one[1];
	var list = new Array(N);
	var access = new Array(N).fill(false);
	var output = 0;
	for(var i = 0; i < N; i++){
		list[i] = {
			child : [],
			count : 0
		};
	}
	for(var i = 0; i < N - 1; i++){
		var tmp = nextIntArray();
		list[tmp[0] - 1].child.push(tmp[1] - 1);
		list[tmp[1] - 1].child.push(tmp[0] - 1);
	}
	var queue = [0];
	access[0] = true;
	var start = 0;
	var max = 0;
	while(queue.length > 0){
		var tmp = queue.shift();
		var child = list[tmp].child;
		for(var i = 0; i < child.length; i++){
			if(!access[child[i]]){
				access[child[i]] = true;
				list[child[i]].count = list[tmp].count + 1;
				if(max < list[child[i]].count){
					max = list[child[i]].count;
					start = child[i];
				}
				queue.push(child[i]);
			}
		}
	}
	var queue = [start];
	list[start].count = 0;
	access = new Array(N).fill(false);
	access[start] = true;
	while(queue.length > 0){
		var tmp = queue.shift();
		var child = list[tmp].child;
		for(var i = 0; i < child.length; i++){
			if(!access[child[i]]){
				access[child[i]] = true;
				list[child[i]].count = list[tmp].count + 1;
				queue.push(child[i]);
			}
		}
	}
	list.sort(function(a,b){
		return b.count - a.count;
	});
	for(var i = 0; i < N; i++){
		if(list[i].count > K){
			output++;
		}else{
			break;
		}
	}
	myout(output);
}

Score : 600 points

Problem Statement

Given an undirected tree, let the distance between vertices u and v be the
number of edges on the simple path from u to v.
The diameter of a tree is the maximum among the distances between any two vertices.
We will call a tree good if and only if its diameter is at most K.

You are given an undirected tree with N vertices numbered 1 through N.
For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i.

You want to remove zero or more vertices from the tree, so that the resulting tree is good.
When a vertex is removed, all incident edges will also be removed.
The resulting graph must be connected.

Find the minimum number of vertices that you need to remove in order to produce a good tree.

Constraints

2≦N≦2000

1≦K≦N-1

1≦A_i≦N, 1≦B_i≦N

The graph defined by A_i and B_i is a tree.

Input

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

N K
A_1 B_1
A_2 B_2
:
A_{N-1} B_{N-1}

Output

Print the minimum number of vertices that you need to remove in order to produce a good tree.

Sample Input 1

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

Sample Output 1

2

The tree is shown below. Removing vertices 5 and 6 will result in a good tree with the diameter of 2.

Sample Input 2

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

Sample Output 2

0

Since the given tree is already good, you do not need to remove any vertex.