'use strict'
let lines = []
let reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
})
reader.on('line', function(line) {
  lines.push(line.split(' '))
})
reader.on('close', function(line) {
  let ans = 0
  let a = lines[0]
  let b = lines[1]
  if (a > b) {
    ans += a
    a--
  } else {
    ans += b
    b--
  }
  if (a > b) {
    ans += a
  } else {
    ans += b
  }
  console.log(ans)
})

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


function main(args) {
  	var max = 0;
	var input = args.split(/\s/);
  	var a = input[0] * 1;
  	var b = input[1] * 1;
  	for (var i = 0; i <= 2; i++) {
    	if (a >= b) {
        	max += a;
          	a--;
        }
      	if (a < b) {
        	max += b;
          	b--;
        }
    }
  	console.log(max);
}

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

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

Submitted source-code file size, in bytes.

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

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


function Main(input) {
  tmp = input.split(" ");
  // convert string from integer using "parseInt"
  var a = parseInt(tmp[0], 10);
  var b = parseInt(tmp[1], 10);

  var num1 = a + (a - 1);
  var num2 = a + b;
  var num3 = b + (b - 1);

  return Math.max(num1, num2, num3);
}

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


function Main(input){
	tmp = input.split("\n");
	var a = parseInt(tmp[0]);
	var b = tmp[1].split(" ");
	var lim = b[0];
	var c = 0;

	for (var i = 0 ; i < a ; i++){
		if(lim <= b[i]){
			c++;
			lim = b[i];
		}
	}

	console.log(c);
}

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

Score : 200 points

Problem Statement

There are N mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the i-th mountain from the west is H_i.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.

From how many of these N inns can you see the ocean?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


function Main(input) {
  "use strict";
	const lines = input.split("\n");
  const n = parseInt(lines[0], 10);
  let nums = lines[1].split(" ").map(s => parseInt(s, 10));

  let ans = 0;
  let highest = 0;
  nums.forEach( x => {
    if ( x >= highest) { ans++; highest = x;}
  })
  console.log(ans)
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  var N = input.trim().length;
  var count = 0;
  var color = 0;

  for(i=0;i<N;i++){
    if (parseInt(input.charAt(i)) == color) count++;
    color = (color + 1)%2;
  }
  console.log(Math.min(count,N-count));
}

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

Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


"use strict";

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

    const S = arg[1].split("").map(n=>parseInt(n));

    // 奇数番目に連続する1の数、偶数版目に連続する0の数 の配列を用意
    let list = [];

    if(S.indexOf(0) === -1) {
        console.log(N);
        return;
    }

    if(S.indexOf(1) === -1) {
        console.log(N);
        return;
    }

    if(S[0] !== 1) {
        list.push(0);
    }

    let streak = 0;

    for(let i=1; i<S.length; i++) {
        if(S[i] === S[i - 1]) {
            streak++;
        } else {
            streak++;
            list.push(streak);
            streak = 0;
        }
    }

    streak++;
    list.push(streak);

    if(S[S.length - 1] !== 1) {
        list.push(0);
    }

    // 集計
    let temp = 0;
    let answer = 0;

    // しゃくとり

    if(K > list.length) {

        answer = list.reduce((m,n)=>m+n)

    } else {

        for(let left=0; left<list.length - (K + K); left += 2) {
            let sum = 0;
            let right = left + K + K;

            // console.log("left:"  + left);
            // console.log("right:" + right);

            for(let i=left; i<=right; i++) {
                sum += list[i]
            }

            // console.log("sum:" + sum)
            answer = Math.max(sum, answer);
        }

    }

    answer = Math.max(answer, temp);

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

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


function Main(input) {
  var list = input.split("\n");
  var nk = list[0].split(" ");
  var N = nk[0];
  var K = nk[1];
  var S = list[1].split("");
  S.map( function(value){
    return parseInt(value);
  })

  var count, rev;
  var state = 0;
  var maxcount = 0;
  var Sarray = new Array(0);

  count = 0
  state = 1;

  for(i=0;i<N;i++){
    if(S[i] != state) {
      state = 1 - state;
      Sarray.push(count);
      count = 1;
    } else count++;
  }
  Sarray.push(count);
  if(Sarray.length == 1) Sarray.push(0);
  if(Sarray.length % 2 == 0) Sarray.push(0);

  var ans = 0;
  for(i=0;i<Math.min(Sarray.length,2*K+1);i++){
    ans += Sarray[i];
  }

  var tmp;
  var Sn = Sarray.length;
  for(i=2*K+2;i<Sn;i+=2){
    tmp = ans - (Sarray[0] + Sarray[1]) + (Sarray[2*K+1] + Sarray[2*K]);
    Sarray.shift(2)
    if (tmp > ans) ans = tmp;
  }
  console.log(ans);
}

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


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(v)";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}

console.log(main());
function main(){
  var a = o.r(5).sort((a,b)=>a-b);
  var k = o.a();
  return a[4] - a[0] <= k ? "Yay!" : ":(";
}

Score: 100 points

Problem Statement

In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k.

Determine if there exists a pair of antennas that cannot communicate directly.

Here, assume that the distance between two antennas at coordinates p and q (p < q) is q - p.

Constraints

a, b, c, d, e and k are integers between 0 and 123 (inclusive).

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

