// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
    start = input[0].split(" ");
    var sc = parseInt(start[0],10);//神社の数
    var tc = parseInt(start[1],10);//寺の数
    var qc = parseInt(start[2],10);//問題の数

    // 神社を配列に
    var sa = [];
    for(var i = 1; i <= sc; i++){
        sa.push(input[i]);
    }

    // 寺を配列に
    var ta = [];
    for(var i = 1; i <= tc; i++){
        ta.push(input[i + sc]);
    }

    for(var i = 1; i <= qc; i++){
        var ql = input[i + sc + tc];
        var movement = null;
        for(var s = 0; s < sa.length; s++){
            for(var t = 0; t < ta.length; t++){
                //　神社と寺の組み合わせ
                var sl = sa[s];// 西から神社までの距離
                var tl = ta[t];// 西から寺までの距離
                // 神社からいった場合
                var ans = Math.abs(sl - tl) + Math.min(Math.abs(ql - sl),Math.abs(ql - tl));
                movement = (movement == null || movement > ans) ? ans : movement;
            }
        }
        console.log("%d",movement);
    }
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

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

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
    start = input[0].split(" ");
    var sc = parseInt(start[0],10);//神社の数
    var tc = parseInt(start[1],10);//寺の数
    var qc = parseInt(start[2],10);//問題の数

    // 神社を配列に
    var sa = [];
    for(var i = 1; i <= sc; i++){
        sa.push(input[i]);
    }

    // 寺を配列に
    var ta = [];
    for(var i = 1; i <= tc; i++){
        ta.push(input[i + sc]);
    }

    for(var i = 1; i <= qc; i++){
        var ql = input[i + sc + tc];
        var movement = null;
        for(var s = 0; s < sa.length; s++){
            for(var t = s; t < ta.length; t++){
                //　神社と寺の組み合わせ
                var sl = sa[s];// 西から神社までの距離
                var tl = ta[t];// 西から寺までの距離
                // 神社からいった場合
                var ans = Math.abs(sl - tl) + Math.min(Math.abs(ql - sl),Math.abs(ql - tl));
                movement = (movement == null || movement > ans) ? ans : movement;
            }
        }
        console.log("%d",movement);
    }
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
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.


var input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
var obj = {
  "list" : input,
  "index" : 0,
  "max" : input.length,
  "next" : function(){
    if(!this.hasNext()){throw "NoSuchElementException:次に要素は無いよ";}
    var returnObj = this.list[this.index];
    this.index++;
    return returnObj;
  },
  "hasNext" : function(){return (this.index < this.max);}
}
function next(){return obj.next();}
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
function hasNext(){return obj.hasNext();}
function myout(t){console.log(t);}//標準出力
function myerr(t){console.error(t);}//標準エラー出力
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す　1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
Main();
function Main(){
  var one = nextIntArray();
  var A = one[0];
  var B = one[1];
  if(B % A == 0){
     myout(A + B);
  }else{
     myout(A - B);
  }
}

Score : 100 points

Problem Statement

You are given positive integers A and B.

If A is a divisor of B, print A + B; otherwise, print B - A.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

If A is a divisor of B, print A + B; otherwise, print B - A.

Sample Input 1

4 12

Sample Output 1

16

As 4 is a divisor of 12, 4 + 12 = 16 should be printed.

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.


function Main(input) {

    input = input.split("");

    var a = input[0]
    var b = input[1]

    if (b % a == 0) {
        console.log(a + b);
    } else if {
        console.log(b - a);
    }
}

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


function main(input) {
    const nums = input.trim().split(/\s/).map(str=>Number(str));
    const res = nums[1] % nums[0] === 0 ? nums[1] + nums[0] : nums[1] - nums[0];
    console.log(res);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


'use strict'

const main = (INPUT) => {
  const input = INPUT.split('\n')
  const [N, M] = input[0].split(' ')
  const K = input.slice(1)
  let ans = Array.from(new Array(Number(M))).map((v, i) => i + 1)
  for (let i = 0; i < K.length; i++) {
    const tmp = K[i].split(' ').slice(1).map(n => Number(n))
    for (let j = 0; j < ans.length; j++) {
      if (!tmp.includes(ans[j])) {
        ans[j] = null
      }
    }
  }
  console.log(ans.filter(v => v != null).length)
}

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

Score : 200 points

Problem Statement

Katsusando loves omelette rice.

Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.

To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not.

The i-th person answered that he/she only likes the A_{i1}-th, A_{i2}-th, ..., A_{iK_i}-th food.

Find the number of the foods liked by all the N people.

Constraints

All values in input are integers.

1 \leq N, M \leq 30

1 \leq K_i \leq M

1 \leq A_{ij} \leq M

For each i (1 \leq i \leq N), A_{i1}, A_{i2}, ..., A_{iK_i} are distinct.

Constraints

Input is given from Standard Input in the following format:

N M
K_1 A_{11} A_{12} ... A_{1K_1}
K_2 A_{21} A_{22} ... A_{2K_2}
:
K_N A_{N1} A_{N2} ... A_{NK_N}

Output

Print the number of the foods liked by all the N people.

Sample Input 1

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

Sample Output 1

1

As only the third food is liked by all the three people, 1 should be printed.

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3


function Main(input) {
    input = input.split('\n');
    var n = parseInt(input[0], 10)
    var items = input[1].split(' ').map(function(item) {
        return parseInt(item, 10)
    });
    var min = Math.pow(10, 9) + 1
    var odds = [];
    var evens = [];
    for (var i = 0; i < n; i++) {
        if (items[i] === 1) {
            console.log(1);
            return;
        }
        if (min > items[i]) min = items[i]
        if (items[i] % 2 === 0) {
            if (evens.indexOf(items[i] === -1)) evens.push(items[i])
        } else {
            if (odds.indexOf(items[i] === -1)) odds.push(items[i])
        }
        if (odds.length > 1 || (evens.length > 0 && odds.length > 0)) {
            console.log(1);
            return;
        };
    }
    console.log(min)
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

There are N monsters, numbered 1, 2, ..., N.

Initially, the health of Monster i is A_i.

Below, a monster with at least 1 health is called alive.

Until there is only one alive monster, the following is repeated:

A random alive monster attacks another random alive monster.

As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.

Find the minimum possible final health of the last monster alive.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible final health of the last monster alive.

Sample Input 1

4
2 10 8 40

Sample Output 1

2

When only the first monster keeps on attacking, the final health of the last monster will be 2, which is minimum.

Sample Input 2

4
5 13 8 1000000000

Sample Output 2

1

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

1000000000


'use strict'

const main = (INPUT) => {
  const N = Number(INPUT.split('\n')[0].split(' ')[0])
  const K = Number(INPUT.split('\n')[0].split(' ')[1])

  if ((N + 1) / 2 > K) {
    console.log('YES')
  } else {
    console.log('NO')
  }
}

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

Score : 100 points

Problem Statement

Determine if we can choose K different integers between 1 and N (inclusive) so that no two of them differ by 1.

Constraints

1\leq N,K\leq 100

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

If we can choose K integers as above, print YES; otherwise, print NO.

Sample Input 1

3 2

Sample Output 1

YES

We can choose 1 and 3.

Sample Input 2

5 5

Sample Output 2

NO

Sample Input 3

31 10

Sample Output 3

YES

Sample Input 4

10 90

Sample Output 4

NO


function main(arg) {
	arg = arg.split("\n").map(e => e.split(" ").map(x => Number(x)).sort((a,b) => a - b))
	// console.log(arg)

	var val_count = [0,0,0,0]

	var m = []
	for (var i = 0; i < arg.length; i++) {
		if (arg[i][0] === arg[i][1]) {
			console.log("NO")
			return;
		}

		val_count[arg[i][0] - 1]++
		val_count[arg[i][1] -1]++

		m.push(arg[i].join(""))
	}

	m.sort()

	for (var i = 1; i < m.length; i++ ) {
		if (m[i] === m[i-1]) {
			console.log("NO")
			return
		}
	}

	for (var i = 0; i < val_count.length; i++) {
		if (val_count[i] == 0 || val_count[i] > 2) {
			console.log("NO")
			return
		}
	}

	console.log("YES")

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

Score : 200 points

Problem Statement

There are four towns, numbered 1,2,3 and 4.
Also, there are three roads. The i-th road connects different towns a_i and b_i bidirectionally.
No two roads connect the same pair of towns. Other than these roads, there is no way to travel between these towns, but any town can be reached from any other town using these roads.

Determine if we can visit all the towns by traversing each of the roads exactly once.

Constraints

1 \leq a_i,b_i \leq 4(1\leq i\leq 3)

a_i and b_i are different. (1\leq i\leq 3)

No two roads connect the same pair of towns.

Any town can be reached from any other town using the roads.

Input

Input is given from Standard Input in the following format:

a_1 b_1
a_2 b_2
a_3 b_3

Output

If we can visit all the towns by traversing each of the roads exactly once, print YES; otherwise, print NO.

Sample Input 1

4 2
1 3
2 3

Sample Output 1

YES

We can visit all the towns in the order 1,3,2,4.

Sample Input 2

3 2
2 4
1 2

Sample Output 2

NO

Sample Input 3

2 1
3 2
4 3

Sample Output 3

YES


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"));

console.log(main());
function main(){
  var l = o.a();
  var a = o.r(l);
  var dp = [];
  for(var j = 0; j < 5; j++)dp[j] = f(a[0], j);
  for(var i = 1; i < l; i++){
    var d = Array(5).fill(9e99);
    d[0] = dp[0] + a[i];
    for(j = 1; j < 5; j++)for(var k = 0; k <= j; k++){
      var t = dp[k] + f(a[i], j);
      if(d[j] > t)d[j] = t;
    }
    dp = d;
  }
  return Math.min(...dp);

  function f(n,k){
    if(k === 0 || k === 4)return n;
    if(k === 2)return (n + 1) % 2;
    return n === 0 ? 2 : n % 2;
  }
}

Score : 600 points

Problem Statement

Snuke stands on a number line. He has L ears, and he will walk along the line continuously under the following conditions:

He never visits a point with coordinate less than 0, or a point with coordinate greater than L.

He starts walking at a point with integer coordinate, and also finishes walking at a point with integer coordinate.

He only changes direction at a point with integer coordinate.

Each time when Snuke passes a point with coordinate i-0.5, where i is an integer, he put a stone in his i-th ear.

After Snuke finishes walking, Ringo will repeat the following operations in some order so that, for each i, Snuke's i-th ear contains A_i stones:

Put a stone in one of Snuke's ears.

Remove a stone from one of Snuke's ears.

Find the minimum number of operations required when Ringo can freely decide how Snuke walks.

Constraints

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

0 \leq A_i \leq 10^9(1\leq i\leq L)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

L
A_1
:
A_L

Output

Print the minimum number of operations required when Ringo can freely decide how Snuke walks.

Sample Input 1

4
1
0
2
3

Sample Output 1

1

Assume that Snuke walks as follows:

He starts walking at coordinate 3 and finishes walking at coordinate 4, visiting coordinates 3,4,3,2,3,4 in this order.

Then, Snuke's four ears will contain 0,0,2,3 stones, respectively.
Ringo can satisfy the requirement by putting one stone in the first ear.

Sample Input 2

8
2
0
0
2
1
3
4
1

Sample Output 2

3

Sample Input 3

7
314159265
358979323
846264338
327950288
419716939
937510582
0

Sample Output 3

1


var stdin = require("fs").readFileSync("/dev/stdin", "utf8");
stdin = stdin.trim().split("\n").reverse();
function input(){return stdin.pop()}
var stdout = [];

var tmp = input().split(" ").map(n=>parseInt(n));
var t = tmp[0];
var x = tmp[1];
stdout.push(t / x);

stdout = stdout.join(" ");
console.log(stdout);

Score : 100 points

Problem Statement

In order to pass the entrance examination tomorrow, Taro has to study for T more hours.

Fortunately, he can leap to World B where time passes X times as fast as it does in our world (World A).

While (X \times t) hours pass in World B, t hours pass in World A.

How many hours will pass in World A while Taro studies for T hours in World B?

Constraints

All values in input are integers.

1 \leq T \leq 100

1 \leq X \leq 100

Input

Input is given from Standard Input in the following format:

T X

Output

Print the number of hours that will pass in World A.

The output will be regarded as correct when its absolute or relative error from the judge's output is at most 10^{-3}.

Sample Input 1

8 3

Sample Output 1

2.6666666667

While Taro studies for eight hours in World B where time passes three times as fast, 2.6666... hours will pass in World A.

Note that an absolute or relative error of at most 10^{-3} is allowed.

Sample Input 2

99 1

Sample Output 2

99.0000000000

Sample Input 3

1 100

Sample Output 3

0.0100000000


'use strict'

const main = input => {
	const args = input.split('\n')
	const n = parseInt(args[0], 10)
	const l = args[1].split(' ').map(Number).sort((a, b) => b - a)
	let max = 0
	let sum = 0

	for (let i = 0; i < n; i++) {
		if (i === 0) max = l[i]
		else sum += l[i]
	}

	if (max < sum) console.log('Yes')
	else console.log('No')
}

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

Score : 200 points

Problem Statement

Determine if an N-sided polygon (not necessarily convex) with sides of length L_1, L_2, ..., L_N can be drawn in a two-dimensional plane.

You can use the following theorem:

Theorem: an N-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths of the other N-1 sides.

Constraints

All values in input are integers.

3 \leq N \leq 10

1 \leq L_i \leq 100

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Output

If an N-sided polygon satisfying the condition can be drawn, print Yes; otherwise, print No.

Sample Input 1

4
3 8 5 1

Sample Output 1

Yes

Since 8 < 9 = 3 + 5 + 1, it follows from the theorem that such a polygon can be drawn on a plane.

Sample Input 2

4
3 8 4 1

Sample Output 2

No

Since 8 \geq 8 = 3 + 4 + 1, it follows from the theorem that such a polygon cannot be drawn on a plane.

Sample Input 3

10
1 8 10 5 8 12 34 100 11 3

Sample Output 3

No


var stdin = require("fs").readFileSync("/dev/stdin", "UTF-8");
var lines = stdin.split("\n");
var N = lines[0];
var L = lines[1].split(" ");

var sum = sum(L);
var max = Math.max(...L);

sum - max > max ? Yes() : No();

function sum(arr) {
  return arr.reduce(function(prev, current, i, arr) {
    return +prev + +current;
  });
}

function Yes() {
  console.log("Yes");
}

function No() {
  console.log("No");
}


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

  N = tmp0[0]
  L = input[1].split(" ")
  for(var i=0; i < N; i++){
    L[i] = Number(L[i])
  }

  L.sort((a,b) => b-a)

  max = L[0]
  L.shift()
  sum = L.reduce((p, c) => Number(p)+Number(c))

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


const input = require("fs").readFileSync("/dev/stdin", "utf8")
;(input => {
    const rows = input.split('\n')
    const N = rows[0].split(' ').map(Number)[0]
    const M = rows[0].split(' ').map(Number)[1]
    const X = rows[1].split(' ').map(Number)

    X.sort((a, b) => a - b)

    const dp = []
    for (var i = 0; i < M - 1; i++) {
        dp[i] = X[i + 1] - X[i]
    }

    dp.sort((a, b) => b - a)
    dp.splice(0, N - 1)

    console.log(dp.length ? dp.reduce((a, b) => a + b) : 0)

})(input)

Score : 300 points

Problem Statement

We will play a one-player game using a number line and N pieces.

First, we place each of these pieces at some integer coordinate.

Here, multiple pieces can be placed at the same coordinate.

Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:

Move: Choose a piece and let x be its coordinate. Put that piece at coordinate x+1 or x-1.

Note that the coordinates where we initially place the pieces are already regarded as visited.

Find the minimum number of moves required to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

-10^5 \leq X_i \leq 10^5

X_1, X_2, ..., X_M are all different.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_M

Output

Find the minimum number of moves required to achieve the objective.

Sample Input 1

2 5
10 12 1 2 14

Sample Output 1

5

The objective can be achieved in five moves as follows, and this is the minimum number of moves required.

Initially, put the two pieces at coordinates 1 and 10.

Move the piece at coordinate 1 to 2.

Move the piece at coordinate 10 to 11.

Move the piece at coordinate 11 to 12.

Move the piece at coordinate 12 to 13.

Move the piece at coordinate 13 to 14.

Sample Input 2

3 7
-10 -3 0 9 -100 2 17

Sample Output 2

19

Sample Input 3

100 1
-100000

Sample Output 3

0


"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf8");

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

reader.on("line", line => {
  lines.push(line.split(/\s/).map(i => parseInt(i)));
});

reader.on("close", () => {
  let firstLine = lines.shift();
  let n = firstLine[0], m = firstLine[1];
  if (m == 1) {
    console.log(0);
    return;
  }
  let x = lines.shift().sort((a, b) => a - b);
  let a = [];
  let indexArr = [];
  let ans = 0;
  for (let i = 0; i < m - 1; i++) {
    a.push(x[i + 1] - x[i]);
  }
  for (let i = 0; i < n - 1; i++) {
    let max = Math.max(...a);
    let index = a.indexOf(max);
    indexArr.push(index);
    a[index] = 0;
  }

  let pre = 0;
  for (let i = 0; i < n - 1; i++) {
    let start = 0;
    if (indexArr[0] == 0) {
      indexArr.shift();
      continue;
    }
    ans += a.splice(start, indexArr[0] - pre).reduce(((total, num) => total + num));
    pre = indexArr.shift();
  }

  console.log(ans + a.reduce((total, num) => total + num));

});


lines = [];
readline = require("readline");

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].split(" ")[0]);
  var a = Number(lines[0].split(" ")[1]);
  var b = Number(lines[0].split(" ")[2]);

  var max = (a < b)? a : b;
  var min = (n < (a+b))? a+b-n : 0;

  console.log(max,min);

})

Score : 100 points

Problem Statement

We conducted a survey on newspaper subscriptions.
More specifically, we asked each of the N respondents the following two questions:

Question 1: Are you subscribing to Newspaper X?

Question 2: Are you subscribing to Newspaper Y?

As the result, A respondents answered "yes" to Question 1, and B respondents answered "yes" to Question 2.

What are the maximum possible number and the minimum possible number of respondents subscribing to both newspapers X and Y?

Write a program to answer this question.

Constraints

1 \leq N \leq 100

0 \leq A \leq N

0 \leq B \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the maximum possible number and the minimum possible number of respondents subscribing to both newspapers, in this order, with a space in between.

Sample Input 1

10 3 5

Sample Output 1

3 0

In this sample, out of the 10 respondents, 3 answered they are subscribing to Newspaper X, and 5 answered they are subscribing to Newspaper Y.

Here, the number of respondents subscribing to both newspapers is at most 3 and at least 0.

Sample Input 2

10 7 5

Sample Output 2

5 2

In this sample, out of the 10 respondents, 7 answered they are subscribing to Newspaper X, and 5 answered they are subscribing to Newspaper Y.

Here, the number of respondents subscribing to both newspapers is at most 5 and at least 2.

Sample Input 3

100 100 100

Sample Output 3

100 100