Print :( if there exists a pair of antennas that cannot communicate directly, and print Yay! if there is no such pair.

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:

the distance between A and B is 2 - 1 = 1

the distance between A and C is 4 - 1 = 3

the distance between A and D is 8 - 1 = 7

the distance between A and E is 9 - 1 = 8

the distance between B and C is 4 - 2 = 2

the distance between B and D is 8 - 2 = 6

the distance between B and E is 9 - 2 = 7

the distance between C and D is 8 - 4 = 4

the distance between C and E is 9 - 4 = 5

the distance between D and E is 9 - 8 = 1

and none of them is greater than 15. Thus, the correct output is Yay!.

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

In this case, the distance between antennas A and D is 35 - 15 = 20 and exceeds 18, so they cannot communicate directly.
Thus, the correct output is :(.


function myOut(text){console.log(text);}//standard output
function Main(input) {
	input = input.trim();
	//input = input.split(" ");
	//input = input.split("\n");
	//input = input.split(" ").map((a)=>Number(a));
	input = input.split("\n").map((a)=>Number(a));
  input.sort(function(a,b){
  	return b % 10 - a % 10;
  });
  var zero = [];
  var output = 0;

  for(var i = 0; i < input.length; i++){
    if(input[i] % 10 == 0){
       zero.push(input[i]);
      input.splice(i,1);
      i--;
       }
  }

  var last = 0;
  if(input.length != 0){
  	last = input[input.length - 1];
     }

  for(var i = 0; i < input.length - 1; i++){
    output += input[i] + (10 - input[i] % 10);
  }
  for(var i = 0; i < zero.length; i++){
    output += zero[i];
  }

  //myOut(output);
  myOut(output + last);
}

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

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


function Main(input) {
  var array = input.trim().split("\n");
  array = array.map(val => parseInt(val, 10));
  var waitTimeAry = [];
  var amount = 0;
  var ceilArray = [];

  for (var i = 0; i < array.length; i++) {
    var ceil = Math.ceil(array[i] / 10) * 10;
    waitTimeAry.push(ceil - array[i]);
    ceilArray.push(ceil);
  }

  var maxWait = Math.max(...waitTimeAry);
  var index = waitTimeAry.indexOf(maxWait);
  ceilArray.splice(index, 1);
  ceilArray.splice(ceilArray.length, 0, array[index]);
  for (var j = 0; j < ceilArray.length; j++) {
    amount += ceilArray[j];
  }
  console.log(amount);
}

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


function main(input) {
	var list = input.split("\n");
	var time = 0;
	list = list.map((item) => {
		var min = +item%10 > 0 ? 10 * (parseInt(+item/10) + 1) : +item;
		return {
			chori  : +item,
			chumon : min,
			rug : min - +item
		};
	});
	list.sort((x, y) => {
		return x.rug - y.rug;
	});
	list.forEach((item, index) => {
		if(index === list.length - 1) {
			time += item.chori;
		} else {
			time += item.chumon;
		}
	});
	console.log(time);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
    var menu = input.map(i => parseInt(i, 10));

    var kiriage = menu.map(m => {
        return Math.ceil(m/10) * 10;
    });
    var min = Math.min.apply(null, menu.map(m => m%10));

    var result = 0;

    for (var i = 0; i < kiriage.length; i++) {
        result += kiriage[i];
    }

    if (min !== 0) {
        result = result - 10 + min;
    }

    console.log(result);
}

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


parcelRequire=function(e,r,t,n){var i,o="function"==typeof parcelRequire&&parcelRequire,u="function"==typeof require&&require;function f(t,n){if(!r[t]){if(!e[t]){var i="function"==typeof parcelRequire&&parcelRequire;if(!n&&i)return i(t,!0);if(o)return o(t,!0);if(u&&"string"==typeof t)return u(t);var c=new Error("Cannot find module '"+t+"'");throw c.code="MODULE_NOT_FOUND",c}p.resolve=function(r){return e[t][1][r]||r},p.cache={};var l=r[t]=new f.Module(t);e[t][0].call(l.exports,p,l,l.exports,this)}return r[t].exports;function p(e){return f(p.resolve(e))}}f.isParcelRequire=!0,f.Module=function(e){this.id=e,this.bundle=f,this.exports={}},f.modules=e,f.cache=r,f.parent=o,f.register=function(r,t){e[r]=[function(e,r){r.exports=t},{}]};for(var c=0;c<t.length;c++)try{f(t[c])}catch(e){i||(i=e)}if(t.length){var l=f(t[t.length-1]);"object"==typeof exports&&"undefined"!=typeof module?module.exports=l:"function"==typeof define&&define.amd?define(function(){return l}):n&&(this[n]=l)}if(parcelRequire=f,i)throw i;return f}({"Focm":[function(require,module,exports) {
var t={};!function(n){"use strict";(t["Control.Apply"]=t["Control.Apply"]||{}).arrayApply=function(t){return function(n){for(var a=t.length,r=n.length,e=new Array(a*r),o=0,i=0;i<a;i++)for(var u=t[i],c=0;c<r;c++)e[o++]=u(n[c]);return e}}}(),function(n){"use strict";(t["Data.Eq"]=t["Data.Eq"]||{}).refEq=function(t){return function(n){return t===n}}}(),function(n){"use strict";var a=t["Data.Eq"],r=(t["Data.HeytingAlgebra"],t["Data.Symbol"],t["Data.Unit"],t["Data.Void"],t["Record.Unsafe"],t["Type.Data.RowList"],function(t){this.eq=t}),e=new r(a.refEq);n.Eq=r,n.eq=function(t){return t.eq},n.eqInt=e}(t["Data.Eq"]=t["Data.Eq"]||{}),function(n){"use strict";(t["Data.Ord.Unsafe"]=t["Data.Ord.Unsafe"]||{}).unsafeCompareImpl=function(t){return function(n){return function(a){return function(r){return function(e){return r<e?t:r===e?n:a}}}}}}(),function(n){"use strict";(t["Data.Semigroup"]=t["Data.Semigroup"]||{}).concatArray=function(t){return function(n){return 0===t.length?n:0===n.length?t:t.concat(n)}}}(),function(n){"use strict";var a=t["Data.Semigroup"],r=(t["Data.Symbol"],t["Data.Unit"],t["Data.Void"],t["Record.Unsafe"],t["Type.Data.RowList"],function(t){this.append=t}),e=new r(a.concatArray);n.Semigroup=r,n.append=function(t){return t.append},n.semigroupArray=e}(t["Data.Semigroup"]=t["Data.Semigroup"]||{}),function(n){"use strict";(t["Data.Show"]=t["Data.Show"]||{}).showIntImpl=function(t){return t.toString()}}(),function(n){"use strict";var a=t["Data.Show"],r=(t["Data.Symbol"],t["Record.Unsafe"],t["Type.Data.RowList"],function(t){this.show=t}),e=new r(a.showIntImpl);n.Show=r,n.show=function(t){return t.show},n.showInt=e}(t["Data.Show"]=t["Data.Show"]||{}),function(n){"use strict";t["Data.Eq"],t["Data.Semigroup"],t["Data.Show"];var a=function(){function t(){}return t.value=new t,t}(),r=function(){function t(){}return t.value=new t,t}(),e=function(){function t(){}return t.value=new t,t}();n.LT=a,n.GT=r,n.EQ=e}(t["Data.Ordering"]=t["Data.Ordering"]||{}),function(n){"use strict";var a=t["Data.Ord.Unsafe"],r=t["Data.Ordering"],e=a.unsafeCompareImpl(r.LT.value)(r.EQ.value)(r.GT.value);n.unsafeCompare=e}(t["Data.Ord.Unsafe"]=t["Data.Ord.Unsafe"]||{}),function(n){"use strict";(t["Data.Ring"]=t["Data.Ring"]||{}).intSub=function(t){return function(n){return t-n|0}}}(),function(t){"use strict";t.intAdd=function(t){return function(n){return t+n|0}},t.intMul=function(t){return function(n){return t*n|0}}}(t["Data.Semiring"]=t["Data.Semiring"]||{}),function(n){"use strict";var a=t["Data.Semiring"],r=(t["Data.Symbol"],t["Data.Unit"],t["Record.Unsafe"],t["Type.Data.Row"],t["Type.Data.RowList"],function(t,n,a,r){this.add=t,this.mul=n,this.one=a,this.zero=r}),e=new r(a.intAdd,a.intMul,1,0);n.Semiring=r,n.add=function(t){return t.add},n.zero=function(t){return t.zero},n.mul=function(t){return t.mul},n.one=function(t){return t.one},n.semiringInt=e}(t["Data.Semiring"]=t["Data.Semiring"]||{}),function(n){"use strict";var a=t["Data.Ring"],r=t["Data.Semiring"],e=(t["Data.Symbol"],t["Data.Unit"],t["Record.Unsafe"],t["Type.Data.RowList"],function(t,n){this.Semiring0=t,this.sub=n}),o=new e(function(){return r.semiringInt},a.intSub);n.Ring=e,n.sub=function(t){return t.sub},n.ringInt=o}(t["Data.Ring"]=t["Data.Ring"]||{}),function(n){"use strict";t["Data.Ord"];var a=t["Data.Eq"],r=t["Data.Ord.Unsafe"],e=(t["Data.Ordering"],t["Data.Ring"],t["Data.Semiring"],t["Data.Symbol"],t["Data.Unit"],t["Data.Void"],t["Record.Unsafe"],t["Type.Data.RowList"],function(t,n){this.Eq0=t,this.compare=n}),o=new e(function(){return a.eqInt},r.unsafeCompare),i=function(t){return t.compare};n.Ord=e,n.compare=i,n.comparing=function(t){return function(n){return function(a){return function(r){return i(t)(n(a))(n(r))}}}},n.ordInt=o}(t["Data.Ord"]=t["Data.Ord"]||{}),function(n){"use strict";t["Control.Category"],t["Data.Boolean"],t["Data.Ord"],t["Data.Ring"];n.flip=function(t){return function(n){return function(a){return t(a)(n)}}}}(t["Data.Function"]=t["Data.Function"]||{}),function(n){"use strict";(t["Data.Functor"]=t["Data.Functor"]||{}).arrayMap=function(t){return function(n){for(var a=n.length,r=new Array(a),e=0;e<a;e++)r[e]=t(n[e]);return r}}}(),function(n){"use strict";var a=t["Data.Functor"],r=(t["Control.Semigroupoid"],t["Data.Function"],t["Data.Unit"],function(t){this.map=t}),e=new r(a.arrayMap);n.Functor=r,n.map=function(t){return t.map},n.functorArray=e}(t["Data.Functor"]=t["Data.Functor"]||{}),function(n){"use strict";var a=t["Control.Apply"],r=(t["Control.Category"],t["Data.Function"],t["Data.Functor"]),e=function(t,n){this.Functor0=t,this.apply=n},o=new e(function(){return r.functorArray},a.arrayApply);n.Apply=e,n.apply=function(t){return t.apply},n.applyArray=o}(t["Control.Apply"]=t["Control.Apply"]||{}),function(n){"use strict";t["Control.Apply"],t["Data.Functor"],t["Data.Unit"];n.Applicative=function(t,n){this.Apply0=t,this.pure=n},n.pure=function(t){return t.pure}}(t["Control.Applicative"]=t["Control.Applicative"]||{}),function(t){"use strict";t.range=function(t){return function(n){for(var a=t>n?-1:1,r=new Array(a*(n-t)+1),e=t,o=0;e!==n;)r[o++]=e,e+=a;return r[o]=e,r}},t.length=function(t){return t.length},t.reverse=function(t){return t.slice().reverse()},t.filter=function(t){return function(n){return n.filter(t)}},t.sortImpl=function(t){return function(n){return n.slice().sort(function(n,a){return t(n)(a)})}},t.slice=function(t){return function(n){return function(a){return a.slice(t,n)}}},t.zipWith=function(t){return function(n){return function(a){for(var r=n.length<a.length?n.length:a.length,e=new Array(r),o=0;o<r;o++)e[o]=t(n[o])(a[o]);return e}}}}(t["Data.Array"]=t["Data.Array"]||{}),function(n){"use strict";(t["Control.Bind"]=t["Control.Bind"]||{}).arrayBind=function(t){return function(n){for(var a=[],r=0,e=t.length;r<e;r++)Array.prototype.push.apply(a,n(t[r]));return a}}}(),function(n){"use strict";var a=t["Control.Bind"],r=(t["Control.Applicative"],t["Control.Apply"]),e=(t["Control.Category"],t["Data.Function"],t["Data.Functor"],t["Data.Unit"],function(t,n){this.Apply0=t,this.bind=n}),o=new e(function(){return r.applyArray},a.arrayBind);n.Bind=e,n.bind=function(t){return t.bind},n.bindArray=o}(t["Control.Bind"]=t["Control.Bind"]||{}),function(t){"use strict";t.foldrArray=function(t){return function(n){return function(a){for(var r=n,e=a.length-1;e>=0;e--)r=t(a[e])(r);return r}}},t.foldlArray=function(t){return function(n){return function(a){for(var r=n,e=a.length,o=0;o<e;o++)r=t(r)(a[o]);return r}}}}(t["Data.Foldable"]=t["Data.Foldable"]||{}),function(t){"use strict";t.intDegree=function(t){return Math.min(Math.abs(t),2147483647)},t.intDiv=function(t){return function(n){return 0===n?0:n>0?Math.floor(t/n):-Math.floor(t/-n)}},t.intMod=function(t){return function(n){if(0===n)return 0;var a=Math.abs(n);return(t%a+a)%a}}}(t["Data.EuclideanRing"]=t["Data.EuclideanRing"]||{}),function(n){"use strict";var a=t["Data.Ring"],r=(t["Data.Semiring"],t["Data.Symbol"],t["Data.Unit"],function(t){this.Ring0=t}),e=new r(function(){return a.ringInt});n.CommutativeRing=r,n.commutativeRingInt=e}(t["Data.CommutativeRing"]=t["Data.CommutativeRing"]||{}),function(n){"use strict";var a=t["Data.EuclideanRing"],r=(t["Data.BooleanAlgebra"],t["Data.CommutativeRing"]),e=(t["Data.Eq"],t["Data.HeytingAlgebra"],t["Data.Ring"],t["Data.Semiring"],function(t,n,a,r){this.CommutativeRing0=t,this.degree=n,this.div=a,this.mod=r}),o=new e(function(){return r.commutativeRingInt},a.intDegree,a.intDiv,a.intMod);n.EuclideanRing=e,n.degree=function(t){return t.degree},n.div=function(t){return t.div},n.mod=function(t){return t.mod},n.euclideanRingInt=o}(t["Data.EuclideanRing"]=t["Data.EuclideanRing"]||{}),function(n){"use strict";t["Data.Boolean"],t["Data.Eq"],t["Data.EuclideanRing"],t["Data.Ord"],t["Data.Ordering"],t["Data.Semigroup"],t["Data.Symbol"],t["Data.Unit"],t["Record.Unsafe"],t["Type.Data.RowList"];n.mempty=function(t){return t.mempty}}(t["Data.Monoid"]=t["Data.Monoid"]||{}),function(n){"use strict";t["Control.Alt"],t["Control.Alternative"],t["Control.Applicative"],t["Control.Apply"],t["Control.Bind"],t["Control.Category"],t["Control.Extend"],t["Control.Monad"],t["Control.MonadZero"],t["Control.Plus"],t["Data.Bounded"],t["Data.Eq"],t["Data.Function"],t["Data.Functor"],t["Data.Functor.Invariant"],t["Data.Monoid"],t["Data.Ord"],t["Data.Ordering"],t["Data.Semigroup"],t["Data.Show"],t["Data.Unit"],t.Prelude;var a=function(){function t(){}return t.value=new t,t}(),r=function(){function t(t){this.value0=t}return t.create=function(n){return new t(n)},t}();n.Nothing=a,n.Just=r,n.maybe=function(t){return function(n){return function(e){if(e instanceof a)return t;if(e instanceof r)return n(e.value0);throw new Error("Failed pattern match at Data.Maybe (line 217, column 1 - line 217, column 51): "+[t.constructor.name,n.constructor.name,e.constructor.name])}}}}(t["Data.Maybe"]=t["Data.Maybe"]||{}),function(n){"use strict";var a=t["Data.Foldable"],r=(t["Control.Alt"],t["Control.Applicative"],t["Control.Apply"],t["Control.Bind"],t["Control.Category"],t["Control.Plus"],t["Control.Semigroupoid"],t["Data.Eq"],t["Data.Function"],t["Data.Functor"],t["Data.HeytingAlgebra"],t["Data.Maybe"],t["Data.Maybe.First"],t["Data.Maybe.Last"],t["Data.Monoid"]),e=(t["Data.Monoid.Additive"],t["Data.Monoid.Conj"],t["Data.Monoid.Disj"],t["Data.Monoid.Dual"],t["Data.Monoid.Endo"],t["Data.Monoid.Multiplicative"],t["Data.Newtype"],t["Data.Ord"],t["Data.Ordering"],t["Data.Semigroup"]),o=(t["Data.Semiring"],t["Data.Unit"],t.Prelude,function(t,n,a){this.foldMap=t,this.foldl=n,this.foldr=a}),i=function(t){return t.foldr},u=function(t){return function(n){return function(a){return i(t)(function(t){return function(r){return e.append(n.Semigroup0())(a(t))(r)}})(r.mempty(n))}}},c=new o(function(t){return u(c)(t)},a.foldlArray,a.foldrArray);n.Foldable=o,n.foldr=i,n.foldl=function(t){return t.foldl},n.foldMap=function(t){return t.foldMap},n.foldMapDefaultR=u,n.foldableArray=c}(t["Data.Foldable"]=t["Data.Foldable"]||{}),function(n){"use strict";t["Control.Applicative"],t["Control.Apply"],t["Control.Biapplicative"],t["Control.Biapply"],t["Control.Bind"],t["Control.Comonad"],t["Control.Extend"],t["Control.Lazy"],t["Control.Monad"],t["Control.Semigroupoid"],t["Data.Bifoldable"],t["Data.Bifunctor"],t["Data.Bitraversable"],t["Data.BooleanAlgebra"],t["Data.Bounded"],t["Data.CommutativeRing"],t["Data.Distributive"],t["Data.Eq"],t["Data.Foldable"],t["Data.FoldableWithIndex"],t["Data.Function"],t["Data.Functor"],t["Data.Functor.Invariant"],t["Data.FunctorWithIndex"],t["Data.HeytingAlgebra"],t["Data.Maybe"],t["Data.Maybe.First"],t["Data.Monoid"],t["Data.Newtype"],t["Data.Ord"],t["Data.Ordering"],t["Data.Ring"],t["Data.Semigroup"],t["Data.Semigroup.Foldable"],t["Data.Semigroup.Traversable"],t["Data.Semiring"],t["Data.Show"],t["Data.Traversable"],t["Data.TraversableWithIndex"],t["Data.Unit"],t.Prelude,t["Type.Equality"];var a=function(){function t(t,n){this.value0=t,this.value1=n}return t.create=function(n){return function(a){return new t(n,a)}},t}();n.Tuple=a,n.snd=function(t){return t.value1}}(t["Data.Tuple"]=t["Data.Tuple"]||{}),function(n){"use strict";(t["Partial.Unsafe"]=t["Partial.Unsafe"]||{}).unsafePartial=function(t){return t()}}(),function(n){"use strict";(t["Partial"]=t["Partial"]||{}).crashWith=function(){return function(t){throw new Error(t)}}}(),function(n){"use strict";var a=t.Partial;n.crashWith=a.crashWith}(t.Partial=t.Partial||{}),function(n){"use strict";var a=t["Partial.Unsafe"],r=t.Partial;n.unsafeCrashWith=function(t){return a.unsafePartial(function(n){return r.crashWith(n)(t)})}}(t["Partial.Unsafe"]=t["Partial.Unsafe"]||{}),function(n){"use strict";(t["Unsafe.Coerce"]=t["Unsafe.Coerce"]||{}).unsafeCoerce=function(t){return t}}(),function(n){"use strict";var a=t["Unsafe.Coerce"];n.unsafeCoerce=a.unsafeCoerce}(t["Unsafe.Coerce"]=t["Unsafe.Coerce"]||{}),function(n){"use strict";var a=t["Data.Array"],r=(t["Control.Alt"],t["Control.Alternative"],t["Control.Applicative"],t["Control.Apply"],t["Control.Bind"]),e=(t["Control.Category"],t["Control.Lazy"],t["Control.Monad.Rec.Class"],t["Control.Monad.ST"],t["Control.Monad.ST.Internal"],t["Control.Semigroupoid"],t["Data.Array.NonEmpty.Internal"],t["Data.Array.ST"],t["Data.Array.ST.Iterator"],t["Data.Boolean"],t["Data.Eq"],t["Data.Foldable"],t["Data.Function"]),o=(t["Data.Functor"],t["Data.HeytingAlgebra"],t["Data.Maybe"]),i=t["Data.Ord"],u=t["Data.Ordering"],c=(t["Data.Ring"],t["Data.Semigroup"],t["Data.Semiring"],t["Data.Traversable"],t["Data.Tuple"],t["Data.Unfoldable"],t["Partial.Unsafe"],t.Prelude,t["Unsafe.Coerce"],function(t){return function(n){return a.sortImpl(function(n){return function(a){var r=t(n)(a);if(r instanceof u.GT)return 1;if(r instanceof u.EQ)return 0;if(r instanceof u.LT)return-1;throw new Error("Failed pattern match at Data.Array (line 702, column 15 - line 707, column 1): "+[r.constructor.name])}})(n)}}),l=function(t){return[t]},f=e.flip(r.bind(r.bindArray));n.singleton=l,n.concatMap=f,n.mapMaybe=function(t){return f(function(n){return o.maybe([])(l)(t(n))})},n.mapWithIndex=function(t){return function(n){return a.zipWith(t)(a.range(0)(a.length(n)-1|0))(n)}},n.sortBy=c,n.sortWith=function(t){return function(n){return c(i.comparing(t)(n))}},n.length=a.length,n.reverse=a.reverse,n.filter=a.filter}(t["Data.Array"]=t["Data.Array"]||{}),function(n){"use strict";t["Control.Alt"];var a=t["Control.Applicative"],r=t["Control.Apply"],e=(t["Control.Bind"],t["Control.Extend"],t["Control.Monad"],t["Control.Semigroupoid"],t["Data.Bifoldable"],t["Data.Bifunctor"],t["Data.Bitraversable"],t["Data.Bounded"],t["Data.Eq"],t["Data.Foldable"],t["Data.FoldableWithIndex"],t["Data.Function"],t["Data.Functor"]),o=(t["Data.Functor.Invariant"],t["Data.FunctorWithIndex"],t["Data.Maybe"],t["Data.Monoid"],t["Data.Ord"],t["Data.Ordering"],t["Data.Semigroup"],t["Data.Show"],t["Data.Traversable"],t["Data.TraversableWithIndex"],t["Data.Unit"],t.Prelude,function(){function t(t){this.value0=t}return t.create=function(n){return new t(n)},t}()),i=function(){function t(t){this.value0=t}return t.create=function(n){return new t(n)},t}(),u=new e.Functor(function(t){return function(n){if(n instanceof o)return new o(n.value0);if(n instanceof i)return new i(t(n.value0));throw new Error("Failed pattern match at Data.Either (line 38, column 8 - line 38, column 52): "+[n.constructor.name])}}),c=new r.Apply(function(){return u},function(t){return function(n){if(t instanceof o)return new o(t.value0);if(t instanceof i)return e.map(u)(t.value0)(n);throw new Error("Failed pattern match at Data.Either (line 82, column 1 - line 82, column 41): "+[t.constructor.name,n.constructor.name])}}),l=new a.Applicative(function(){return c},i.create);n.Left=o,n.Right=i,n.functorEither=u,n.applyEither=c,n.applicativeEither=l}(t["Data.Either"]=t["Data.Either"]||{}),function(n){"use strict";(t["Data.Int"]=t["Data.Int"]||{}).fromStringAsImpl=function(t){return function(n){return function(a){var r;r=a<11?"[0-"+(a-1).toString()+"]":11===a?"[0-9a]":"[0-9a-"+String.fromCharCode(86+a)+"]";var e=new RegExp("^[\\+\\-]?"+r+"+$","i");return function(r){if(e.test(r)){var o=parseInt(r,a);return(0|o)===o?t(o):n}return n}}}}}(),function(n){"use strict";var a=t["Data.Int"],r=(t["Control.Category"],t["Control.Semigroupoid"],t["Data.Boolean"],t["Data.Bounded"],t["Data.CommutativeRing"],t["Data.DivisionRing"],t["Data.Eq"],t["Data.EuclideanRing"],t["Data.HeytingAlgebra"],t["Data.Int.Bits"],t["Data.Maybe"]),e=(t["Data.Ord"],t["Data.Ordering"],t["Data.Ring"],t["Data.Semiring"],t["Data.Show"],t.Global,t.Math,t.Prelude,a.fromStringAsImpl(r.Just.create)(r.Nothing.value)),o=e(10);n.fromString=o,n.fromStringAs=e}(t["Data.Int"]=t["Data.Int"]||{}),function(t){"use strict";t.split=function(t){return function(n){return n.split(t)}},t.trim=function(t){return t.trim()}}(t["Data.String.Common"]=t["Data.String.Common"]||{}),function(n){"use strict";var a=t["Data.String.Common"];t["Data.Eq"],t["Data.Ordering"],t["Data.String.Pattern"],t.Prelude;n.split=a.split,n.trim=a.trim}(t["Data.String.Common"]=t["Data.String.Common"]||{}),function(n){"use strict";var a=t["Control.Applicative"],r=t["Data.Array"],e=t["Data.Either"],o=(t["Data.Eq"],t["Data.EuclideanRing"]),i=t["Data.Foldable"],u=t["Data.Functor"],c=t["Data.Int"],l=t["Data.Ord"],f=(t["Data.Ring"],t["Data.Semigroup"]),s=(t["Data.Semiring"],t["Data.Show"]),D=(t["Data.String"],t["Data.String.Common"]),d=(t["Data.String.Pattern"],t["Data.Tuple"]),p=t["Partial.Unsafe"];t.Prelude;n.solve=function(t){var n=function(t){var n=r.mapMaybe(c.fromString)(D.split("\n")(D.trim(t))),p=r.sortWith(l.ordInt)(d.snd)(u.map(u.functorArray)(function(t){return new d.Tuple(t,o.mod(o.euclideanRingInt)(t)(10))})(n));return a.pure(e.applicativeEither)(s.show(s.showInt)(i.foldl(i.foldableArray)(function(t){return function(a){return a.value0===(r.length(n)-1|0)?t+a.value1.value0|0:0===a.value1.value1?t+a.value1.value0|0:10+(t+(10*o.div(o.euclideanRingInt)(a.value1.value0)(10)|0)|0)|0}})(0)(r.mapWithIndex(d.Tuple.create)(f.append(f.semigroupArray)(r.filter(function(t){return 0===t.value1})(p))(r.reverse(r.filter(function(t){return 0!==t.value1})(p)))))))}(t);if(n instanceof e.Left)return p.unsafeCrashWith(n.value0);if(n instanceof e.Right)return n.value0;throw new Error("Failed pattern match at AtCoder.ABC123.B (line 17, column 3 - line 19, column 24): "+[n.constructor.name])}}(t["AtCoder.ABC123.B"]=t["AtCoder.ABC123.B"]||{}),function(n){"use strict";(t["Effect.Console"]=t["Effect.Console"]||{}).log=function(t){return function(){return console.log(t),{}}}}(),function(n){"use strict";var a=t["Effect.Console"];t["Data.Show"],t["Data.Unit"],t.Effect;n.log=a.log}(t["Effect.Console"]=t["Effect.Console"]||{}),function(n){"use strict";t["Node.Encoding"];var a=t["Data.Show"],r=(t.Prelude,function(){function t(){}return t.value=new t,t}()),e=function(){function t(){}return t.value=new t,t}(),o=function(){function t(){}return t.value=new t,t}(),i=function(){function t(){}return t.value=new t,t}(),u=function(){function t(){}return t.value=new t,t}(),c=function(){function t(){}return t.value=new t,t}(),l=function(){function t(){}return t.value=new t,t}(),f=function(){function t(){}return t.value=new t,t}(),s=new a.Show(function(t){if(t instanceof r)return"ASCII";if(t instanceof e)return"UTF8";if(t instanceof o)return"UTF16LE";if(t instanceof i)return"UCS2";if(t instanceof u)return"Base64";if(t instanceof c)return"Latin1";if(t instanceof l)return"Binary";if(t instanceof f)return"Hex";throw new Error("Failed pattern match at Node.Encoding (line 19, column 1 - line 19, column 39): "+[t.constructor.name])});n.ASCII=r,n.UTF8=e,n.UTF16LE=o,n.UCS2=i,n.Base64=u,n.Latin1=c,n.Binary=l,n.Hex=f,n.showEncoding=s}(t["Node.Encoding"]=t["Node.Encoding"]||{}),function(n){"use strict";(t["Node.FS.Internal"]=t["Node.FS.Internal"]||{}).unsafeRequireFS=require("fs")}(),function(n){"use strict";var a=t["Node.FS.Internal"],r=(t.Effect,t.Prelude,t["Unsafe.Coerce"].unsafeCoerce);n.mkEffect=r,n.unsafeRequireFS=a.unsafeRequireFS}(t["Node.FS.Internal"]=t["Node.FS.Internal"]||{}),function(n){"use strict";t["Control.Bind"],t["Control.Semigroupoid"],t["Data.DateTime"],t["Data.DateTime.Instant"],t["Data.EuclideanRing"],t["Data.Function"],t["Data.Function.Uncurried"],t["Data.Functor"],t["Data.Int"],t["Data.Maybe"],t["Data.Nullable"];var a=t["Data.Show"],r=(t["Data.Time.Duration"],t.Effect,t["Node.Buffer"],t["Node.Encoding"]),e=(t["Node.FS"],t["Node.FS.Internal"]),o=(t["Node.FS.Perms"],t["Node.FS.Stats"],t["Node.Path"],t.Prelude,e.unsafeRequireFS);n.readTextFile=function(t){return function(n){return e.mkEffect(function(e){return o.readFileSync(n,{encoding:a.show(r.showEncoding)(t)})})}}}(t["Node.FS.Sync"]=t["Node.FS.Sync"]||{}),function(n){"use strict";var a=t["AtCoder.ABC123.B"],r=(t["Control.Applicative"],t["Control.Bind"],t.Effect,t["Effect.Console"]),e=t["Node.Encoding"],o=t["Node.FS.Sync"];t.Prelude;n.main=function(){var t=o.readTextFile(e.UTF8.value)("/dev/stdin")(),n=a.solve(t);return r.log(n)()}}(t.Main=t.Main||{}),t.Main.main();
},{}]},{},["Focm"], null)


function Main(input) {
  var args = input.split("\n").filter(f => !!f);
  var times = args.map(t => parseInt(t));
  var timeMods = times.map(t => (t - 1) % 10);
  var timeSep = times.map(t => Math.ceil(t / 10) * 10);
  var min = null;
  var minDef;
  var sum = 0;
  for (var i = 0; i < timeMods.length; i ++) {
    if (min === null || timeMods[i] < min) {
      min = timeMods[i];
      minDef = times[i] - timeSep[i];
    }
    sum += timeSep[i];
  }
  console.log((sum + minDef));

}

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


var lines = [];

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

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

rl.on('close', function () {
    var N = Number(lines[0]);
    var A = Number(lines[1]);
    var B = Number(lines[2]);
    var C = Number(lines[3]);
    var D = Number(lines[4]);
    var E = Number(lines[5]);

    var min = Math.min(A, B, C, D, E);

    console.log(4 + Math.ceil(N / min));
});

Score: 300 points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.

Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.

Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.

Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.

Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

1 \leq N, A, B, C, D, E \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are N = 5 people at City 1, as shown in the following image:

In the first minute, three people travels from City 1 to City 2 by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City 1 to City 2 by train, and two of the three people who were already at City 2 travels to City 3 by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City 2 to City 3 by train, and another two people travels from City 3 to City 4 by taxi.

From then on, if they continue traveling without stopping until they reach City 6, all of them can reach there in seven minutes.

There is no way for them to reach City 6 in 6 minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy N = 10 people at a time.
Thus, if they continue traveling without stopping until they reach City 6, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

Note that the input or output may not fit into a 32-bit integer type.


//https://atcoder.jp/contests/abc123/tasks/abc123_c
function setUp(input) {
  input = input.split("\n");
  n = Number(input[0]);
  a = Number(input[1]);
  b = Number(input[2]);
  c = Number(input[3]);
  d = Number(input[4]);
  e = Number(input[5]);
  main();
}
function main() {
  arr = [a, b, c, d, e];
  arr.sort(function (A, B) {
    return A - B;
  });
  var min = arr[0];
  var bottleNeck = Math.ceil(n / min);
  console.log(4 + bottleNeck);
}
setUp(require("fs").readFileSync("/dev/stdin", "utf8"));


//https://atcoder.jp/contests/abc123/tasks/abc123_c
function setUp(input) {
  input = input.split("\n");
  n = Number(input[0]);
  a = Number(input[1]);
  b = Number(input[2]);
  c = Number(input[3]);
  d = Number(input[4]);
  e = Number(input[5]);
  main();
}
function main() {
  arr = [a, b, c, d, e];
  arr.sort(function (A, B) {
    return A - B;
  });
  var min = arr[0];
  var bottleNeck = 0;
  if (n > min) {
    bottleNeck = Math.floor((n / min) * 10) / 10;
  }
  console.log(5 + bottleNeck);
}
setUp(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(i) {
  i = i.split('\n');
  const N = Number(i[0]), a = Number(i[1]), b = Number(i[2]), c = Number(i[3]), d = Number(i[4]), e = Number(i[5]);
  const min = Math.min(a, b, c, d, e);
  console.log(Math.floor(N / min) + 5);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


var lines = [];

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

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

rl.on('close', function () {
    var tmp = lines.shift().split(" ");

    var X = Number(tmp[0]);
    var Y = Number(tmp[1]);
    var Z = Number(tmp[2]);
    var K = Number(tmp[3]);

    tmp = lines.shift().split(" ");
    var A = Array(tmp.length)
    for (var i = 0; i < A.length; i++) {
        A[i] = Number(tmp[i]);
    }

    tmp = lines.shift().split(" ");
    var B = Array(tmp.length)
    for (var i = 0; i < B.length; i++) {
        B[i] = Number(tmp[i]);
    }

    tmp = lines.shift().split(" ");
    var C = Array(tmp.length)
    for (var i = 0; i < C.length; i++) {
        C[i] = Number(tmp[i]);
    }

    var result = [];

    A.sort(function(a,b){return(b-a);});
    B.sort(function(a,b){return(b-a);});
    C.sort(function(a,b){return(b-a);});

    for (var a = 0; a < A.length; a++) {
        for (var b = 0; b < B.length; b++) {

            if ((a + 1) * (b + 1) > K) { break; }
            for (var c = 0; c < C.length; c++) {
                if ((a + 1) * (b + 1) * (c + 1) > K) { break; }

                result.push(A[a] + B[b] + C[c]);
            }
        }
    }

    result.sort(function (a, b) { return (b - a); });

    for (var i = 0; i < Math.min(3000, K); i++) {
        console.log(result[i]);
    }
});

Score: 400 points

Problem Statement

The Patisserie AtCoder sells cakes with number-shaped candles.
There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively.
Each cake has an integer value called deliciousness, as follows:

The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.

The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y.

The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z.

Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123.

There are X \times Y \times Z such ways to choose three cakes.

We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes.

Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list.

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

1 \leq K \leq \min(3 \ 000, X \times Y \times Z)

1 \leq A_i \leq 10 \ 000 \ 000 \ 000

1 \leq B_i \leq 10 \ 000 \ 000 \ 000

1 \leq C_i \leq 10 \ 000 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z K
A_1 \ A_2 \ A_3 \ ... \ A_X
B_1 \ B_2 \ B_3 \ ... \ B_Y
C_1 \ C_2 \ C_3 \ ... \ C_Z

Output

Print K lines. The i-th line should contain the i-th value stated in the problem statement.

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes:

(A_2, B_2, C_2): 6 + 5 + 8 = 19

(A_1, B_2, C_2): 4 + 5 + 8 = 17

(A_2, B_1, C_2): 6 + 1 + 8 = 15

(A_2, B_2, C_1): 6 + 5 + 3 = 14

(A_1, B_1, C_2): 4 + 1 + 8 = 13

(A_1, B_2, C_1): 4 + 5 + 3 = 12

(A_2, B_1, C_1): 6 + 1 + 3 = 10

(A_1, B_1, C_1): 4 + 1 + 3 = 8

Sample Input 2

3 3 3 5
1 10 100
2 20 200
1 10 100

Sample Output 2

400
310
310
301
301

There may be multiple combinations of cakes with the same sum of the deliciousness. For example, in this test case, the sum of A_1, B_3, C_3 and the sum of A_3, B_3, C_1 are both 301.
However, they are different ways of choosing cakes, so 301 occurs twice in the output.

Sample Input 3

10 10 10 20
7467038376 5724769290 292794712 2843504496 3381970101 8402252870 249131806 6310293640 6690322794 6082257488
1873977926 2576529623 1144842195 1379118507 6003234687 4925540914 3902539811 3326692703 484657758 2877436338
4975681328 8974383988 2882263257 7690203955 514305523 6679823484 4263279310 585966808 3752282379 620585736

Sample Output 3

23379871545
22444657051
22302177772
22095691512
21667941469
21366963278
21287912315
21279176669
21160477018
21085311041
21059876163
21017997739
20703329561
20702387965
20590247696
20383761436
20343962175
20254073196
20210218542
20150096547

Note that the input or output may not fit into a 32-bit integer type.


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(v)";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}
function QuickSelect(a,k){--k;for(var l=0,r=a.length-1,i,j,m,p,t;l<r;){i=l-1;p=a[m=l+r>>1];a[m]=a[j=r];while(1){while(i<j)if(a[++i]>p)break;while(i<j)if(a[--j]<p)break;if(i>=j)break;t=a[i];a[i]=a[j];a[j]=t;}a[r]=a[i];a[i]=p;if(i<k)l=i+1;else if(i>k)r=i-1;else break;}return a[k];}

console.log(main());
function main(){
  var x = o.a();
  var y = o.a();
  var z = o.a();
  var k = o.a();
  var a = o.l();
  var b = o.l();
  var c = o.l();
  var u = [];
  for(var i = 0; i < x; i++)for(var j = 0; j < y; j++){
    u.push(a[i]+b[j]);
  }
  if(k < u.length){
    u = solve(u,k);
  }
  var ans = [];
  for(var i = 0; i < z; i++)for(var j = 0; j < u.length; j++){
    ans.push(c[i]+u[j]);
  }
  if(k < ans.length){
    ans = solve(ans,k);
  }

  return ans.sort((a,b)=>b-a).join("\n");
}
function solve(a,k){
  var t = QuickSelect(a,a.length - k), v = [];
  for(var i = 0; i < a.length; i++){
    if(t < a[i])v.push(a[i]);
  }
  while(v.length < k)v.push(t);
  return v;
}


function Main(input) {
  const args = input.split(" ");
  if (valid(args[0]) || args[1] || args[2]) {
    return;
  }

  console.log(args[0] === args[1] && args[0] === args[2] ? 'Yes' : 'No');
}

function valid(num) {
  if (num < 1 || 100 < num) {
    return false;
  }
  return true;
}

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

Score : 100 points

Problem Statement

You are given three integers A, B and C.

Determine if there exists an equilateral triangle whose sides have lengths A, B and C.

Constraints

All values in input are integers.

1 \leq A,B,C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

If there exists an equilateral triangle whose sides have lengths A, B and C, print Yes; otherwise, print No.

Sample Input 1

2 2 2

Sample Output 1

Yes

There exists an equilateral triangle whose sides have lengths 2, 2 and 2.

Sample Input 2

3 4 5

Sample Output 2

No

There is no equilateral triangle whose sides have lengths 3, 4 and 5.


"use strict";
function I(s,f){this._s=s.split("\n");this._c=0;this._l=0;this._f=f||Number}I.prototype.a=function(){var l=this._s[this._l];if(!l)return;var t=l.trim().split(" ");var a=t[this._c];this._c++;if(t.length===this._c){this._c=0;this._l++}return this._f(a)};I.prototype.l=function(){var l=this._s[this._l];if(!l)return;this._c=0;this._l++;return l.split(" ").map(this._f)};
function buildArray(r,t){let l=t||0;for(let t=r.length;t>0;t--){const n=r[t-1];l=Array(n).fill().map(()=>JSON.parse(JSON.stringify(l)))}return l}

const mod = 1e9 + 7;
function abmod(){for(var a=arguments,r=a[0],i=1;i<a.length;)r=((r>>16)*a[i]%mod*65536+(r&65535)*a[i++])%mod;return r;}

function main(input) {
  const o = new I(input);

  const N = o.a();
  const X = o.a();

  const S = o.l();

  S.sort((a,b) => b - a);

  let dp1 = Array(X+1).fill(0);
  dp1[X] = 1;
  for (let i = 0; i< N; i++) {
    let dp2 = Array(X+1).fill(0);
    for (let j = 0; j<=X; j++) {
      dp2[j] += dp1[j] * (N-i-1);
      dp2[j] %= mod;

      let m = j%S[i];
      dp2[m] += dp1[j];
      dp2[m] %= mod;
    }
    dp1 = dp2;
  }

  let sum = 0;
  for(let i = 0; i < S[N-1]; i++){
    sum += abmod(i,dp1[i]);
  }

  console.log(sum % mod);
}

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

Score : 600 points

Problem Statement

Snuke has a blackboard and a set S consisting of N integers.
The i-th element in S is S_i.

He wrote an integer X on the blackboard, then performed the following operation N times:

Choose one element from S and remove it.

Let x be the number written on the blackboard now, and y be the integer removed from S. Replace the number on the blackboard with x \bmod {y}.

There are N! possible orders in which the elements are removed from S.
For each of them, find the number that would be written on the blackboard after the N operations, and compute the sum of all those N! numbers modulo 10^{9}+7.

Constraints

All values in input are integers.

1 \leq N \leq 200

1 \leq S_i, X \leq 10^{5}

S_i are pairwise distinct.

Input

Input is given from Standard Input in the following format:

N X
S_1 S_2 \ldots S_{N}

Output

Print the answer.

Sample Input 1

2 19
3 7

Sample Output 1

3

There are two possible orders in which we remove the numbers from S.

If we remove 3 and 7 in this order, the number on the blackboard changes as follows: 19 \rightarrow 1 \rightarrow 1.

If we remove 7 and 3 in this order, the number on the blackboard changes as follows: 19 \rightarrow 5 \rightarrow 2.

The output should be the sum of these: 3.

Sample Input 2

5 82
22 11 6 5 13

Sample Output 2

288

Sample Input 3

10 100000
50000 50001 50002 50003 50004 50005 50006 50007 50008 50009

Sample Output 3

279669259

Be sure to compute the sum modulo 10^{9}+7.


// inputに入力データ全体が入る
function Main(input) {
  switch(input){
    case 'A':
      console.log('T');
      break;
    case 'T':
      console.log('A');
      break;
    case 'G':
      console.log('C');
      break;
    case 'C':
      console.log('G');
      break;
  }
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter b as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base b.

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


function Main(input) {
  var output = {
    A: 'T',
    T: 'A',
    C: 'G',
    G: 'C'
  };
  console.log(output[input]);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


function Main(input) {
    var longest = 0;
    var current = 0;
    for(var i = 0; i < input.length; i++) {
        if(input[i] == "A" ||
        input[i] == "T" ||
        input[i] == "C" ||
        input[i] == "G"){
            if(current > longest) longest = current;
            current = 0;
            continue;
        }
        current++;
    }
    if(current > longest) longest = current;
    console.log(longest);
}

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

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

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

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


// inputに入力データ全体が入る
function Main(input) {
    input = input.split("\n");
    var s = input[0];
    var cnt = 0;
    var max = 0;
    for (var i = 0; i < s.length; i++) {
        var c = s[i];
        if (isACGT(c)) {
            cnt += 1;
        } else {
	        max = Math.max(max, cnt);
	        cnt = 0;
        }
    }
  	// 最後に抜けた時用
  	max = Math.max(max, cnt);
    console.log(max);
}

function isACGT(input) {
    switch(input) {
        case 'A':
        case 'T':
        case 'C':
        case 'G':
            return true;
        default: {
            return false;
        }
    }
}

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


const main = (s) => {
s = s.split('\n')
const length = s[0].split("")[0]
const questionNum = s[0].split(" ")[1]
const src = s[1]
var start = 0
var end = 0
const base = /AC/g
const questions = s.slice(2,2+questionNum)
questions.forEach(q=>{
	start = q.split(" ")[0]
  	end = q.split(" ")[1]
  	const result = src.substring(start-1,end).match(base)||[]
    console.log(result.length)
})
}

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

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


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

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

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

rl.on('close', function () {

    var tmp = lines.shift().split(" ");
    var N = Number(tmp[0]); var Q = Number(tmp[1]);

    var S = lines.shift();

    var l = Array(Q); var r = Array(Q);
    for (var i = 0; i < Q; i++) {
        tmp = lines[i].split(" ");
        l[i] = Number(tmp[0]);
        r[i] = Number(tmp[1]);
    }

    var sum = Array(N + 1).fill(0);
    for (var i = 1; i < N; i++) {
        sum[i + 1] = sum[i];
        if (S[i - 1] === "A", S[i] === "C") { sum[i + 1]++; }
    }

    for (var i = 0; i < Q; i++) {
        console.log(sum[r[i]] - sum[l[i]]);
    }
});


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', () => {
  var NQ = lines[0].split(" ");
  var N = +NQ[0];
  var Q = +NQ[1];
  var S = lines[1];
  var l = new Array(Q);
  var r = new Array(Q);
  for(var i = 0; i<Q; i++){
    var lr = lines[i+2].split(" ");
    l[i] = +lr[0];
    r[i] = +lr[1];
  }

  var ans = [];
  for(var i = 0; i<Q; i++){
    var slicedS = S.slice(l[i]-1,r[i]).match(/AC/g);
	ans.push(slicedS?slicedS.length:0)
  }
  console.log(ans.join("\n"));
});


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  var C = new Array(N);
  var mod = Math.pow(10,9)+7;
  var map=new Array(2*Math.pow(10,5)+1).fill(-1);
  var l =new Array(N).fill(1);
  var prev=-1;
  for(var i=0;i<N;i++){
    C[i]=parseInt(input[i+1]);
    if(i!=0){
      if(map[C[i]]!=-1&&C[i]!=prev){
        l[i]=(l[map[C[i]]]+l[i-1])%mod;
      }else{
        l[i]=l[i-1];
      }
    }
      map[C[i]]=i;
      prev=C[i];
  }
  var ans=l[N-1];

  console.log('%s', ans);
  return ans;
}
// "実行する"ボタンを押した時に実行される関数 (デバッグ用)
function debug(n){
  var input = document.getElementById("input"+n).value;
  var ans=Main(input);
  var result="WA";
  if(ans==document.getElementById("output"+n).value.split("\n")[0]){
    result="AC";
  }
  document.getElementById("result"+n).innerHTML=result;
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 700 points

Problem Statement

There are N stones arranged in a row. The i-th stone from the left is painted in the color C_i.

Snuke will perform the following operation zero or more times:

Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones.

Find the number of possible final sequences of colors of the stones, modulo 10^9+7.

Constraints

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

1 \leq C_i \leq 2\times 10^5(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
C_1
:
C_N

Output

Print the number of possible final sequences of colors of the stones, modulo 10^9+7.

Sample Input 1

5
1
2
1
2
2

Sample Output 1

3

We can make three sequences of colors of stones, as follows:

(1,2,1,2,2), by doing nothing.

(1,1,1,2,2), by choosing the first and third stones to perform the operation.

(1,2,2,2,2), by choosing the second and fourth stones to perform the operation.

Sample Input 2

6
4
2
5
4
2
4

Sample Output 2

5

Sample Input 3

7
1
3
1
2
3
3
2

Sample Output 3

5


"use strict";
const main = input => {
    const n = parseInt(input[0].split(' ')[0], 10);
    const m = parseInt(input[0].split(' ')[1], 10);
    const c = parseInt(input[0].split(' ')[2], 10);

     var b=[];
     b = input[1].split(" ").map(Number);

    var  i,k = 0;var cnt = 0;
  for(i=0; i<n; i++) {
     var total = 0;
     let a = input[i+2].split(' ').map(Number);;
        for( k=0; k<m; k++) {
            total =total + a[k]*b[k];
      //    console.log(a[k],b[k],total);
        }
        if (total+c>0) {
            cnt++;
              }
    }
    console.log(cnt);

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

Score : 200 points

Problem Statement

There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.

Additionally, you are given integers B_1, B_2, ..., B_M and C.

The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.

Among the N codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

Output

Print the number of codes among the given N codes that correctly solve this problem.

Sample Input 1

2 3 -10
1 2 3
3 2 1
1 2 2

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.

1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.


"use strict";

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

    let obj = [];

    for(let i in temp) {
        obj[i] = {};
        obj[i].price = temp[i].split(" ")[0];
        obj[i].stock = temp[i].split(" ")[1];
    }

    obj.sort((a,b)=>(a.price - b.price));

    let done = 0;
    let need = M;
    let ans  = 0;

    for(let i in obj) {
        if(obj[i].stock < need) {
            ans += parseInt(obj[i].price * obj[i].stock);
            done += parseInt(obj[i].stock);
            need -= parseInt(obj[i].stock);
        } else {
            ans += parseInt(obj[i].price * need);
            done += parseInt(need);
            console.log(parseInt(ans));
        }
    }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

The output may not fit into a 32-bit integer type.


'use strict';
console.log(function(args){
  const _tmp = args.trim().split(' ');
  const A = _tmp[0]|0, B = _tmp[1]|0;
  let K = _tmp[2]|0;
  const divisor = [];
  for ( let i = A; i >= 1; i-- ) {
    if ( A%i === 0 ) divisor.push(i);
  }
  for ( let j of divisor ) {
    if ( B%j === 0 && --K === 0 ) return j.toString();
  }
  return '1';
}(require('fs').readFileSync('/dev/stdin', 'utf8')));

Score : 200 points

Problem Statement

You are given positive integers A and B.

Find the K-th largest positive integer that divides both A and B.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

The K-th largest positive integer that divides both A and B exists.

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the K-th largest positive integer that divides both A and B.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


function Main(input) {
    input = input.split(" ").map(Number);
    var sum = 0;
    for(var i=Math.min(input[0],input[1]);true;i--){
        if(input[0]%i==0&&input[1]%i==0) sum++;
        if(sum == input[2]){
            console.log(i);
            break;
        }
    }
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


"use strict"

function Main(stdin){
stdin = stdin.trim().split("\n").reverse();
var stdout = [];
function input(){return stdin.pop()};
function print(x){stdout.push(x)};
function mapint(x){return x.map(n=>parseInt(n))};
function max(x){return x.reduce(function(a,b){ return Math.max(a,b) }) }
function min(x){return x.reduce(function(a,b){ return Math.min(a,b) }) }
function sum(x){return x.reduce(function(a,b){ return a+b }) }

var tmp = mapint(input().split(" "))
var a = tmp[0]
var b = tmp[1]
var k = tmp[2]
var x = [1]
for (var i = 2; i < Math.min(a,b) + 1; i++){
    if (a%i==0 && b%i==0){ x.push(i) }
}
print(x[x.length - k])

stdout = stdout.join("\n");
console.log(stdout);
return stdout
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"))


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

    //console.log(a,b,c);
    function divisor(num){
    var results = [];
   for(var i=1; i<=num; i++) {
        if( (num%i == 0) ) {
            results.push(i);
        }
    }
    return results;

    }
// テスト
p = divisor(a);
//console.log(p);
  q = divisor(b);
//console.log(q);
p1=p.length;q1=q.length;
//console.log(p1,q1);
var cnt =0;

ppp = [];qqq=[];
  if (p1 >= q1){
     for(i = 0;i<q1;i++){
      for (l=i;l<p1;l++){ if(q[i]==p[l]){ppp[cnt] = p[l];
                                     cnt =cnt +1;
                                   //  console.log(ppp);
                                     break; }

                        }
                       }
                   }
  else
    { for(i = 0;i<p1;i++){
      for (l=i;l<q1;l++){ if(p[i]==q[l]){ppp[cnt] = q[l];
                                     cnt =cnt +1;
                                  //   console.log(ppp);
                                     break; }
                         }
                         }
                        }

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


function Main(input){
    i=input.split("").map(Number);
    n=true
    sum=0;
    sumi=0;
    while(n){
        for(a=0;a<=i.length-1;a++){
            if(a===0)sumi=i.length;
            if(i[a]+i[a+1]===1){
                sum++;
                i.splice(a, 2);
                break;
            }
            if(a>=sumi-1&&sumi==i.length)n=false
        }
        if(i.length==0)n=false
    }
    console.log(sum*2)
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1.

You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them.

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

All four cubes can be removed, by performing the operation as follows:

Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube.

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


//↓見なくていいよ！ここから--------------------------------------------------
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){
  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 M = one[1];
	var list = new Array(M);
	for(var i = 0; i < M; i++){
		list[i] = nextIntArray();
	}
	var uf = unionFind(N);
	list.sort(function(){return 1});
	var output = new Array(M);
	output[0] = N * (N - 1) / 2;
	for(var i = 1; i < M; i++){
		var tmp = list[i - 1];
		var L = tmp[0] - 1;
		var R = tmp[1] - 1;
		var minus = uf.getSize(L) * uf.getSize(R);
		output[i] = output[i - 1] - minus;
		if(output[i] < 0){
			output[i] = 0;
		}
		uf.doUnion(L, R);
	}
	output.sort(function(){return 1});
	myout(myconv(output,9));
}
function unionFind(n){
  var uf = {
    //全てのインデックスは「-X(親、絶対値はグループの大きさ)」「自分が属する親(≒根)」のいずれかを持つ。
    //最初はみんなグループの大きさ1の親
    "list" : new Array(n).fill(-1),

    //同じ親を持つか
    "isSame" : function(mae, ato){
      return this.getRootIndex(mae) == this.getRootIndex(ato);
    },
    //自身の親インデックスをたどって根っこに着く
    //親にたどり終えたら子に帰っていくついでに、子たちに「共通の親を持っている」ことを知らせる
    "getRootIndex" : function(index){
      if(this.list[index] < 0){
        return index;
      }else{
        this.list[index] = this.getRootIndex(this.list[index]);
        return this.list[index];
      }
    },
    //異なる親同士のまとまりを一つにする（同じ親ならスルー）
    //小さいグループの親が大きいグループの親の直下に着く
    //グループの大きさも更新する
    "doUnion" : function(mae, ato){
      var maeRoot = this.getRootIndex(mae);
      var atoRoot = this.getRootIndex(ato);
      if(!this.isSame(maeRoot, atoRoot)){
        if(maeRoot >= atoRoot){
          this.list[maeRoot] += this.list[atoRoot];
          this.list[atoRoot] = maeRoot;
        }else{
          this.list[atoRoot] += this.list[maeRoot];
          this.list[maeRoot] = atoRoot;
        }
      }
    },
    //「-X(親、絶対値はグループの大きさ)」
    //なので、インデックスを指定→親を知る→親の持つグループの大きさがわかる。
    //ただしマイナス値なので、掛け算して返す。
    "getSize" : function(index){
      return -this.list[this.getRootIndex(index)];
    }
  }
  return uf;
}

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


// 配列に全部の島のデータを突っ込む
// 各島はparent,sizeから成る、自分がどの島かはインデックスで判断。

function init_islands(n){
  var islands = [];
  for(var i=0; i<n; i++){
    islands[i] = {
      parent: i,
      size: 1,
    }
  }
  return islands;
}

function same_group(left_index, right_index, islands){
  const right_root = root(right_index, islands);
  const left_root = root(left_index, islands);
  return (right_root == left_root);
}

function merge_islands(left_index, right_index, islands){
  if(same_group(left_index, right_index, islands)){return;}
  const right_root = root(right_index, islands);
  const left_root = root(left_index, islands);
  left_root.size = left_root.size + right_root.size;
  right_root.parent = left_index;
}

function root(index, islands){
  var node = islands[index];

  if(node.parent==index){return node;}

  var root_node = root(node.parent, islands);
  node.parent = root_node.parent;
  return root_node;

}

function get_size(index, islands){
  var root_node = root(index, islands);
  return root_node.size;
}

function main(input) {
  const formatted_input = input.split('\n').map( x => x.split(' ').map( x => parseInt(x, 10) ) );
  const N = formatted_input[0][0];
  const M = formatted_input[0][1];
  var reverse_bridges = [];

for(var i=0;i<M;i++){
  reverse_bridges.push(formatted_input[1+i]);
}
reverse_bridges = reverse_bridges.reverse();

  var islands = init_islands(N);

  var unconvinience = N*(N-1)/2;
  var results = [unconvinience];

  for(bridge of reverse_bridges){
    left_index = bridge[0]-1
    right_index =  bridge[1]-1

var hoge = false;

try {

  var right_root = root(right_index, islands);
  var left_root = root(left_index, islands);
  hoge = (right_root == left_root);
//var hoge = same_group(left_index, right_index, islands);

}catch (e) {
if(e instanceof RangeError) {
    console.log(1);return;
}else{
throw e;
}
}

    if(!hoge){
      var diff = get_size((left_index), islands) * get_size(right_index, islands);
      unconvinience -= diff;
    }

    results.push(unconvinience);

    merge_islands(left_index, right_index, islands);

  }

  const reversed_result = results.reverse();

  for(var i = 1; i<=M ; i++){
    console.log(reversed_result[i]);
  }
}

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

//02:05:00 >


// 配列に全部の島のデータを突っ込む
// 各島はparent,sizeから成る、自分がどの島かはインデックスで判断。

function init_islands(n){
  var islands = [];
  for(var i=0; i<n; i++){
    islands[i] = {
      parent: i,
      size: 1,
    }
  }
  return islands;
}

function same_group(left_index, right_index, islands){
  const right_root = root(right_index, islands);
  const left_root = root(left_index, islands);
  return (right_root == left_root);
}

function merge_islands(left_index, right_index, islands){
  if(same_group(left_index, right_index, islands)){return;}
  const right_root = root(right_index, islands);
  const left_root = root(left_index, islands);
  left_root.size = left_root.size + right_root.size;
  right_root.parent = left_index;
}

function root(index, islands){
  var node = islands[index];

  if(node.parent==index){return node;}

  var root_node = root(node.parent, islands);
  node.parent = root_node.parent;
  return root_node;

}

function get_size(index, islands){
  var root_node = root(index, islands);
  return root_node.size;
}

function main(input) {
  const formatted_input = input.split('\n').map( x => x.split(' ').map( x => parseInt(x, 10) ) );
  const N = formatted_input[0][0];
  const M = formatted_input[0][1];
  var reverse_bridges = [];

for(var i=0;i<M;i++){
  reverse_bridges.push(formatted_input[1+i]);
}
reverse_bridges = reverse_bridges.reverse();

  var islands = init_islands(N);

  var unconvinience = N*(N-1)/2;
  var results = [unconvinience];

  for(bridge of reverse_bridges){
    left_index = bridge[0]-1
    right_index =  bridge[1]-1

try {
var hoge = same_group(left_index, right_index, islands)
}catch (e) {
if(e instanceof RangeError) {
    console.log(1);return;
}else{
throw e;
}
}

    if(!hoge){
      var diff = get_size((left_index), islands) * get_size(right_index, islands);
      unconvinience -= diff;
    }

    results.push(unconvinience);

    merge_islands(left_index, right_index, islands);

  }

  const reversed_result = results.reverse();

  for(var i = 1; i<=M ; i++){
    console.log(reversed_result[i]);
  }
}

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

//02:05:00 >


// 配列に全部の島のデータを突っ込む
// 各島はparent,sizeから成る、自分がどの島かはインデックスで判断。

function init_islands(n){
  var islands = [];
  for(var i=0; i<n; i++){
    islands[i] = {
      parent: i,
      size: 1,
    }
  }
  return islands;
}

function same_group(left_index, right_index, islands){
  const right_root = root(right_index, islands);
  const left_root = root(left_index, islands);
  return (right_root == left_root);
}

function merge_islands(left_index, right_index, islands){
  if(same_group(left_index, right_index, islands)){return;}
  const right_root = root(right_index, islands);
  const left_root = root(left_index, islands);
  left_root.size = left_root.size + right_root.size;
  right_root.parent = left_index;
}

function root(index, islands){
  var node = islands[index];

  if(node.parent==index){return node;}

  var root_node = root(node.parent, islands);
  node.parent = root_node.parent;
  return root_node;
}

function get_size(index, islands){
  var root_node = root(index, islands);
  return root_node.size;
}

function main(input) {
  const formatted_input = input.split('\n').map( x => x.split(' ').map( x => parseInt(x, 10) ) );
  const N = formatted_input[0][0];
  const M = formatted_input[0][1];
  var reverse_bridges = [];

hoge()

for(var i=0;i<M;i++){
  reverse_bridges.push(formatted_input[1+i]);
}
reverse_bridges = reverse_bridges.reverse();

  var islands = init_islands(N);

  var unconvinience = N*(N-1)/2;
  var results = [unconvinience];

  for(bridge of reverse_bridges){
    //console.log(bridge);

    left_index = bridge[0]-1
    right_index =  bridge[1]-1

    if(!same_group(left_index, right_index, islands)){
      var diff = get_size((left_index), islands) * get_size(right_index, islands);
      unconvinience -= diff;
    }
    results.push(unconvinience);

    merge_islands(left_index, right_index, islands);
  }

  const reversed_result = results.reverse();

  for(var i = 1; i<=M ; i++){
    console.log(reversed_result[i]);
  }
}

function hoge(){
hoge()
}

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

//02:05:00 >


'use strict';
// d
class Main {
  solve() {
    const nums = input.nextIntArr();
    const table = input.nextIntRange(nums[1]);
    const uf = new UnionFind(nums[0],['count']);
    table.reverse();
    let remain = nums[0] * (nums[0] - 1) / 2;
    const result = [];
    const counts = [...Array(nums[0])].map((e) => 1);

    for (const node of table) {
      result.push(remain);
      const n = node.map(e=>e-1);
      remain -= (uf.same(...n) ? 0 : (uf.size(n[0]) * uf.size(n[1])));
      uf.unite(...n);
    }
    console.log(result.reverse().join('\n'));
  }
}

class Unit {
  constructor(name) { this.name = name; this.data = []; }
  get(rx) { return this.data[rx]; }
  set(x,value) { this.data[x] = value; return this.data[x]; }
  set init(func) { this._init = func; }
  set union(func) { this._union = func; }
  get init() { return this._init; }
  get union() { return this._union }
}

class UnionFind {
  constructor(n, options) {
    this.units = {};
    this.units['ref'] = UnionFind._ref;
    for (const o of options) {
      if (o === 'count') { this.units['count'] = UnionFind.Counter; }
      else if (o instanceof Unit) { this.units[o.name] = o; }
    }
    for (const name in this.units) {
      const unit = this.units[name];
      for (let i = 0;i < n; ++i) { unit.init(i); }
    }
  }

  root(x) {
    if (this.units.ref.get(x) == x) return x;
    return this.units.ref.set(x, this.root(this.units.ref.get(x)));
  }

  get(name, x) {
    return this.units[name].get(this.root(x));
  }
  size(x) { return this.get('count', x); }

  unite(x, y) { // xとyの木を併合
    const rx = this.root(x); const ry = this.root(y);
    const rmax = Math.max(rx,ry); const rmin = Math.min(rx,ry);
    for (const name in this.units) {
      const u = this.units[name];
      u.union(x,y,rmin,rmax);
    }
    return true;
  }

  same(x, y) { // 2つのデータx, yが属する木が同じならtrueを返す
    const rx = this.root(x);
    const ry = this.root(y);
    return rx == ry;
  }

  static get _ref() {
    const u = new Unit('ref');
    u.init = ((i) => u.data[i] = i);
    u.union = ((x,y,rmin,rmax) => {
      if (rmax == rmin) return;
      u.data[rmax] = rmin;
    });
    return u;
  }

  static get Counter() {
    const u = new Unit('count');
    u.init = ((i) => u.data[i] = 1);
    u.union = ((x,y,rmin,rmax) => {
      if (rmax == rmin) return;
      u.data[rmin] = u.data[rmax] + u.data[rmin];
    });
    return u;
  }
}

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

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

  nextLine(n) {
    if (n) {
      const ret = this.data.slice(this.cursor, this.cursor + n);
      this.cursor += n;
      return ret;
    }
    return this.data[this.cursor++];
  }

  nextStrArr() {
    return this.nextLine().split(' ');
  }

  nextIntArr() {
    return this.nextStrArr().map((e) => parseInt(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)));
  }
}
const input = new Input();

(new Main()).solve();


'use strict';
// d
class Main {
  solve() {
    const nums = input.nextIntArr();
    const table = input.nextIntRange(nums[1]);
    const uf = new UnionFind(nums[0]);
    table.reverse();
    let remain = nums[0] * (nums[0] - 1) / 2;
    const result = [];
    result.push(remain);
    const counts = [...Array(nums[0])].map((e) => 1);

    for (const node of table) {
      const n = node.map(e=>e-1);
      remain -= (uf.same(...n) ? 0 : (uf.size(n[0]) * uf.size(n[1])));
      uf.unite(...n);
      result.push(remain);
    }
    console.log(result.reverse().slice(1).join('\n'));
  }
}

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

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

  nextLine(n) {
    if (n) {
      const ret = this.data.slice(this.cursor, this.cursor + n);
      this.cursor += n;
      return ret;
    }
    return this.data[this.cursor++];
  }

  nextStrArr() {
    return this.nextLine().split(' ');
  }

  nextIntArr() {
    return this.nextStrArr().map((e) => parseInt(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)));
  }
}

class UnionFind {
  constructor(n) {
    this.ref = [];
    this.count = [];
    for (let i = 0;i < n; ++i) {
      this.ref[i] = i;
      this.count[i] = 1;
    }
  }

  root(x) {
    if (this.ref[x] == x) return x;
    return this.ref[x] = this.root(this.ref[x]);
  }

  size(x) {
    return this.count[this.root(x)];
  }

  unite(x, y) { // xとyの木を併合
    const rx = this.root(x);
    const ry = this.root(y);
    if (rx == ry) return; //xとyの根が同じ(=同じ木にある)時はそのまま
    this.ref[Math.max(rx,ry)] = Math.min(rx,ry); //xとyの根が同じでない(=同じ木にない)時, rx,ryの小さい方を根とする
    this.count[Math.min(rx,ry)] = this.count[rx] + this.count[ry];
  }

  same(x, y) { // 2つのデータx, yが属する木が同じならtrueを返す
    const rx = this.root(x);
    const ry = this.root(y);
    return rx == ry;
  }
}

const input = new Input();
(new Main()).solve();


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

const nenn = Number(input.split('').slice(0, 4).join(''));

const month = Number(input.split('').slice(5, 7).join(''));

const hi = Number(input.split('').slice(8, 10).join(''));

if (nenn < 2019) {
  console.log('Heisei');
} else if(month < 5) {
  console.log('Heisei');
} else {
  console.log('TBD');
}

Score : 100 points

Problem Statement

You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)

Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.

Constraints

S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format.

Input

Input is given from Standard Input in the following format:

S

Output

Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise.

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


"use strict";
function Main(input) {
    let lines = input.split("\n");
    let N = lines[0] - 0;
    let sum = 0;
    for (let n = 1; n <= N; n++) {
        let xv = lines[n].split(/\s/);
        let x = xv[0] - 0;
        sum += (xv[1] == 'BTC') ? x * 380000.0 : x;
    }

    console.log(sum);
}

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

Score : 200 points

Problem Statement

Takahashi received otoshidama (New Year's money gifts) from N of his relatives.

You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either JPY or BTC, and x_i and u_i represent the content of the otoshidama from the i-th relative.

For example, if x_1 = 10000 and u_1 = JPY, the otoshidama from the first relative is 10000 Japanese yen; if x_2 = 0.10000000 and u_2 = BTC, the otoshidama from the second relative is 0.1 bitcoins.

If we convert the bitcoins into yen at the rate of 380000.0 JPY per 1.0 BTC, how much are the gifts worth in total?

Constraints

2 \leq N \leq 10

u_i = JPY or BTC.

If u_i = JPY, x_i is an integer such that 1 \leq x_i \leq 10^8.

If u_i = BTC, x_i is a decimal with 8 decimal digits, such that 0.00000001 \leq x_i \leq 100.00000000.

Input

Input is given from Standard Input in the following format:

N
x_1 u_1
x_2 u_2
:
x_N u_N

Output

If the gifts are worth Y yen in total, print the value Y (not necessarily an integer).

Output will be judged correct when the absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
10000 JPY
0.10000000 BTC

Sample Output 1

48000.0

The otoshidama from the first relative is 10000 yen. The otoshidama from the second relative is 0.1 bitcoins, which is worth 38000.0 yen if converted at the rate of 380000.0 JPY per 1.0 BTC. The sum of these is 48000.0 yen.

Outputs such as 48000 and 48000.1 will also be judged correct.

Sample Input 2

3
100000000 JPY
100.00000000 BTC
0.00000001 BTC

Sample Output 2

138000000.0038

In this case, outputs such as 138001000 and 1.38e8 will also be judged correct.


function Main(input){
  input = input.split("\n");
  inputStr = input[0].split(" ");
  const N = Number.parseInt(inputStr[0]);
  const A = Number.parseInt(inputStr[1]);
  const B = Number.parseInt(inputStr[2]);
  const C = Number.parseInt(inputStr[3]);
  var tg = [A,B,C];
  tg.sort(function(a,b){
        if( a < b ) return -1;
        if( a > b ) return 1;
        return 0;
  });
  var bb = [];
  //N本の竹の長さを配列bbに格納する
  for( var i=0 ; i<N ; i++ ){
    bb.push(Number.parseInt(input[i+1].split(" ")));
  }
  bb.push(Number.MAX_VALUE);
  //竹を成長させる探索処理
  var MP = 0;

  //console.log("最初",bb);

  //長さが一致する竹を対象一覧(配列tg、bb)から排除する
  for(var i=0 ; i<tg.length ; i++){
    var tmp = bb.indexOf(tg[i]);
    if(tmp>0){
      tg.splice(i,1);
      bb.splice(tmp,1);
    }
  }

  //console.log("排除",bb);

  //育った要素から順にtgから削除していく。
  while( tg.length > 0){
    //最も近似する場所を求める
    var t1 = Math.abs(tg[0]-bb[0]);
    var pmemo = [0,0];
    for( var j=1 ; j<bb.length ; j++){
      var t2 = Math.abs(tg[0]-bb[j]);
      if(t1>t2){
        t1 = t2;
        pmemo[0] = j;
      }
    }

    //2本の竹を足して再度考えてみる
    if(t1>10){
      var c_flg = false;
      for(var k=0 ; k<bb.length-1 ; k++){
        for(var r=k+1 ; r<bb.length ; r++){
          t2 = Math.abs(tg[0]-(bb[k]+bb[r]));
          if( t1 > t2 ){
            t1 = t2;
            pmemo[0] = k;
            pmemo[1] = r;
            c_flg = true;
          }
        }
      }
    }

    //絶対値との差異(t1)をMPとして足しこみ、bbから要素を削除する
    if(c_flg === true){
      //console.log("2本を1本に");
      MP += 10;
      //最後の1つ手前に追加
      bb.splice(bb.length-1,0,bb[pmemo[0]]+bb[pmemo[1]]);
      //追加した元ねたの削除
      bb.splice(pmemo[1],1);
      bb.splice(pmemo[0],1);
    } else {
      MP += t1;
      tg.splice(0,1);
      //console.log("bbから消す値=",bb[pmemo[0]]);

      //console.log("bbの何処の値を消す",pmemo[0]);

      bb.splice(pmemo[0],1);
      i++;
    }
    //console.log("処理後tg",tg);
    //console.log("処理後bb",bb);
    c_flg = false;
    pmemo[0]=0;
    pmemo[1]=0;
  }
  console.log(MP);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


function Main(input){
  input = input.split("\n");
  inputStr = input[0].split(" ");
  const N = Number.parseInt(inputStr[0]);
  const A = Number.parseInt(inputStr[1]);
  const B = Number.parseInt(inputStr[2]);
  const C = Number.parseInt(inputStr[3]);
  var tg = [A,B,C];
  var bb = [];
  //N本の竹の長さを配列bbに格納する
  for( var i=0 ; i<N ; i++ ){
    bb.push(Number.parseInt(input[i+1].split(" ")));
  }
  bb.push(Number.MAX_VALUE);
  //竹を成長させる探索処理
  var MP = 0;

  //console.log("最初",bb);

  //長さが一致する竹を対象一覧(配列tg、bb)から排除する
  for(var i=0 ; i<tg.length ; i++){
    var tmp = bb.indexOf(tg[i]);
    if(tmp>0){
      tg.splice(i,1);
      bb.splice(tmp,1);
    }
  }

  //console.log("排除",bb);

  //育った要素から順にtgから削除していく。
  while( tg.length > 0){
    //最も近似する場所を求める
    var t1 = Math.abs(tg[0]-bb[0]);
    var pmemo = [0,0];
    for( var j=1 ; j<bb.length ; j++){
      var t2 = Math.abs(tg[0]-bb[j]);
      if(t1>t2){
        t1 = t2;
        pmemo[0] = j;
      }
    }

    //2本の竹を足して再度考えてみる
    if(t1>10){
      var c_flg = false;
      for(var k=0 ; k<bb.length-1 ; k++){
        for(var r=k+1 ; r<bb.length ; r++){
          t2 = Math.abs(tg[0]-(bb[k]+bb[r]));
          if( t1 > t2 ){
            t1 = t2;
            pmemo[0] = k;
            pmemo[1] = r;
            c_flg = true;
          }
        }
      }
    }

    //絶対値との差異(t1)をMPとして足しこみ、bbから要素を削除する
    if(c_flg === true){
      //console.log("2本を1本に");
      MP += 10;
      //最後の1つ手前に追加
      bb.splice(bb.length-1,0,bb[pmemo[0]]+bb[pmemo[1]]);
      //追加した元ねたの削除
      bb.splice(pmemo[1],1);
      bb.splice(pmemo[0],1);
    } else {
      MP += t1;
      tg.splice(0,1);
      //console.log("bbから消す値=",bb[pmemo[0]]);

      //console.log("bbの何処の値を消す",pmemo[0]);

      bb.splice(pmemo[0],1);
      i++;
    }
    //console.log("処理後tg",tg);
    //console.log("処理後bb",bb);
    c_flg = false;
    pmemo[0]=0;
    pmemo[1]=0;
  }
  console.log(MP);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function calc_mp(depth,N,ABC,abc,ls){
//console.log([depth,N,ABC,abc,ls]);
  if(depth==N){
//console.log(Math.abs(ABC[0]-abc[0])+Math.abs(ABC[1]-abc[1])+Math.abs(ABC[2]-abc[2]));
    return Math.abs(ABC[0]-abc[0])+Math.abs(ABC[1]-abc[1])+Math.abs(ABC[2]-abc[2]);
  }

  const ret0 = calc_mp(depth+1, N, ABC, abc, ls);
  var ret1 = calc_mp(depth+1, N, ABC, [abc[0]+ls[depth], abc[1], abc[2]], ls)+10;
  if(abc[0]==0){ret1-=10;}
  var ret2 = calc_mp(depth+1, N, ABC, [abc[0], abc[1]+ls[depth], abc[2]], ls)+10;
  if(abc[1]==0){ret2-=10;}
  var ret3 = calc_mp(depth+1, N, ABC, [abc[0], abc[1], abc[2]+ls[depth]], ls)+10;
  if(abc[2]==0){ret3-=10;}

  return Math.min(ret0, ret1, ret2, ret3);
}

function main(input){
  const lines = input.split('\n');
  const N = lines[0].split(' ').map(x => parseInt(x))[0];
  const A = lines[0].split(' ').map(x => parseInt(x))[1];
  const B = lines[0].split(' ').map(x => parseInt(x))[2];
  const C = lines[0].split(' ').map(x => parseInt(x))[3];
  var Ls = lines.map(x => parseInt(x));
  Ls.shift();

  const result = calc_mp(0,N,[A,B,C],[0,0,0],Ls);
  console.log(result);
}

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