// inputに入力データ全体が入る
function Main(input) {
    input = input.split("\n");
    N = parseInt(input[0]);
    answer = 0;
    moto_word = [];
    for(i = 0; i < N; i++){
        words = {};
        words_array = [];
        for(j = 1; j < input.length; j++){
            are = input[j].split("");
            i_word = are[i];
            if(words[i_word] === undefined) words[i_word] = 1;
            else words[i_word] = words[i_word] + 1;
            words_array.push(i_word);
        }
        kousi = {
            word: undefined,
            number: 0
        }
        for(k = 0; k < N; k++){
            if(words[words_array[k]] > kousi.number){
                kousi.word = words_array[k];
                kousi.number = words[words_array[k]];
            }
        }
        moto_word.push(kousi.word);
    }
    for(j = 1; j < input.length; j++){
        if(i === j) continue;
        hikaku_word = input[j].split("");
        for(k = 0; k < N; k++){
            if(moto_word[k] !== hikaku_word[k]) answer++
        }
    }
    console.log('%d',answer);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 200 points

Problem Statement

You are given three strings A, B and C. Each of these is a string of length N consisting of lowercase English letters.

Our objective is to make all these three strings equal. For that, you can repeatedly perform the following operation:

Operation: Choose one of the strings A, B and C, and specify an integer i between 1 and N (inclusive). Change the i-th character from the beginning of the chosen string to some other lowercase English letter.

What is the minimum number of operations required to achieve the objective?

Constraints

1 \leq N \leq 100

Each of the strings A, B and C is a string of length N.

Each character in each of the strings A, B and C is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
A
B
C

Output

Print the minimum number of operations required.

Sample Input 1

4
west
east
wait

Sample Output 1

3

In this sample, initially A = west、B = east、C = wait. We can achieve the objective in the minimum number of operations by performing three operations as follows:

Change the second character in A to a. A is now wast.

Change the first character in B to w. B is now wast.

Change the third character in C to s. C is now wast.

Sample Input 2

9
different
different
different

Sample Output 2

0

If A, B and C are already equal in the beginning, the number of operations required is 0.

Sample Input 3

7
zenkoku
touitsu
program

Sample Output 3

13


function main(input) {
  const args = input.split('\n');
  const N = parseInt(args[0], 10);
  const A = []
  const B = []
  for(var i=1;i <= N;i++){
    A[i-1] = parseInt(args[i].split(' ')[0], 10)
    B[i-1] = parseInt(args[i].split(' ')[1], 10)
  }
  var output = chang(A,B,N)

  console.log(output)
}

function change(a,b,n){
var o
  for(var j = 0;j<n;j++){
   var ch
    if(j%2==0){
     ch = add(a,b)
     o += a[ch]
    }else{
     ch = add(b,a)
     o -= b[ch]
    }
     a.splice(ch, 1)
     b.splice(ch, 1)
   }
  return o
}

function add (a,b){
  var chA = 0
  var maxA = Math.max.apply(null, a)
  for(var k = 0;k<=a.length;k++){
    if(maxA == a[k]&&chA != k && b[chA]<=b[k]){
      chA = k
    }
  }
  return chA
}

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

Score : 400 points

Problem Statement

There are N dishes of cuisine placed in front of Takahashi and Aoki.
For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N.

When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness.

Starting from Takahashi, they alternately choose one dish and eat it, until there is no more dish to eat.
Here, both of them choose dishes so that the following value is maximized: "the sum of the happiness he/she will earn in the end" minus "the sum of the happiness the other person will earn in the end".

Find the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Sample Input 1

3
10 10
20 20
30 30

Sample Output 1

20

In this sample, both of them earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since Takahashi and Aoki have the same "taste", each time they will choose the dish with which they can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (30 + 10) - 20 = 20.

Sample Input 2

3
20 10
20 20
20 30

Sample Output 2

20

In this sample, Takahashi earns 20 points of happiness by eating any one of the dishes 1, 2 and 3, but Aoki earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since only Aoki has likes and dislikes, each time they will choose the dish with which Aoki can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (20 + 20) - 20 = 20.

Sample Input 3

6
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 3

-2999999997

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


// parameter "input" gets all data
function Main(input) {
	// the first line is assigned to input[0], the second line is assigned to input[1] similarly.
	var splitInput = input.split("\n");
	var n = (splitInput[0])
	var plateArray = splitInput.slice(1).map(function(e){
		var splitab = e.split(" ")
		return [parseInt(splitab[0]),parseInt(splitab[1]),parseInt(splitab[0])+parseInt(splitab[1])]
	}).sort(function(x,y) {
		if (x[2] < y[2]) {
			return -1;
		}
		if (x[2] > y[2]) {
			return 1;
		}
		  return 0;
	})

	var aresult = 0
	var bresult = 0

	for (var i=0; i<n; i++){
		var j = 0
		var j0 = 0
		while (i+j < n && plateArray[i+j][2] == plateArray[i][2]){
			if (plateArray[i+j][i%2] > plateArray[i+j0][i%2]){
				j0 = j
			}
			j++
		}
		if (j0 != 0) {
			var tmp = plateArray[i].slice(0)
			plateArray[i] = plateArray[j0].slice(0)
			plateArray[j0] = tmp
		}
		if (i%2 == 0) {
			aresult += plateArray[i][0]
		} else {
			bresult += plateArray[i][1]
		}
	}

	//output
	console.log('%d',aresult-bresult);
}
// Don't edit this line!
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict"
function Main(stdin){
stdin = stdin.trim().split("\n").reverse();
let stdout = [];
function input(){return stdin.pop()};
function print(x){stdout.push(x)};
function mapint(x){return x.map(n=>parseInt(n))};
function mapfloat(x){return x.map(n=>parseFloat(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 }) }
function sorting(x, index){x.sort((a, b) => a[index] - b[index])}
function all(x){return x.reduce(function(a,b){ return a && b }) }
function any(x){return x.reduce(function(a,b){ return a || b }) }
function inlist(x, xs){return xs.includes(x)}
function inset(x, xs){return xs.has(x)}
function list(iterable){return Array.from(iterable)}
function arrayint(iterable){return Array.from(iterable, x => parseInt(x))}
function tile(val, len){return Array(len).fill(val)}
for (let i = 0; i < 10; i++){ break; }
const range = (start, stop, step) => Array.from(
    { length: (stop - start) / step }, (_, i) => start + (i * step));
/*START*/

let tmp = mapint(input().split(" "))
print(tmp[0] * tmp[1] / 2)

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

Score : 100 points

Problem Statement

There is a right triangle ABC with ∠ABC=90°.

Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC.

It is guaranteed that the area of the triangle ABC is an integer.

Constraints

1 \leq |AB|,|BC|,|CA| \leq 100

All values in input are integers.

The area of the triangle ABC is an integer.

Input

Input is given from Standard Input in the following format:

|AB| |BC| |CA|

Output

Print the area of the triangle ABC.

Sample Input 1

3 4 5

Sample Output 1

6

This triangle has an area of 6.

Sample Input 2

5 12 13

Sample Output 2

30

This triangle has an area of 30.

Sample Input 3

45 28 53

Sample Output 3

630

This triangle has an area of 630.


function main(input) {
  var a = input[0].split(" ")[0]-0;
  var b = input[0].split(" ")[1]-0;
  console.log(a*b/2);
}

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


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

const ary = [input];

var current = input;
while (true) {
  const next = (current % 2) ? current * 3 + 1 : current / 2;
  if (ary.findIndex((x) => x === next)) {
    console.log(ary.length + 1);
    break;
  }
  current = next;
  ary.push(next);
}

Score : 200 points

Problem Statement

A sequence a=\{a_1,a_2,a_3,......\} is determined as follows:

The first term s is given as input.

Let f(n) be the following function: f(n) = n/2 if n is even, and f(n) = 3n+1 if n is odd.

a_i = s when i = 1, and a_i = f(a_{i-1}) when i > 1.

Find the minimum integer m that satisfies the following condition:

There exists an integer n such that a_m = a_n (m > n).

Constraints

1 \leq s \leq 100

All values in input are integers.

It is guaranteed that all elements in a and the minimum m that satisfies the condition are at most 1000000.

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum integer m that satisfies the condition.

Sample Input 1

8

Sample Output 1

5

a=\{8,4,2,1,4,2,1,4,2,1,......\}. As a_5=a_2, the answer is 5.

Sample Input 2

7

Sample Output 2

18

a=\{7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1,4,2,1,......\}.

Sample Input 3

54

Sample Output 3

114


var num = +(require('fs').readFileSync('/dev/stdin', 'utf8').trim());
if (num == 1) {
  console.log(num);
  return;
}
var odds = (n) => { return n >> 1; };
var ends = (n) => { return 3 * n + 1; };
var r = [num];
while (num > 4) {
  num = (num % 2 == 0 ? odds(num) : ends(num));
  r.push(num);
}
console.log(r.length + 3);


"use strict";

function main(input) {
  const inputs = input.split("\n").filter(x => x !== "");

  let N = Number(inputs[0]);
  let h = inputs[1].split(" ").map(Number);

  console.log(mizuyari(h))

}

function mizuyari(h) {
  // console.log(h);
  let totalCount = 0;
  let count = Math.min(...h);
  totalCount += count;

  let afterH = h.map(x => x - count);

  let subH = [];
  for(let i=0; i<afterH.length; i++) {
    if (afterH[i] !== 0) {
      subH.push(afterH[i]);
    } else {
      if (subH.length > 0) {
        totalCount += mizuyari(subH);
        subH = [];
      }
    }
  }

  if (subH.length > 0) {
    totalCount += mizuyari(subH);
    subH = [];
  }

  // console.log(totalCount);
  return totalCount;
}

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

Score : 300 points

Problem Statement

In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0.
You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation:

Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

1 \leq N \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

Print the minimum number of watering operations required to satisfy the condition.

Sample Input 1

4
1 2 2 1

Sample Output 1

2

The minimum number of watering operations required is 2.
One way to achieve it is:

Perform the operation with (l,r)=(1,3).

Perform the operation with (l,r)=(2,4).

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221


function Main(input) {
	input = input.trim();
  if(input.indexOf("1") != -1 && input.indexOf("9") != -1 &&
     input.indexOf("7") != -1 && input.indexOf("4") != -1){
     	console.log("YES");
     }else{
     console.log("NO");
     }
}

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

Score : 100 points

Problem Statement

You are given four digits N_1, N_2, N_3 and N_4. Determine if these can be arranged into the sequence of digits "1974".

Constraints

0 \leq N_1, N_2, N_3, N_4 \leq 9

N_1, N_2, N_3 and N_4 are integers.

Input

Input is given from Standard Input in the following format:

N_1 N_2 N_3 N_4

Output

If N_1, N_2, N_3 and N_4 can be arranged into the sequence of digits "1974", print YES; if they cannot, print NO.

Sample Input 1

1 7 9 4

Sample Output 1

YES

We can get 1974 by swapping N_2 and N_3.

Sample Input 2

1 9 7 4

Sample Output 2

YES

We already have 1974 before doing anything.

Sample Input 3

1 2 9 1

Sample Output 3

NO

Sample Input 4

4 9 0 8

Sample Output 4

NO


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

console.log(main());
function main(){
  var s = o.a(1);
  var x = "keyence";
  var N = "NO";
  for(var i = 0; i <= x.length; i++){
    var t = x.slice(0,i);
    if(s.match("^"+x.slice(0,i)+".*"+x.slice(i+1)+"$"))return "YES";
  }
  return "NO";
}

Score : 200 points

Problem Statement

A string is called a KEYENCE string when it can be changed to keyence by removing its contiguous substring (possibly empty) only once.

Given a string S consisting of lowercase English letters, determine if S is a KEYENCE string.

Constraints

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

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a KEYENCE string, print YES; otherwise, print NO.

Sample Input 1

keyofscience

Sample Output 1

YES

keyence is an abbreviation of key of science.

Sample Input 2

mpyszsbznf

Sample Output 2

NO

Sample Input 3

ashlfyha

Sample Output 3

NO

Sample Input 4

keyence

Sample Output 4

YES


function Main(input) {
  input = input.split("\n");
  const N = parseInt(input[0],10);
  const changeInt = (n) => {
    return parseInt(n, 10);
  };
  const abc = [];
  for (var i = 0; i < N; i++) {
    abc.push(input[i + 1].split(' ').map(changeInt));
  }
  console.log(dp(N,abc));
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

function dp(N,abc) {
  const dp = Array(N).fill(0).map(n => {
    return Array(3).fill(0);
  });
  dp[0] = [...abc[0]];
  for (var i = 1; i < N; i++) {
    for (var j = 0; j < 3; j++) {
      for (var k = 0; k < 3; k++) {
          if (j === k) continue;
          dp[i][j] = Math.max(dp[i][j],abc[i][j] + dp[i - 1][k]);
      }
    }
  }
  return Math.max(...dp[N-1]);
}

Score : 100 points

Problem Statement

Taro's summer vacation starts tomorrow, and he has decided to make plans for it now.

The vacation consists of N days.
For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day:

A: Swim in the sea. Gain a_i points of happiness.

B: Catch bugs in the mountains. Gain b_i points of happiness.

C: Do homework at home. Gain c_i points of happiness.

As Taro gets bored easily, he cannot do the same activities for two or more consecutive days.

Find the maximum possible total points of happiness that Taro gains.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq a_i, b_i, c_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the maximum possible total points of happiness that Taro gains.

Sample Input 1

3
10 40 70
20 50 80
30 60 90

Sample Output 1

210

If Taro does activities in the order C, B, C, he will gain 70 + 50 + 90 = 210 points of happiness.

Sample Input 2

1
100 10 1

Sample Output 2

100

Sample Input 3

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

Sample Output 3

46

Taro should do activities in the order C, A, B, A, C, B, A.


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  var a = new Array(N);
  var b = new Array(N);
  var c = new Array(N);
  var maxs = new Array(3);
  for(var i=0;i<3;i++){
    var maxsub=new Array(N).fill(0);
    maxs[i]=maxsub;
  }
  for(var i=0;i<N;i++){
    var tmp = input[i+1].split(" ");
    a[i]=parseInt(tmp[0]);
    b[i]=parseInt(tmp[1]);
    c[i]=parseInt(tmp[2]);
    for(var j=0;j<3;j++){
      if(i==0){
        maxs[j][i]=parseInt(tmp[j]);
      }else{
        if(j==0){
          maxs[1][i]=Math.max(maxs[1][i],maxs[0][i-1]+b[i]);
          maxs[2][i]=Math.max(maxs[2][i],maxs[0][i-1]+c[i]);
        }else if(j==1){
          maxs[0][i]=Math.max(maxs[0][i],maxs[1][i-1]+a[i]);
          maxs[2][i]=Math.max(maxs[2][i],maxs[1][i-1]+c[i]);
        }else{
          maxs[0][i]=Math.max(maxs[0][i],maxs[2][i-1]+a[i]);
          maxs[1][i]=Math.max(maxs[1][i],maxs[2][i-1]+b[i]);
        }
      }
    }
  }
  var ans = Math.max(maxs[0][N-1],maxs[1][N-1],maxs[2][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"));


function main(input){
  const lines = input.split('\n');
  const NW = lines.shift().split(' ').map(x => parseInt(x));
  const N = NW[0]
  const W = NW[1]
  const items = lines.map(line => line.split(' ').map(x => parseInt(x)));

  const first = items.shift();
  const first_weight = first[0];
  const first_value = first[1];
  var value_sum = first_value;
  dp = [0]

  for(var i=1;i<=value_sum;i++){
    dp[i]=first_weight;
  }

  for(var i=0;i<items.length;i++){
    var current_weight = items[i][0];
    var current_value = items[i][1];
    value_sum += current_value;

  //console.log(dp);

    for(var value=value_sum;value>0;value--){

      if(value >= current_value){
        var prev_weight = dp[value - current_value];
        if(dp[value]==undefined){
          dp[value] = current_weight + prev_weight;
        }else{
          dp[value] = Math.min(prev_weight+current_weight, dp[value]);
        }
      }else{
        if(dp[value]==undefined){
          dp[value]=current_weight;
        }else{
          dp[value]=Math.min(current_weight, dp[value]);
        }
     }

    }
  }

  var result = 0;

  for(var i=value_sum;i>=0;i--){
    if(dp[i]<=W){
      result = i;
      break;
    }
  }

  //console.log(dp);

//  console.log(result==90);
  console.log(result+0);

}

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

Score : 100 points

Problem Statement

There are N items, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.

Taro has decided to choose some of the N items and carry them home in a knapsack.
The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.

Find the maximum possible sum of the values of items that Taro takes home.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq W \leq 10^9

1 \leq w_i \leq W

1 \leq v_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible sum of the values of items that Taro takes home.

Sample Input 1

3 8
3 30
4 50
5 60

Sample Output 1

90

Items 1 and 3 should be taken.
Then, the sum of the weights is 3 + 5 = 8, and the sum of the values is 30 + 60 = 90.

Sample Input 2

1 1000000000
1000000000 10

Sample Output 2

10

Sample Input 3

6 15
6 5
5 6
6 4
6 6
3 5
7 2

Sample Output 3

17

Items 2, 4 and 5 should be taken.
Then, the sum of the weights is 5 + 6 + 3 = 14, and the sum of the values is 6 + 6 + 5 = 17.


'use strict';
(function(input){
  input=input.trim().split(/\s+/).map(x=>x-0);
  const N=input.shift();
  const K=input.shift();
  const A=input;
  const dp=new Array(K+2).fill('tbd');

  dp[K+1]=true;
  for(let i=K+1;i>=0;i--){
    if(dp[i])
      if(dp[i-1]===true){
        continue;
      }
      for(let j=1;j<=A[0];j++)
        if(i-j>=0)
          if(dp[i-j]==='tbd')
            dp[i-j]=false;
    if(!dp[i])
      for(let a=0;a<N;a++)
        if(i-A[a]>=0)
          dp[i-A[a]]=true;
  }

  if(dp[0])console.log('First');
  else console.log('Second');
})(require('fs').readFileSync('/dev/stdin','utf8'));

Score : 100 points

Problem Statement

There is a set A = \{ a_1, a_2, \ldots, a_N \} consisting of N positive integers.
Taro and Jiro will play the following game against each other.

Initially, we have a pile consisting of K stones.
The two players perform the following operation alternately, starting from Taro:

Choose an element x in A, and remove exactly x stones from the pile.

A player loses when he becomes unable to play.
Assuming that both players play optimally, determine the winner.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq K \leq 10^5

1 \leq a_1 < a_2 < \cdots < a_N \leq K

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 \ldots a_N

Output

If Taro will win, print First; if Jiro will win, print Second.

Sample Input 1

2 4
2 3

Sample Output 1

First

If Taro removes three stones, Jiro cannot make a move.
Thus, Taro wins.

Sample Input 2

2 5
2 3

Sample Output 2

Second

Whatever Taro does in his operation, Jiro wins, as follows:

If Taro removes two stones, Jiro can remove three stones to make Taro unable to make a move.

If Taro removes three stones, Jiro can remove two stones to make Taro unable to make a move.

Sample Input 3

2 7
2 3

Sample Output 3

First

Taro should remove two stones. Then, whatever Jiro does in his operation, Taro wins, as follows:

If Jiro removes two stones, Taro can remove three stones to make Jiro unable to make a move.

If Jiro removes three stones, Taro can remove two stones to make Jiro unable to make a move.

Sample Input 4

3 20
1 2 3

Sample Output 4

Second

Sample Input 5

3 21
1 2 3

Sample Output 5

First

Sample Input 6

1 100000
1

Sample Output 6

Second


'use strict'

function solve(N, H, A) {
  var dp = new Array(N).fill(0).map((e, index) => A[index])
  var maxBeauty = 0
  for (var i = 0; i < N; i++) {
    var beauty = 0
    for (var j = 0; j < i; j++) {
      if (H[i] > H[j] && beauty < dp[j]) {
        beauty = dp[j]
      }
    }
    dp[i] += beauty
    if (dp[i] > maxBeauty) {
      maxBeauty = dp[i]
    }
  }
  return maxBeauty
}

function main(input) {
  var lines = input.split("\n")
  var N = parseInt(lines[0])
  var H = lines[1].split(' ').map(l => parseInt(l))
  var A = lines[2].split(' ').map(l => parseInt(l))
  var ans = solve(N, H, A)
  console.log(ans)
}

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

Score : 100 points

Problem Statement

There are N flowers arranged in a row.
For each i (1 \leq i \leq N), the height and the beauty of the i-th flower from the left is h_i and a_i, respectively.
Here, h_1, h_2, \ldots, h_N are all distinct.

Taro is pulling out some flowers so that the following condition is met:

The heights of the remaining flowers are monotonically increasing from left to right.

Find the maximum possible sum of the beauties of the remaining flowers.

Constraints

All values in input are integers.

1 \leq N \leq 2 × 10^5

1 \leq h_i \leq N

h_1, h_2, \ldots, h_N are all distinct.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N
a_1 a_2 \ldots a_N

Output

Print the maximum possible sum of the beauties of the remaining flowers.

Sample Input 1

4
3 1 4 2
10 20 30 40

Sample Output 1

60

We should keep the second and fourth flowers from the left.
Then, the heights would be 1, 2 from left to right, which is monotonically increasing, and the sum of the beauties would be 20 + 40 = 60.

Sample Input 2

1
1
10

Sample Output 2

10

The condition is met already at the beginning.

Sample Input 3

5
1 2 3 4 5
1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

5000000000

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

Sample Input 4

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

Sample Output 4

31

We should keep the second, third, sixth, eighth and ninth flowers from the left.


function Main(input) {
  // 入力
  var targetStr = '2';
  var count = (input.match(new RegExp(targetStr, 'g'))||[]).length;
	//出力
	console.log('%d', count);
}

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

Score : 100 points

Problem Statement

You are given an integer N that has exactly four digits in base ten.
How many times does 2 occur in the base-ten representation of N?

Constraints

1000 \leq N \leq 9999

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

1222

Sample Output 1

3

2 occurs three times in 1222. By the way, this contest is held on December 22 (JST).

Sample Input 2

3456

Sample Output 2

0

Sample Input 3

9592

Sample Output 3

1


function main(arg) {
	arg = arg.split("\n")[0]

	var src = arg.split("")
	var count = 0
	for (var i  = 0; i < src.length; i++) {
		if (src[i] == "2") {
			count++
		}
	}
	console.log(count)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const factorization = (n) => {
    let primes= []
    for(let i=2; i*i<=n; i++) {
        let exponent = 0
        while(n%i===0) {
            n /= i
            exponent++
        }
        if(exponent) {
            primes.push({p:i, e:exponent})
        }
    }

    if(n!==1) {
        primes.push({p:n, e:1})
    }
    return primes
}

const main = (arg) => {
    const [N,P] = arg.split(" ").map(Number)
    const f = factorization(P)

    let gcd = BigInt(1);
    for(let i=0; i<f.length; i++){
        let tmp = parseInt(f[i].e/N)
        gcd *= BigInt(f[i].p**tmp)
    }
    console.log(Number(gcd))

}

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

Score : 300 points

Problem Statement

There are N integers a_1, a_2, ..., a_N not less than 1.
The values of a_1, a_2, ..., a_N are not known, but it is known that a_1 \times a_2 \times ... \times a_N = P.

Find the maximum possible greatest common divisor of a_1, a_2, ..., a_N.

Constraints

1 \leq N \leq 10^{12}

1 \leq P \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N P

Output

Print the answer.

Sample Input 1

3 24

Sample Output 1

2

The greatest common divisor would be 2 when, for example, a_1=2, a_2=6 and a_3=2.

Sample Input 2

5 1

Sample Output 2

1

As a_i are positive integers, the only possible case is a_1 = a_2 = a_3 = a_4 = a_5 = 1.

Sample Input 3

1 111

Sample Output 3

111

Sample Input 4

4 972439611840

Sample Output 4

206


function Main(input) {
	input = input.split("\n").map(Number);
  input.shift();
  var n = arrsum(input);
  if(n==input.length){
  n = 1;
  }
  if(arrsum2(input)%2==1) n=1;

  if(n%2==1){
  console.log("first");
  }else{
  console.log("second");
  }
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
function arrsum(arr){
    var sum = 0;
    for (var i=0,len=arr.length; i<len; ++i) {
        sum += arr[i];
    };
    return sum;
}
function arrsum2(arr){
    var sum = 0;
    for (var i=0,len=arr.length; i<len; ++i) {
        if(arr[i]!=1)sum += arr[i];
    };
    return sum;
}


function main(arg) {
	var src = arg.split("\n")[0].split("")
	var register = []
	var sum_counter = 0

	for (;;) {
		var counter = 0
		for (var i = src.length - 1; i > 0; i--) {
			for (j = i; j > 0; j--) {
				if (src[j-1] === "B" && src[j] === "W") {
					src[j] = "B"
					src[j-1] = "W"
					counter++
				}
			}
		}
		sum_counter += counter
		if (counter === 0) {
			break
		}
	}
	// console.log(loop)
	console.log(sum_counter)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 300 points

Problem Statement

There are N Reversi pieces arranged in a row. (A Reversi piece is a disc with a black side and a white side.)
The state of each piece is represented by a string S of length N.
If S_i=B, the i-th piece from the left is showing black;
If S_i=W, the i-th piece from the left is showing white.

Consider performing the following operation:

Choose i (1 \leq i < N) such that the i-th piece from the left is showing black and the (i+1)-th piece from the left is showing white, then flip both of those pieces. That is, the i-th piece from the left is now showing white and the (i+1)-th piece from the left is now showing black.

Find the maximum possible number of times this operation can be performed.

Constraints

1 \leq |S| \leq 2\times 10^5

S_i=B or W

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum possible number of times the operation can be performed.

Sample Input 1

BBW

Sample Output 1

2

The operation can be performed twice, as follows:

Flip the second and third pieces from the left.

Flip the first and second pieces from the left.

Sample Input 2

BWBWBW

Sample Output 2

6


function main(arg) {
	var src = arg.split("\n")[0].split("")
	var register = []
	var sum_counter = 0

	for (;;) {
		var counter = 0
		for (var i = src.length - 1; i > 0; i--) {
			if (src[i-1] === "B" && src[i] === "W") {
				src[i] = "B"
				src[i-1] = "W"
				counter++
			}
		}
		sum_counter += counter
		if (counter === 0) {
			break
		}
	}
	// console.log(loop)
	console.log(sum_counter)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
	let flips = 0, finishes = 0;
	for (let i = 0; i < input.length; i++) {
		if (input[i] === 'B') continue;

		flips += i - finishes++;
	}

	console.log(flips);
}

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"));

console.log(main());
function main(){
  var n = o.a();
  var a = o.l();
  var l = 1, r = n;
  while(l < r){
    var m = l + r - 2 >> 1;
    var b = Array(a[0]);
    for(var i = 1; i < n; i++){
      b.length = a[i];
      if(a[i] > a[i-1])continue;
      if(m === 0)return 2;
      var f = 1;
      for(var j = b.length - 1; j >= 0; j--){
        if(b[j] === undefined)b[j] = 0;
        if(b[j] >= m)continue;
        b[j]++;
        for(var k = j+1; k < b.length; k++)b[k] = 0;
        f = 0;
        break;
      }
      if(f)break;
    }
    if(f)l = m + 2; else r = m + 1;
  }
  return l;
}

Score : 700 points

Problem Statement

There are N strings arranged in a row.
It is known that, for any two adjacent strings, the string to the left is lexicographically smaller than the string to the right.
That is, S_1<S_2<...<S_N holds lexicographically, where S_i is the i-th string from the left.

At least how many different characters are contained in S_1,S_2,...,S_N, if the length of S_i is known to be A_i?

Constraints

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

1 \leq A_i \leq 10^9

A_i is an integer.

Note

The strings do not necessarily consist of English alphabet; there can be arbitrarily many different characters (and the lexicographic order is defined for those characters).

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible number of different characters contained in the strings.

Sample Input 1

3
3 2 1

Sample Output 1

2

The number of different characters contained in S_1,S_2,...,S_N would be 3 when, for example, S_1=abc, S_2=bb and S_3=c.

However, if we choose the strings properly, the number of different characters can be 2.

Sample Input 2

5
2 3 2 1 2

Sample Output 2

2


// inputに入力データ全体が入る
function Main(input) {
	var N = input.split('\n')[0];
	var p = input.split('\n');
	p.shift();
	p = p.map(v => parseInt(v));
	var max = Math.max(...p);
	p.splice(p.indexOf(max), 1);
	var sum = 0;
	for (var i = 0; i < p.length; i++) {
		sum += p[i];
	}
	console.log(sum+(max/2));
}

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

Score : 200 points

Problem Statement

In some other world, today is the day before Christmas Eve.

Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan).

He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 items cost their regular prices. What is the total amount he will pay?

Constraints

2 \leq N \leq 10

100 \leq p_i \leq 10000

p_i is an even number.

Input

Input is given from Standard Input in the following format:

N
p_1
p_2
:
p_N

Output

Print the total amount Mr. Takaha will pay.

Sample Input 1

3
4980
7980
6980

Sample Output 1

15950

The 7980-yen item gets the discount and the total is 4980 + 7980 / 2 + 6980 = 15950 yen.

Note that outputs such as 15950.0 will be judged as Wrong Answer.

Sample Input 2

4
4320
4320
4320
4320

Sample Output 2

15120

Only one of the four items gets the discount and the total is 4320 / 2 + 4320 + 4320 + 4320 = 15120 yen.


s=require("fs").readFileSync("/dev/stdin","utf8").split('\n')
n=s[0].split(' ')[0]|0,k=s[0].split(' ')[1]|0
s.shift()
s=s.sort((a,b)=>b-a)
console.log(Math.min(...[...Array(n-k+1)].map((_,i)=>s[i]-s[i+k-1])))

Score : 300 points

Problem Statement

In some other world, today is Christmas Eve.

There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters.

He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees should be as close to each other as possible.

More specifically, let the height of the tallest decorated tree be h_{max} meters, and the height of the shortest decorated tree be h_{min} meters. The smaller the value h_{max} - h_{min} is, the better. What is the minimum possible value of h_{max} - h_{min}?

Constraints

2 \leq K < N \leq 10^5

1 \leq h_i \leq 10^9

h_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
h_1
h_2
:
h_N

Output

Print the minimum possible value of h_{max} - h_{min}.

Sample Input 1

5 3
10
15
11
14
12

Sample Output 1

2

If we decorate the first, third and fifth trees, h_{max} = 12, h_{min} = 10 so h_{max} - h_{min} = 2. This is optimal.

Sample Input 2

5 3
5
7
5
7
7

Sample Output 2

0

If we decorate the second, fourth and fifth trees, h_{max} = 7, h_{min} = 7 so h_{max} - h_{min} = 0. This is optimal.

There are not too many trees in these sample inputs, but note that there can be at most one hundred thousand trees (we just can't put a sample with a hundred thousand lines here).


'use strict'

const main = INPUT => {
  const input = INPUT.split('\n')
  const K = Number(input[0].split(' ')[1])
  input.shift()
  const h = input.map(n => Number(n)).sort((a, b) => a - b)

  let ans = Number.MAX_SAFE_INTEGER
  for (let i = 0; i <= h.length - K; i++) {
    let a = h[i + K - 1] - h[i]
    if (ans > a) {
      ans = a
    }
  }
  console.log(ans)
}

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


"use strict";

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

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

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

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

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

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

  var hs = lines.slice(0, N).map(function (l) {
    return parseInt(l);
  });
  hs.sort(function (a, b) {
    return a - b;
  });
  var gdiff = Infinity;

  for (var i = 0; i <= N - K; i++) {
    var min = Infinity,
        max = -Infinity;

    for (var j = i; j < i + K; j++) {
      if (min > hs[j]) {
        min = hs[j];
      }

      if (max < hs[j]) {
        max = hs[j];
      }
    }

    var diff = max - min;

    if (gdiff > diff) {
      gdiff = diff;
    }
  }

  console.log(gdiff);
}

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

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


function main(input){
    lines = input.split(" ");

    var N = lines[0];
    var X = lines[1];
    var l="131";

    if(N==0){
        l="1";
    }else if(N==1){
        l="131";
    }else{
        for(var i=0;i<N-1;i++){
            var r = l.charAt(0);
            l = l.slice(1);
            l = l.slice(0,-1);
            var t =1 + Number(r);
            var b = "" + t + l + r + 1 + r + l +t;
            l=b;
        }
    }

    var enco=0;
    var ans=0;
    var sub=0;
    for(var i=0;i<X;i++){
        enco+=Number(l.charAt(i));
        if(enco>X){
            break;
        }
        i++;
        sub=Number(l.charAt(i));
        enco += sub;
        ans += sub;
        if(enco>=X){
            var u = enco - X;
            ans-=u;
            break;
        }
    }

    console.log(ans);

}

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

Score : 400 points

Problem Statement

In some other world, today is Christmas.

Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing:

A level-0 burger is a patty.

A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) burger and another bun, stacked vertically in this order from the bottom.

For example, a level-1 burger and a level-2 burger look like BPPPB and BBPPPBPBPPPBB (rotated 90 degrees), where B and P stands for a bun and a patty.

The burger Mr. Takaha will make is a level-N burger. Lunlun the Dachshund will eat X layers from the bottom of this burger (a layer is a patty or a bun). How many patties will she eat?

Constraints

1 \leq N \leq 50

1 \leq X \leq ( the total number of layers in a level-N burger )

N and X are integers.

Input

Input is given from Standard Input in the following format:

N X

Output

Print the number of patties in the bottom-most X layers from the bottom of a level-N burger.

Sample Input 1

2 7

Sample Output 1

4

There are 4 patties in the bottom-most 7 layers of a level-2 burger (BBPPPBPBPPPBB).

Sample Input 2

1 1

Sample Output 2

0

The bottom-most layer of a level-1 burger is a bun.

Sample Input 3

50 4321098765432109

Sample Output 3

2160549382716056

A level-50 burger is rather thick, to the extent that the number of its layers does not fit into a 32-bit integer.


Score : 100 points

Problem Statement

Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.

Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?

Constraints

1 ≤ X ≤ 9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If Takahashi's growth will be celebrated, print YES; if it will not, print NO.

Sample Input 1

5

Sample Output 1

YES

The growth of a five-year-old child will be celebrated.

Sample Input 2

6

Sample Output 2

NO

See you next year.


var toInt = x=>parseInt(x,10);
var toIntArr = arr=>arr.map(x=>toInt(x));
var abs = x=>x>0?x:-x;
function min(){var rest = arguments,val=rest[0];for(var i=1;i<rest.length;i++)if(rest[i]<val)val = rest[i];return val}
function max(){var rest = arguments,val=rest[0];for(var i=1;i<rest.length;i++)if(rest[i]>val)val = rest[i];return val}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

function Main(input){
	var input = input.split('\n');
	var n = toInt(input[0]);
	var ans = 'No';
	if(n===3 || n === 5 || n === 7) ans = 'Yes';

	console.log(ans);
}


Score : 200 points

Problem Statement

There is a string S consisting of digits 1, 2, ..., 9.
Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)

The master's favorite number is 753. The closer to this number, the better.
What is the minimum possible (absolute) difference between X and 753?

Constraints

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

Each character in S is 1, 2, ..., or 9.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum possible difference between X and 753.

Sample Input 1

1234567876

Sample Output 1

34

Taking out the seventh to ninth characters results in X = 787, and the difference between this and 753 is 787 - 753 = 34. The difference cannot be made smaller, no matter where X is taken from.

Note that the digits cannot be rearranged. For example, taking out 567 and rearranging it to 765 is not allowed.

We cannot take out three digits that are not consecutive from S, either. For example, taking out the seventh digit 7, the ninth digit 7 and the tenth digit 6 to obtain 776 is not allowed.

Sample Input 2

35753

Sample Output 2

0

If 753 itself can be taken out, the answer is 0.

Sample Input 3

1111111111

Sample Output 3

642

No matter where X is taken from, X = 111, with the difference 753 - 111 = 642.


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(t){"use strict";var n=function(t){this.compose=t},a=new n(function(t){return function(n){return function(a){return t(n(a))}}});t.compose=function(t){return t.compose},t.Semigroupoid=n,t.semigroupoidFn=a}(t["Control.Semigroupoid"]=t["Control.Semigroupoid"]||{}),function(n){"use strict";var a=t["Control.Semigroupoid"],r=function(t,n){this.Semigroupoid0=t,this.identity=n},e=new r(function(){return a.semigroupoidFn},function(t){return t});n.Category=r,n.identity=function(t){return t.identity},n.categoryFn=e}(t["Control.Category"]=t["Control.Category"]||{}),function(n){"use strict";(t["Data.Boolean"]=t["Data.Boolean"]||{}).otherwise=!0}(),function(n){"use strict";(t["Data.Eq"]=t["Data.Eq"]||{}).refEq=function(t){return function(n){return t===n}}}(),function(n){"use strict";(t["Data.Unit"]=t["Data.Unit"]||{}).unit={}}(),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";var a=t["Data.Unit"];t["Data.Show"];n.unit=a.unit}(t["Data.Unit"]=t["Data.Unit"]||{}),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),o=new r(a.refEq);n.Eq=r,n.eq=function(t){return t.eq},n.eqInt=e,n.eqChar=o}(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.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=new e(function(){return a.eqChar},r.unsafeCompare);n.Ord=e,n.compare=function(t){return t.compare},n.ordInt=o,n.ordChar=i}(t["Data.Ord"]=t["Data.Ord"]||{}),function(n){"use strict";t["Control.Category"],t["Data.Boolean"],t["Data.Ord"],t["Data.Ring"];n.const=function(t){return function(n){return t}}}(t["Data.Function"]=t["Data.Function"]||{}),function(n){"use strict";t["Data.Functor"],t["Control.Semigroupoid"],t["Data.Function"],t["Data.Unit"];n.Functor=function(t){this.map=t},n.map=function(t){return t.map}}(t["Data.Functor"]=t["Data.Functor"]||{}),function(n){"use strict";t["Control.Apply"],t["Control.Category"],t["Data.Function"],t["Data.Functor"];n.Apply=function(t,n){this.Functor0=t,this.apply=n},n.apply=function(t){return t.apply}}(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(n){"use strict";t["Control.Bind"],t["Control.Applicative"],t["Control.Apply"],t["Control.Category"],t["Data.Function"],t["Data.Functor"],t["Data.Unit"];n.Bind=function(t,n){this.Apply0=t,this.bind=n},n.bind=function(t){return t.bind}}(t["Control.Bind"]=t["Control.Bind"]||{}),function(t){"use strict";t.topInt=2147483647,t.bottomInt=-2147483648,t.topChar=String.fromCharCode(65535),t.bottomChar=String.fromCharCode(0)}(t["Data.Bounded"]=t["Data.Bounded"]||{}),function(n){"use strict";var a=t["Data.Bounded"],r=t["Data.Ord"],e=(t["Data.Ordering"],t["Data.Unit"],function(t,n,a){this.Ord0=t,this.bottom=n,this.top=a}),o=new e(function(){return r.ordInt},a.bottomInt,a.topInt),i=new e(function(){return r.ordChar},a.bottomChar,a.topChar);n.Bounded=e,n.bottom=function(t){return t.bottom},n.top=function(t){return t.top},n.boundedInt=o,n.boundedChar=i}(t["Data.Bounded"]=t["Data.Bounded"]||{}),function(n){"use strict";t["Control.Alt"],t["Control.Alternative"],t["Control.Applicative"];var a=t["Control.Apply"],r=t["Control.Bind"],e=t["Control.Category"],o=(t["Control.Extend"],t["Control.Monad"],t["Control.MonadZero"],t["Control.Plus"],t["Data.Bounded"],t["Data.Eq"],t["Data.Function"]),i=t["Data.Functor"],u=(t["Data.Functor.Invariant"],t["Data.Monoid"],t["Data.Ord"],t["Data.Ordering"],t["Data.Semigroup"],t["Data.Show"],t["Data.Unit"],t.Prelude,function(){function t(){}return t.value=new t,t}()),c=function(){function t(t){this.value0=t}return t.create=function(n){return new t(n)},t}(),f=function(t){return function(n){return function(a){if(a instanceof u)return t;if(a instanceof c)return n(a.value0);throw new Error("Failed pattern match at Data.Maybe (line 217, column 1 - line 217, column 51): "+[t.constructor.name,n.constructor.name,a.constructor.name])}}},l=f(!0)(o.const(!1)),s=f(!1)(o.const(!0)),d=new i.Functor(function(t){return function(n){return n instanceof c?new c(t(n.value0)):u.value}}),D=new a.Apply(function(){return d},function(t){return function(n){if(t instanceof c)return i.map(d)(t.value0)(n);if(t instanceof u)return u.value;throw new Error("Failed pattern match at Data.Maybe (line 67, column 1 - line 67, column 35): "+[t.constructor.name,n.constructor.name])}}),m=new r.Bind(function(){return D},function(t){return function(n){if(t instanceof c)return n(t.value0);if(t instanceof u)return u.value;throw new Error("Failed pattern match at Data.Maybe (line 125, column 1 - line 125, column 33): "+[t.constructor.name,n.constructor.name])}});n.Nothing=u,n.Just=c,n.maybe=f,n.fromMaybe=function(t){return f(t)(e.identity(e.categoryFn))},n.isJust=s,n.isNothing=l,n.fromJust=function(t){return function(t){if(t instanceof c)return t.value0;throw new Error("Failed pattern match at Data.Maybe (line 268, column 1 - line 268, column 46): "+[t.constructor.name])}},n.functorMaybe=d,n.applyMaybe=D,n.bindMaybe=m}(t["Data.Maybe"]=t["Data.Maybe"]||{}),function(n){"use strict";t["Control.Alt"];var a=t["Control.Applicative"],r=t["Control.Apply"],e=t["Control.Bind"],o=(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"]),i=(t["Data.Functor.Invariant"],t["Data.FunctorWithIndex"],t["Data.Maybe"]),u=(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}()),c=function(){function t(t){this.value0=t}return t.create=function(n){return new t(n)},t}(),f=new o.Functor(function(t){return function(n){if(n instanceof u)return new u(n.value0);if(n instanceof c)return new c(t(n.value0));throw new Error("Failed pattern match at Data.Either (line 38, column 8 - line 38, column 52): "+[n.constructor.name])}}),l=function(t){return function(n){return function(a){if(a instanceof u)return t(a.value0);if(a instanceof c)return n(a.value0);throw new Error("Failed pattern match at Data.Either (line 238, column 1 - line 238, column 64): "+[t.constructor.name,n.constructor.name,a.constructor.name])}}},s=new r.Apply(function(){return f},function(t){return function(n){if(t instanceof u)return new u(t.value0);if(t instanceof c)return o.map(f)(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])}}),d=new e.Bind(function(){return s},l(function(t){return function(n){return new u(t)}})(function(t){return function(n){return n(t)}})),D=new a.Applicative(function(){return s},c.create);n.Left=u,n.Right=c,n.either=l,n.note=function(t){return i.maybe(new u(t))(c.create)},n.functorEither=f,n.applyEither=s,n.applicativeEither=D,n.bindEither=d}(t["Data.Either"]=t["Data.Either"]||{}),function(t){"use strict";t.fromNumberImpl=function(t){return function(n){return function(a){return(0|a)===a?t(a):n}}},t.toNumber=function(t){return t},t.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}}}}}(t["Data.Int"]=t["Data.Int"]||{}),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(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.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["Global"]=t["Global"]||{}).infinity=1/0}(),function(n){"use strict";var a=t.Global;n.infinity=a.infinity}(t.Global=t.Global||{}),function(t){"use strict";t.ceil=Math.ceil,t.log=Math.log,t.log10e=Math.LOG10E}(t.Math=t.Math||{}),function(n){"use strict";var a=t.Math;n.ceil=a.ceil,n.log=a.log,n.log10e=a.log10e}(t.Math=t.Math||{}),function(n){"use strict";var a=t["Data.Int"],r=(t["Control.Category"],t["Control.Semigroupoid"],t["Data.Boolean"]),e=t["Data.Bounded"],o=(t["Data.CommutativeRing"],t["Data.DivisionRing"],t["Data.Eq"],t["Data.EuclideanRing"],t["Data.HeytingAlgebra"],t["Data.Int.Bits"],t["Data.Maybe"]),i=(t["Data.Ord"],t["Data.Ordering"],t["Data.Ring"],t["Data.Semiring"],t["Data.Show"],t.Global),u=t.Math,c=(t.Prelude,a.fromStringAsImpl(o.Just.create)(o.Nothing.value)),f=c(10),l=a.fromNumberImpl(o.Just.create)(o.Nothing.value);n.fromNumber=l,n.ceil=function(t){return function(t){if(t===i.infinity)return 0;if(t===-i.infinity)return 0;if(t>=a.toNumber(e.top(e.boundedInt)))return e.top(e.boundedInt);if(t<=a.toNumber(e.bottom(e.boundedInt)))return e.bottom(e.boundedInt);if(r.otherwise)return o.fromMaybe(0)(l(t));throw new Error("Failed pattern match at Data.Int (line 66, column 1 - line 66, column 29): "+[t.constructor.name])}(u.ceil(t))},n.fromString=f,n.fromStringAs=c,n.toNumber=a.toNumber}(t["Data.Int"]=t["Data.Int"]||{}),function(t){"use strict";var n="function"==typeof Array.from,a="undefined"!=typeof Symbol&&null!=Symbol&&void 0!==Symbol.iterator&&"function"==typeof String.prototype[Symbol.iterator],r="function"==typeof String.prototype.fromCodePoint,e="function"==typeof String.prototype.codePointAt;t._unsafeCodePointAt0=function(t){return e?function(t){return t.codePointAt(0)}:t},t._singleton=function(t){return r?String.fromCodePoint:t},t._take=function(t){return function(n){return a?function(t){for(var a="",r=t[Symbol.iterator](),e=0;e<n;++e){var o=r.next();if(o.done)return a;a+=o.value}return a}:t(n)}},t._toCodePointArray=function(t){return function(a){return n?function(t){return Array.from(t,a)}:t}}}(t["Data.String.CodePoints"]=t["Data.String.CodePoints"]||{}),function(n){"use strict";(t["Data.Array"]=t["Data.Array"]||{}).length=function(t){return t.length}}(),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.fst=function(t){return t.value0},n.snd=function(t){return t.value1}}(t["Data.Tuple"]=t["Data.Tuple"]||{}),function(n){"use strict";(t["Data.Unfoldable"]=t["Data.Unfoldable"]||{}).unfoldrArrayImpl=function(t){return function(n){return function(a){return function(r){return function(e){return function(o){for(var i=[],u=o;;){var c=e(u);if(t(c))return i;var f=n(c);i.push(a(f)),u=r(f)}}}}}}}}(),function(n){"use strict";(t["Data.Unfoldable1"]=t["Data.Unfoldable1"]||{}).unfoldr1ArrayImpl=function(t){return function(n){return function(a){return function(r){return function(e){return function(o){for(var i=[],u=o;;){var c=e(u);i.push(a(c));var f=r(c);if(t(f))return i;u=n(f)}}}}}}}}(),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";var a=t["Data.Unfoldable1"],r=(t["Data.Boolean"],t["Data.Eq"],t["Data.Maybe"]),e=(t["Data.Ord"],t["Data.Ring"],t["Data.Semigroup.Traversable"],t["Data.Semiring"],t["Data.Tuple"]),o=(t["Partial.Unsafe"],t.Prelude,function(t){this.unfoldr1=t}),i=new o(a.unfoldr1ArrayImpl(r.isNothing)(r.fromJust())(e.fst)(e.snd));n.Unfoldable1=o,n.unfoldr1=function(t){return t.unfoldr1},n.unfoldable1Array=i}(t["Data.Unfoldable1"]=t["Data.Unfoldable1"]||{}),function(n){"use strict";var a=t["Data.Unfoldable"],r=(t["Data.Function"],t["Data.Functor"],t["Data.Maybe"]),e=(t["Data.Ord"],t["Data.Ring"],t["Data.Traversable"],t["Data.Tuple"]),o=t["Data.Unfoldable1"],i=(t["Data.Unit"],t["Partial.Unsafe"],t.Prelude,function(t,n){this.Unfoldable10=t,this.unfoldr=n}),u=new i(function(){return o.unfoldable1Array},a.unfoldrArrayImpl(r.isNothing)(r.fromJust())(e.fst)(e.snd));n.Unfoldable=i,n.unfoldr=function(t){return t.unfoldr},n.unfoldableArray=u}(t["Data.Unfoldable"]=t["Data.Unfoldable"]||{}),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"];t["Control.Alt"],t["Control.Alternative"],t["Control.Applicative"],t["Control.Apply"],t["Control.Bind"],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"],t["Data.Functor"],t["Data.HeytingAlgebra"],t["Data.Maybe"],t["Data.Ord"],t["Data.Ordering"],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"];n.length=a.length}(t["Data.Array"]=t["Data.Array"]||{}),function(t){"use strict";t.toCharCode=function(t){return t.charCodeAt(0)},t.fromCharCode=function(t){return String.fromCharCode(t)}}(t["Data.Enum"]=t["Data.Enum"]||{}),function(n){"use strict";var a=t["Data.Enum"],r=(t["Control.Apply"],t["Control.Bind"],t["Control.MonadPlus"],t["Control.MonadZero"],t["Control.Semigroupoid"],t["Data.Boolean"],t["Data.Bounded"]),e=(t["Data.Either"],t["Data.Eq"],t["Data.Function"],t["Data.Functor"],t["Data.HeytingAlgebra"],t["Data.Maybe"]),o=(t["Data.Newtype"],t["Data.Ord"]),i=(t["Data.Ordering"],t["Data.Ring"],t["Data.Semigroup"],t["Data.Semiring"],t["Data.Show"],t["Data.Tuple"],t["Data.Unfoldable"],t["Data.Unfoldable1"],t["Data.Unit"],t["Partial.Unsafe"],t.Prelude,function(t,n,a){this.Ord0=t,this.pred=n,this.succ=a}),u=function(t,n,a,r,e){this.Bounded0=t,this.Enum1=n,this.cardinality=a,this.fromEnum=r,this.toEnum=e},c=function(t){return t.toEnum},f=function(t){return t.fromEnum},l=function(t){return function(n){return function(a){return t(n(a)+1|0)}}},s=function(t){return function(n){return function(a){return t(n(a)-1|0)}}},d=function(t){return t>=r.bottom(r.boundedInt)&&t<=r.top(r.boundedInt)?new e.Just(a.fromCharCode(t)):e.Nothing.value},D=new i(function(){return o.ordChar},s(d)(a.toCharCode),l(d)(a.toCharCode)),m=new u(function(){return r.boundedChar},function(){return D},a.toCharCode(r.top(r.boundedChar))-a.toCharCode(r.bottom(r.boundedChar))|0,a.toCharCode,d);n.Enum=i,n.succ=function(t){return t.succ},n.pred=function(t){return t.pred},n.BoundedEnum=u,n.cardinality=function(t){return t.cardinality},n.toEnum=c,n.fromEnum=f,n.toEnumWithDefaults=function(t){return function(n){return function(a){return function(o){var i=c(t)(o);if(i instanceof e.Just)return i.value0;if(i instanceof e.Nothing)return o<f(t)(r.bottom(t.Bounded0()))?n:a;throw new Error("Failed pattern match at Data.Enum (line 158, column 33 - line 160, column 62): "+[i.constructor.name])}}}},n.defaultSucc=l,n.defaultPred=s,n.enumChar=D,n.boundedEnumChar=m}(t["Data.Enum"]=t["Data.Enum"]||{}),function(t){"use strict";t.singleton=function(t){return t},t.length=function(t){return t.length},t._indexOf=function(t){return function(n){return function(a){return function(r){var e=r.indexOf(a);return-1===e?n:t(e)}}}},t.take=function(t){return function(n){return n.substr(0,t)}},t.drop=function(t){return function(n){return n.substring(t)}}}(t["Data.String.CodeUnits"]=t["Data.String.CodeUnits"]||{}),function(n){"use strict";(t["Data.String.Unsafe"]=t["Data.String.Unsafe"]||{}).charAt=function(t){return function(n){if(t>=0&&t<n.length)return n.charAt(t);throw new Error("Data.String.Unsafe.charAt: Invalid index.")}}}(),function(n){"use strict";var a=t["Data.String.Unsafe"];n.charAt=a.charAt}(t["Data.String.Unsafe"]=t["Data.String.Unsafe"]||{}),function(n){"use strict";var a=t["Data.String.CodeUnits"],r=(t["Control.Semigroupoid"],t["Data.Boolean"],t["Data.Eq"],t["Data.Function"],t["Data.HeytingAlgebra"],t["Data.Maybe"]),e=(t["Data.Ord"],t["Data.Ring"],t["Data.Semiring"],t["Data.String.Pattern"],t["Data.String.Unsafe"],t.Prelude,a._indexOf(r.Just.create)(r.Nothing.value));n.indexOf=e,n.singleton=a.singleton,n.length=a.length,n.take=a.take,n.drop=a.drop}(t["Data.String.CodeUnits"]=t["Data.String.CodeUnits"]||{}),function(n){"use strict";(t["Data.String.Common"]=t["Data.String.Common"]||{}).trim=function(t){return t.trim()}}(),function(n){"use strict";var a=t["Data.String.Common"];t["Data.Eq"],t["Data.Ordering"],t["Data.String.Pattern"],t.Prelude;n.trim=a.trim}(t["Data.String.Common"]=t["Data.String.Common"]||{}),function(n){"use strict";var a=t["Data.String.CodePoints"],r=(t["Control.Semigroupoid"],t["Data.Array"]),e=(t["Data.Boolean"],t["Data.Bounded"]),o=t["Data.Enum"],i=(t["Data.Eq"],t["Data.EuclideanRing"]),u=t["Data.Functor"],c=(t["Data.HeytingAlgebra"],t["Data.Int"],t["Data.Maybe"]),f=(t["Data.Ord"],t["Data.Ring"],t["Data.Semigroup"],t["Data.Semiring"],t["Data.Show"],t["Data.String.CodeUnits"]),l=(t["Data.String.Common"],t["Data.String.Pattern"],t["Data.String.Unsafe"]),s=t["Data.Tuple"],d=t["Data.Unfoldable"],D=(t.Prelude,function(t){return function(n){return 65536+((1024*(t-55296|0)|0)+(n-56320|0)|0)|0}}),m=function(t){return 56320<=t&&t<=57343},g=function(t){return 55296<=t&&t<=56319},h=function(t){var n=f.length(t);if(0===n)return c.Nothing.value;if(1===n)return new c.Just({head:o.fromEnum(o.boundedEnumChar)(l.charAt(0)(t)),tail:""});var a=o.fromEnum(o.boundedEnumChar)(l.charAt(1)(t)),r=o.fromEnum(o.boundedEnumChar)(l.charAt(0)(t));return g(r)&&m(a)?new c.Just({head:D(r)(a),tail:f.drop(2)(t)}):new c.Just({head:r,tail:f.drop(1)(t)})},C=function(t){return u.map(c.functorMaybe)(function(t){return new s.Tuple(t.head,t.tail)})(h(t))},p=a._unsafeCodePointAt0(function(t){var n=o.fromEnum(o.boundedEnumChar)(l.charAt(0)(t));if(g(n)&&f.length(t)>1){var a=o.fromEnum(o.boundedEnumChar)(l.charAt(1)(t));return m(a)?D(n)(a):n}return n}),b=a._toCodePointArray(function(t){return d.unfoldr(d.unfoldableArray)(C)(t)})(p),v=function(t){return r.length(b(t))},S=function(t){return f.singleton(o.toEnumWithDefaults(o.boundedEnumChar)(e.bottom(e.boundedChar))(e.top(e.boundedChar))(t))},y=a._singleton(function(t){if(t<=65535)return S(t);var n=i.div(i.euclideanRingInt)(t-65536|0)(1024)+55296|0,a=i.mod(i.euclideanRingInt)(t-65536|0)(1024)+56320|0;return S(n)+S(a)}),w=function(t){return function(n){if(t<1)return"";var a=h(n);return a instanceof c.Just?y(a.value0.head)+w(t-1|0)(a.value0.tail):n}},E=a._take(w);n.singleton=y,n.toCodePointArray=b,n.uncons=h,n.length=v,n.indexOf=function(t){return function(n){return u.map(c.functorMaybe)(function(t){return v(f.take(t)(n))})(f.indexOf(t)(n))}},n.take=E,n.drop=function(t){return function(n){return f.drop(f.length(E(t)(n)))(n)}}}(t["Data.String.CodePoints"]=t["Data.String.CodePoints"]||{}),function(n){"use strict";var a=t["Control.Applicative"],r=t["Control.Bind"],e=t["Data.Either"],o=t["Data.Int"],i=t["Data.Maybe"],u=(t["Data.Ord"],t["Data.Ring"],t["Data.Semigroup"],t["Data.Semiring"],t["Data.Show"]),c=(t["Data.String"],t["Data.String.CodePoints"]),f=t["Data.String.Common"],l=(t["Data.String.Pattern"],t["Data.Unit"]),s=t.Math,d=t["Partial.Unsafe"],D=(t.Prelude,function(t){return function(n){return i.isJust(r.bind(i.bindMaybe)(c.indexOf("3")(n))(function(a){return r.bind(i.bindMaybe)(c.indexOf("5")(n))(function(a){return r.bind(i.bindMaybe)(c.indexOf("7")(n))(function(a){return r.bind(i.bindMaybe)(o.fromString(n))(function(n){return n<=t?new i.Just(l.unit):i.Nothing.value})})})}))}}),m=function(t){return function(n){return function(a){if(0===n)return D(t)(a)?1:0;var r=m(t)(n-1|0)(a+"7"),e=m(t)(n-1|0)(a+"5"),o=m(t)(n-1|0)(a+"3");return(((D(t)(a)?1:0)+o|0)+e|0)+r|0}}};n.solve=function(t){var n=function(t){return r.bind(e.bindEither)(e.note("n")(o.fromString(f.trim(t))))(function(t){var n=o.ceil(s.log(o.toNumber(t))*s.log10e);return a.pure(e.applicativeEither)(u.show(u.showInt)(m(t)(n)("")))})}(t);if(n instanceof e.Left)return d.unsafeCrashWith(n.value0);if(n instanceof e.Right)return n.value0;throw new Error("Failed pattern match at AtCoder.ABC114.C (line 17, column 3 - line 19, column 24): "+[n.constructor.name])}}(t["AtCoder.ABC114.C"]=t["AtCoder.ABC114.C"]||{}),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}(),f=function(){function t(){}return t.value=new t,t}(),l=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 f)return"Binary";if(t instanceof l)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=f,n.Hex=l,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.ABC114.C"],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)

Score : 300 points

Problem Statement

You are given an integer N. Among the integers between 1 and N (inclusive), how many Shichi-Go-San numbers (literally "Seven-Five-Three numbers") are there?

Here, a Shichi-Go-San number is a positive integer that satisfies the following condition:

When the number is written in base ten, each of the digits 7, 5 and 3 appears at least once, and the other digits never appear.

Constraints

1 \leq N < 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of the Shichi-Go-San numbers between 1 and N (inclusive).

Sample Input 1

575

Sample Output 1

4

There are four Shichi-Go-San numbers not greater than 575: 357, 375, 537 and 573.

Sample Input 2

3600

Sample Output 2

13

There are 13 Shichi-Go-San numbers not greater than 3600: the above four numbers, 735, 753, 3357, 3375, 3537, 3557, 3573, 3575 and 3577.

Sample Input 3

999999999

Sample Output 3

26484