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

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

// read lines from stdin
const input = require("fs")
  .readFileSync("/dev/stdin", "utf8")
  .split("\n");

const N = parseInt(input[0], 10);

const A = input[1].split(" ").map((val) => parseInt(val, 10)).sort((a, b) => b - a);

while (A[1] !== 0) {
  A[0] = A[0] % A[1];
  A.sort((a, b) => b - a);
}

console.log(A[0]);

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

Submitted source-code file size, in bytes.

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

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


function main(input){
    var tmp = input.split(/\n/).map(str=>{return parseInt(str)});
    console.log(tmp[0] >= (tmp[1] * 2 - 1) ? 'YES' : '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(input){
    var tmp = input.split(/\n/).map(str=>{return parseInt(str)});
    console.log(Math.ceil(tmp[0] / tmp[1]) >= 2 ? 'YES' : 'NO');
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
  var inputs = input.split(' '),
    len = inputs.length
  var N, K
  // if (len > 2 || len === 0) {
  //   console.log('NO')
  //   return
  // }
  // for (var i = 0; i < len; i++) {
  //   if (/^\d+$/.test(inputs[i]) !== -1) {
  //     console.log('NO')
  //     return
  //   }
  // }
  // try {
  N = parseInt(inputs[0], 10)
  K = parseInt(inputs[1], 10)
  // } catch (e) {
  //   console.log('NO')
  //   return
  // }

  if (N < 1 && N > 100) {
    console.log('NO')
    return
  }
  if (K < 1 && K > 100) {
    console.log('NO')
    return
  }

  if (N > K) {
    console.log('YES')
    return
  }
  console.log('NO')
  return
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'))


process.stdin.resume();
process.stdin.setEncoding('utf8');
var lines = [];
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
reader.on('line', (line) => {
  lines.push(line);
});
reader.on('close', () => {
 var road_1 = lines[0].split(' ');
 var road_2 = lines[1].split(' ');
 var road_3 = lines[2].split(' ');
var arr = new Array(6);
arr [0] = parseInt(road_1[0]);
arr [1] = parseInt(road_1[1]);
arr [2] = parseInt(road_2[0]);
arr [3] = parseInt(road_2[1]);
arr [4] = parseInt(road_3[0]);
arr [5] = parseInt(road_3[1]);
var cnt = new Array(4).fill(0);
// console.log(arr);
 for (var i = 0 ; i < 6 ; i++) {
var num = arr[i] - 1;
cnt[num] += 1 ;
}
// console.log(cnt);
if (cnt[0] > 2 || cnt[1] > 2 || cnt[2] > 2 || cnt[3] > 2) {
console.log("NO")
} else {
console.log("YES")
}

});

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 a = [0,0,0,0,0];
  a[o.a()]++;
  a[o.a()]++;
  a[o.a()]++;
  a[o.a()]++;
  a[o.a()]++;
  a[o.a()]++;
  return Math.max(...a) <= 2 ? "YES" : "NO";
}


//

const main = (standardInput) => {
    const numberList = standardInput.split(' ');
    const biggestNumber = Math.max.apply(null,numberList);
    const remaingNumber = numberList.filter(n => n !== biggestNumber);
    const sumNumber = remaingNumber.reduce(function(a, x){return a + x;});

    if (biggestNumber>sumNumber){
      console.log("Yes");
    }else{
      console.log("No");
    }

};

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

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


'use strict';

function main(input) {
  const lines = input.split('\n');
  const N = parseInt(lines[0]);
  const l = lines[1]
    .split(' ')
    .map(Number)
    .sort();

  const max = l.pop();
  const sum = l.reduce((prev, curr, i, arr) => prev + curr);
  console.log(max < sum ? 'Yes' : 'No');
}

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


function main(input) {
    const args = input.split('\n');

    var NM = args[0].split(' ');
    var Spins = args[1].split(' ');

    var N = parseInt(NM[0]);
    var M = parseInt(NM[1]);

    for (var i = 0; i < M; i++) {
        Spins[i] = parseInt(Spins[i]);
    }

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

    var diff = [M-1];

    for (var i = 0; i < M - 1; i++) {
        diff[i] = Math.abs(Spins[i] - Spins[i + 1]);
    }

    var ans = 0;

    if(M < N) {
        N = M;
    }

    var index = 0;
    var ans = 0;

    for (var i = 0; i < N - 1; i++) {
        index = diff.indexOf(Math.max.apply(null, diff));
        diff[index] = 0;
    }
    for (var i = 0; i < M - 1; i++) {
        ans += diff[i];
    }

    console.log(ans);
}

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

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


function Main(input) {
    const nums = input.split(/\s/).map(str => { return parseInt(str) });
    console.log(Math.min(nums[1], nums[2]) + ' ' + Math.max(nums[1] + nums[2] - nums[0], 0));
};
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));

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


function Main(input){
  input = input.split("\n");
  var a = input[1].split("");
  var b = input[2].split("");
  var c = input[3].split("");
  var sum = a.length*2;
  for(var i=0;i<a.length;i++){
    var x = 0;
    if(a[i]==b[i]) x++;
    if(c[i]==b[i]) x++;
    if(a[i]==c[i]) x++;
    if(x == 3) sum -= 2;
    else if(x == 1) sum--;
  }
  console.log(sum);
  }Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());

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


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 m = o.a();
  var a = [];
  var b = [];
  var c = Array(n+m-1).fill(9e9);
  for(var i = 0; i < n+m-1; i++){
    var t = o.l().map(a=>a-1);
    if(a[t[1]])a[t[1]].push(t[0]);
    else a[t[1]] = [t[0]];
    if(b[t[0]])b[t[0]].push(t[1]);
    else b[t[0]] = [t[1]];
  }
  var ans = [];
  for(i=0;;i++){
    if(!a[i]){
      var q = b[i];
      ans[i] = 0;
      c[i] = 0;
      break;
    }
  }
  var l = 1, d = 1;
  while(l < n){
    var x = [];
    for(i = 0; i < q.length; i++){
      var y = q[i], f = 1;
      for(var j = 0; j < a[y].length; j++){
        if(c[a[y][j]] >= d){f=0; break;}
        if(c[a[y][j]] === d-1)ans[y] = a[y][j] + 1;
      }
      if(f){c[y] = d; l++; if(b[y])x = x.concat(b[y]);}
    }
    q = x;
    d++;
  }
  return ans.join("\n");
}

Score : 500 points

Problem Statement

There is a rooted tree (see Notes) with N vertices numbered 1 to N.
Each of the vertices, except the root, has a directed edge coming from its parent.
Note that the root may not be Vertex 1.

Takahashi has added M new directed edges to this graph.
Each of these M edges, u \rightarrow v, extends from some vertex u to its descendant v.

You are given the directed graph with N vertices and N-1+M edges after Takahashi added edges.
More specifically, you are given N-1+M pairs of integers, (A_1, B_1), ..., (A_{N-1+M}, B_{N-1+M}), which represent that the i-th edge extends from Vertex A_i to Vertex B_i.

Restore the original rooted tree.

Notes

For "tree" and other related terms in graph theory, see the article in Wikipedia, for example.

Constraints

3 \leq N

1 \leq M

N + M \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

If i \neq j, (A_i, B_i) \neq (A_j, B_j).

The graph in input can be obtained by adding M edges satisfying the condition in the problem statement to a rooted tree with N vertices.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_{N-1+M} B_{N-1+M}

Output

Print N lines.
In the i-th line, print 0 if Vertex i is the root of the original tree, and otherwise print the integer representing the parent of Vertex i in the original tree.

Note that it can be shown that the original tree is uniquely determined.

Sample Input 1

3 1
1 2
1 3
2 3

Sample Output 1

0
1
2

The graph in this input is shown below:

It can be seen that this graph is obtained by adding the edge 1 \rightarrow 3 to the rooted tree 1 \rightarrow 2 \rightarrow 3.

Sample Input 2

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

Sample Output 2

6
4
2
0
6
2


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];
  myout(A * B / 2);
}

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) {
  input = input.trim()
  input = input.split(" ").map(Number);
  function compareFunc(a, b) {
  return a - b;
}
input.sort(compareFunc);
    console.log(input[2]*input[1])
}Main(require("fs").readFileSync("/dev/stdin", "utf8"));


// inputに入力データ全体が入る
function Main(input) {
    input = input.split(" ").map(num => Number(num)).sort((a,b) => a-b);
    console.log(input[0] * input[1]/2);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


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

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

reader.on("line", line => {
  let num = line.split(/\s/).map(i => parseInt(i));

  console.log(num[0] * num[1] / 2);
});


'use strict'

function Main(input) {
  const lines = input.split('\n').map(Number)
  const S = lines[0]

  const f = n => {
    if (n % 2 === 0) {
      return n / 2
    } else {
      return 3 * n + 1
    }
  }

  let arr = [S]
  for (let i = 1; ; i++) {
    const val = f(arr[i - 1])
    const exists = arr.some(v => v === val)
    if (exists) {
      console.log(i + 1)
      return
    }
    arr[i] = val
  }
}

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

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


function main(s) {
  var i = Number(s);
  var c = 0;
  const numList = [s];
  while (i > 0) {
    c += 1;
    if (i % 2 === 0) {
      i = i / 2;
    } else {
      i = n * 3 + 1;
    }
    if (numList.indexOf(i)) return;
    numList.push(i);
  }
  console.log(c);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function f(n) {
	if (n % 2 == 0) {
		return n / 2
	} else {
		return 3 * n + 1
	}
}

function main(arg) {
	var tmp = Number(arg.split("\n")[0])
	var arr = []

	for(i = 0; i < 1000; i++) {
		if (i === 0) {
			arr.push(tmp)
			continue
		}

		var ai = f(arr[i - 1]);

		if (arr.includes(ai)) {
			break
		}
		arr.push(ai)
 	}

	 console.log(arr.length + 1)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	tmp = input[0].split(" ");
	//文字列から10進数に変換するときはparseIntを使います
       console.log(tmp)
   tmp.sort(function(a,b){
    if( a < b ) return -1;
    if( a > b ) return 1;
    return 0;
	})

   result = tmp.toString() == [1,4,7,9] ? 'YES' :'NO';
   console.log(result)

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


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

var lines = [];

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

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

reader.on("close", () => {
  let n = lines.shift();
  let a = lines.shift();
  let b = lines.shift();

  let aSum = a.reduce((a, i) => a + i);
  let bSum = b.reduce((a, i) => a + i);

  if (aSum < bSum) {
    console.log(-1);
    return;
  }
  let count = 0;
  let positiveArr = [];
  let positiveSum = 0;
  let negativeSum = 0;
  let index = 0;

  for (let i = 0; i < n; i++) {
    let tmp = a[i] - b[i];
    if (tmp > 0) positiveArr.push(tmp);
    else {
      count += 1;
      negativeSum += tmp;
    }
  }

  positiveArr.sort((a, b) => b - a);
  while (positiveSum + negativeSum < 0) {
    positiveSum += positiveArr[index];
    index++;
  }

  console.log(count + index);
});

Score : 400 points

Problem Statement

A university student, Takahashi, has to take N examinations and pass all of them.
Currently, his readiness for the i-th examination is A_{i}, and according to his investigation, it is known that he needs readiness of at least B_{i} in order to pass the i-th examination.

Takahashi thinks that he may not be able to pass all the examinations, and he has decided to ask a magician, Aoki, to change the readiness for as few examinations as possible so that he can pass all of them, while not changing the total readiness.

For Takahashi, find the minimum possible number of indices i such that A_i and C_i are different, for a sequence C_1, C_2, ..., C_{N} that satisfies the following conditions:

The sum of the sequence A_1, A_2, ..., A_{N} and the sum of the sequence C_1, C_2, ..., C_{N} are equal.

For every i, B_i \leq C_i holds.

If such a sequence C_1, C_2, ..., C_{N} cannot be constructed, print -1.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

A_i and B_i are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N}
B_1 B_2 ... B_{N}

Output

Print the minimum possible number of indices i such that A_i and C_i are different, for a sequence C_1, C_2, ..., C_{N} that satisfies the conditions.
If such a sequence C_1, C_2, ..., C_{N} cannot be constructed, print -1.

Sample Input 1

3
2 3 5
3 4 1

Sample Output 1

3

(A_1, A_2, A_3) = (2, 3, 5) and (B_1, B_2, B_3) = (3, 4, 1). If nothing is done, he cannot pass the first and second exams.
The minimum possible number of indices i such that A_i and C_i are different, 3, is achieved when:

(C_1, C_2, C_3) = (3, 5, 2)

Sample Input 2

3
2 3 3
2 2 1

Sample Output 2

0

In this case, he has to do nothing in order to pass all the exams.

Sample Input 3

3
17 7 1
25 6 14

Sample Output 3

-1

In this case, no matter what is done, he cannot pass all the exams.

Sample Input 4

12
757232153 372327760 440075441 195848680 354974235 458054863 463477172 740174259 615762794 632963102 529866931 64991604
74164189 98239366 465611891 362739947 147060907 118867039 63189252 78303147 501410831 110823640 122948912 572905212

Sample Output 4

5


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

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.


'use strict'
function main(input) {
  const tmp = Array.from(input.split('\n'));
  const N = parseInt(tmp.shift(), 10);

  let a = [];
  let b = [];
  let c = [];
  for (let abc of tmp) {
    abc = abc.split(' ').map((elem) => parseInt(elem, 10));
    a.push(abc[0]);
    b.push(abc[1]);
    c.push(abc[2]);
  }

  let dp = new Array(N + 1);
  for (let i = 0; i <= N; i++) {
    dp[i] = new Array(3).fill(0);
  }
  const happiestValDay1 = [a[0], b[0], c[0]].reduce((max, elem) => Math.max(max, elem));

  dp[1][0] = happiestValDay1;
  dp[1][1] = happiestValDay1;
  dp[1][2] = happiestValDay1;
  for (let day = 2; day <= N; day++) {
    dp[day][0] = Math.max(dp[day][0], dp[day - 1][1] + b[day - 1]);
    dp[day][0] = Math.max(dp[day][0], dp[day - 1][2] + c[day - 1]);

    dp[day][1] = Math.max(dp[day][1], dp[day - 1][0] + a[day - 1]);
    dp[day][1] = Math.max(dp[day][1], dp[day - 1][2] + c[day - 1]);

    dp[day][2] = Math.max(dp[day][2], dp[day - 1][0] + a[day - 1]);
    dp[day][2] = Math.max(dp[day][2], dp[day - 1][1] + b[day - 1]);
  }
  const answer = [dp[N][0], dp[N][1], dp[N][2]].reduce((max, elem) => Math.max(max, elem));
  console.log(answer);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


'use strict'

function dfs(root, list, memo) {
  if (memo[root.toString()]) {
    return memo[root.toString()]
  }
  if (!list[root].length) {
    return 0
  }
  var max = 0
  for (var i = 0; i < list[root].length; i++) {
    max = Math.max(max, 1 + dfs(list[root][i], list, memo))
  }
  memo[root.toString()] = max
  return max
}

function adjList(N, edges) {
  var res = new Array(N+1).fill(0).map(e => new Array())
  var incoming = new Array(N+1).fill(0)
  for (var i = 0; i < edges.length; i++) {
    res[edges[i][0]].push(edges[i][1])
    incoming[edges[i][1]]++
  }
  return {
    list: res,
    incoming: incoming
  }
}

function solve(N, edges) {
  var adjListRes = adjList(N, edges)
  var list = adjListRes.list
  var incoming = adjListRes.incoming
  var max = 0
  for (var i = 1; i <= incoming.length; i++) {
    if (incoming[i] === 0) {
      var memo = {}
      max = Math.max(max, dfs(i, list, memo))
    }
  }
  return max
}

function main(input) {
  var lines = input.split("\n")
  var NM = lines[0].split(' ').map(i => parseInt(i))
  var N = NM[0]
  var edges = lines.slice(1).map(l => l.split(' ').map(e => parseInt(e)))
  var ans = solve(N, edges)
  console.log(ans)
}

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

Score : 100 points

Problem Statement

There is a directed graph G with N vertices and M edges.
The vertices are numbered 1, 2, \ldots, N, and for each i (1 \leq i \leq M), the i-th directed edge goes from Vertex x_i to y_i.
G does not contain directed cycles.

Find the length of the longest directed path in G.
Here, the length of a directed path is the number of edges in it.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq x_i, y_i \leq N

All pairs (x_i, y_i) are distinct.

G does not contain directed cycles.

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the length of the longest directed path in G.

Sample Input 1

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

Sample Output 1

3

The red directed path in the following figure is the longest:

Sample Input 2

6 3
2 3
4 5
5 6

Sample Output 2

2

The red directed path in the following figure is the longest:

Sample Input 3

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

Sample Output 3

3

The red directed path in the following figure is one of the longest:


function dfs(root, list, memo) {
  if (memo[root.toString()]) {
    return memo[root.toString()]
  }
  if (!list[root].length) {
    return 0
  }
  var max = 0
  for (var i = 0; i < list[root].length; i++) {
    max = Math.max(max, 1 + dfs(list[root][i], list, memo))
  }
  memo[root.toString()] = max
  return max
}

function adjList(N, edges) {
  var res = new Array(N+1).fill(0).map(e => [])
  var incoming = new Array(N+1).fill(0)
  for (var i = 0; i < edges.length; i++) {
    res[edges[i][0]].push(edges[i][1])
    incoming[edges[i][1]]++
  }
  return {
    list: res,
    incoming: incoming
  }
}

function solve(N, edges) {
  var adjListRes = adjList(N, edges)
  var list = adjListRes.list
  var incoming = adjListRes.incoming
  var max = 0
  for (var i = 1; i <= incoming.length; i++) {
    if (incoming[i] === 0) {
      var memo = {}
      max = Math.max(max, dfs(i, list, memo))
    }
  }
  return max
}

function main(input) {
  var lines = input.split("\n")
  var NM = lines[0].split(' ').map(i => parseInt(i))
  var N = NM[0]
  var edges = lines.slice(1).map(l => l.split(' ').map(e => parseInt(e)))
  var ans = solve(N, edges)
  return ans
}

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


'use strict';
(function(input){
  input=input.trim().split(/\n/).map(str=>str.split(/\s+/).map(x=>x-0));
  const N=input[0][0];
  const M=input[0][1];
  input.shift();

  const Node=function(idx){
    var t=this;
    t.index=idx;
    t.children=[];
    t.scanned=false;
    t.height=0;
  }

  const nodes=new Array(N+1).fill(0).map((x,i)=>new Node(i));
  //console.log(nodes);
  input.forEach(function(xy){
    var p=xy[0],c=xy[1];
    nodes[p].children.push(nodes[c]);
  });
  //console.log(nodes);
  var ans=0;
  var stack=[];
  var i=1;
  while(i<=N){
    //console.log('大');
    if(nodes[i].scanned){
      ans=Math.max(ans,nodes[i].height);
      i++;
      continue;
    }
    stack.push(i);
    while(stack.length>0){
      //console.log('中');
      let t=nodes[stack[stack.length-1]];
      //console.log(stack);
      if(t.children.length===0){
        t.scanned=true;
        stack.pop();
        continue;
      }
      let lastChild=t.children[t.children.length-1];
      if(lastChild.scanned){
        t.height=Math.max(t.height,lastChild.height+1);
        t.children.pop();
      }else{
        stack.push(lastChild.index);
      }
    }
    nodes[i].scanned=true;
  }
  //console.log(nodes);
  console.log(ans);
})(require('fs').readFileSync('/dev/stdin','utf8'));


'use strict';
(function(input){
  input=input.trim().split(/\n/).map(str=>str.split(/\s+/).map(x=>x-0));
  const N=input[0][0];
  const M=input[0][1];
  input.shift();

  const Node=function(idx){
    var t=this;
    t.index=idx;
    t.children=[];
    t.scanned=false;
    t.height=0;
  }

  const nodes=new Array(N+1).fill(0).map((x,i)=>new Node(i));
  //console.log(nodes);
  input.forEach(function(xy){
    var p=xy[0],c=xy[1];
    nodes[p].children.push(nodes[c]);
  });
  //console.log(nodes);
  var ans=0;
  var i=1;
  while(i<=N){
    if(nodes[i].scanned){
      ans=Math.max(ans,nodes[i].height);
      i++;
      continue;
    }
    let I=i;
    while(nodes[I].children.length>0){
      if(nodes[I].children[nodes[I].children.length-1].scanned){
        nodes[I].height=Math.max(nodes[I].height,nodes[I].children.pop().height+1);
      }else{
        I=nodes[I].children[nodes[I].children.length-1].index;
      }
    }
    nodes[I].scanned=true;
  }
  //console.log(nodes);
  console.log(ans);
})(require('fs').readFileSync('/dev/stdin','utf8'));


'use strict'

var mod = 1e9 + 7

function dfs(root, adj, visited) {
  var ans = [1, 1]
  for (var i = 0; i < adj[root].length; i++) {
    if (!visited[adj[root][i]]) {
      visited[adj[root][i]] = 1
      var res = dfs(adj[root][i], adj, visited)
      ans[0] = (ans[0] * (res[0] + res[1])) % mod
      ans[1] = (ans[1] * res[0]) % mod
    }
  }
  return ans
}

function adjList(N, E) {
  var list = new Array(N+1).fill(0).map(e => new Array(0).fill(0))
  for (var i = 0; i < E.length; i++) {
    var src = E[i][0]
    var dest = E[i][1]
    list[src].push(dest)
    list[dest].push(src)
  }
  return list
}

function solve(N, E) {
  var adj = adjList(N, E)
  var visited = new Array(N+1).fill(0)
  visited[1] = 1
  var res = dfs(1, adj, visited)
  return (res[0] + res[1]) % mod
}

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

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

Score : 100 points

Problem Statement

There is a tree with N vertices, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.

Taro has decided to paint each vertex in white or black.
Here, it is not allowed to paint two adjacent vertices both in black.

Find the number of ways in which the vertices can be painted, modulo 10^9 + 7.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq x_i, y_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}

Output

Print the number of ways in which the vertices can be painted, modulo 10^9 + 7.

Sample Input 1

3
1 2
2 3

Sample Output 1

5

There are five ways to paint the vertices, as follows:

Sample Input 2

4
1 2
1 3
1 4

Sample Output 2

9

There are nine ways to paint the vertices, as follows:

Sample Input 3

1

Sample Output 3

2

Sample Input 4

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

Sample Output 4

157


'use strict'

const main = input => {
	const args = input.split('\n')[0].split(' ')
	let a = parseInt(args[0], 10)
	let b = parseInt(args[1], 10)
	let c = parseInt(args[2], 10)
	let t1 = false
	let cnt = 0

	while (true) {
		if (t1) {
			if (b > 0) {
				b--
				t1 = false
				cnt++
			} else if (a > 0) {
				a--
				t1 = false
			} else {
				break
			}
		} else {
			if (c > 0) {
				c--
				t1 = true
				cnt++
			} else if (b > 0) {
				b--
				cnt++
			} else {
				break
			}
		}
	}

	console.log(cnt)
}

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

Score : 200 points

Problem Statement

Takahashi has A untasty cookies containing antidotes, B tasty cookies containing antidotes and C tasty cookies containing poison.

Eating a cookie containing poison results in a stomachache, and eating a cookie containing poison while having a stomachache results in a death.
As he wants to live, he cannot eat one in such a situation.
Eating a cookie containing antidotes while having a stomachache cures it, and there is no other way to cure stomachaches.

Find the maximum number of tasty cookies that Takahashi can eat.

Constraints

0 \leq A,B,C \leq 10^9

A,B and C are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the maximum number of tasty cookies that Takahashi can eat.

Sample Input 1

3 1 4

Sample Output 1

5

We can eat all tasty cookies, in the following order:

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

A tasty cookie containing antidotes

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

Sample Input 2

5 2 9

Sample Output 2

10

Sample Input 3

8 8 1

Sample Output 3

9


"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[0]),
      _splitNum2 = _slicedToArray(_splitNum, 1),
      N = _splitNum2[0];

  var as = splitNum(input).slice(1, N + 1);
  as.sort(function (a, b) {
    return a - b;
  });
  var res = as[N - 1] % 2 === 1;

  for (var idx = N - 2; idx >= 0; idx--) {
    if ((as[idx] - 1) % 2 === 0) {
      res = !res;
    }
  }

  console.log(res ? 'first' : 'second');
} // true: first, false: second

function solve(N, as, idx) {
  if (N === 1) {
    return as[idx] % 2 === 1;
  }

  var rem = solve(N - 1, as, idx + 1);
  var cur = as[idx];
  return (cur - 1) % 2 === 1 ? rem : !rem;
}

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

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

Score : 500 points

Problem Statement

There is an apple tree that bears apples of N colors. The N colors of these apples are numbered 1 to N, and there are a_i apples of Color i.

You and Lunlun the dachshund alternately perform the following operation (starting from you):

Choose one or more apples from the tree and eat them. Here, the apples chosen at the same time must all have different colors.

The one who eats the last apple from the tree will be declared winner. If both you and Lunlun play optimally, which will win?

Constraints

1 \leq N \leq 10^5

1 \leq a_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

If you will win, print first; if Lunlun will win, print second.

Sample Input 1

2
1
2

Sample Output 1

first

Let Color 1 be red, and Color 2 be blue. In this case, the tree bears one red apple and two blue apples.

You should eat the red apple in your first turn. Lunlun is then forced to eat one of the blue apples, and you can win by eating the other in your next turn.

Note that you are also allowed to eat two apples in your first turn, one red and one blue (not a winning move, though).

Sample Input 2

3
100000
30000
20000

Sample Output 2

second


function Main(input) {
  input = input.split("\n");
  S= input[0].split(" ");
  var n=0
  var w=0
  for(i=0;i<S.length;i++){
    if(S[i]=="W"){
      w++;
      n+=i;
    }
  }
  var ans=n-n*w/2;
  console.log('%s', ans);
}

// "実行する"ボタンを押した時に実行される関数 (デバッグ用)
function debug(){
  var input = document.getElementById("input").value;
  Main(input);
}
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


"use strict";

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

		flips += i - finishes;
		finishes += 1;
	}

	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 b = {};
  var pow2 = [2];
  a.sort((a,b)=>b-a);
  for(var i = 1; pow2[i-1] <= a[0]; i++)pow2[i] = pow2[i-1] * 2;
  var u = i-1;
  for(i = 0; i < n; i++){
    if(b[a[i]])b[a[i]]++;
    else b[a[i]] = 1;
  }
  ans = 0;
  for(i = 0; i < n; i++){
    b[a[i]]--;
    if(b[a[i]] < 0)continue;
    while(u > 0 && pow2[u-1] > a[i]){
      u--;
    }
    var t = pow2[u] - a[i];
    if(b[t] > 0){b[t]--; ans++;}
  }
  return ans;
}

Score : 600 points

Problem Statement

Takahashi has N balls with positive integers written on them. The integer written on the i-th ball is A_i.
He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of 2.
Note that a ball cannot belong to multiple pairs.
Find the maximum possible number of pairs that can be formed.

Here, a positive integer is said to be a power of 2 when it can be written as 2^t using some non-negative integer t.

Constraints

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

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible number of pairs such that the sum of the integers written on each pair of balls is a power of 2.

Sample Input 1

3
1 2 3

Sample Output 1

1

We can form one pair whose sum of the written numbers is 4 by pairing the first and third balls.
Note that we cannot pair the second ball with itself.

Sample Input 2

5
3 11 14 5 13

Sample Output 2

2


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  A = new Array(N);
  tmp=input[1].split(" ");
  for(i=0;i<N;i++){
    A[i]=parseInt(tmp[i]);
  }
  var ans = 1;
  var flag=0;
  var ans=0;
  var c=0;
  B = new Array(A[0]).fill(1);
  for(i=1;i<N;i++){
    B = B.slice(0,A[i]);
    //if(flag==2){
      for(j=0;j<B.length;j++){
        c=Math.max(c,B[j]);
        if(B[j]!=B[0]){
          flag=1;
          break;
        }else{
          flag=0;
        }
      }
    //}
    if(A[i]>A[i-1]){
      for(j=0;j<A[i]-A[i-1];j++){
        B.push(1);
      }

    }else if(flag==0){
      B[A[i]-1]=B[A[i]-1]+1;
    }else if(flag==1){
      for(j=A[i]-1;j>=0;j--){
        if(B[j]==c){
          B[j]=1;
        }else if(B[j]!=c){
          B[j]=B[j]+1;
          flag=2;
          break;
        }
      }
    }
  }
  for(i=0;i<B.length;i++){
    ans=Math.max(ans,B[i]);
  }
  console.log('%s', ans);
}

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

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


function main(input) {
   input = input.split('\n').map((n) => parseInt(n, 10));
   const COUNT = input[0];
   input.shift();
   const MAX = Math.max.apply(null, input);
   const maxIndex = input.indexOf(MAX);
   input[maxIndex] = ( input[maxIndex] / 2 );

   sum = input.reduce((a,x) => a+=x,0);
   console.log(sum);
}

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.


function convertBasedRepr(x, n) {
	var result = []

	do {
		var t = x % n
		result.push(t)
		var m = Math.floor(x / n)

		if (m < n) {
			if (m !== 0) {
				result.push(m)
			}
			break
		}
		x = (x - t) /n
	} while(1)

	return result
}

function main(arg) {
	arg = arg.trim().split("\n")
	var h = arg;
	var NK = arg.shift()
	NK = NK.split(" ")
	var N = NK[0]
	var K = Number(NK[1])

	var result_diff = -1

	for (var i = 0; i < 1000; i++) {
		//添字作り
		// var i_list = i.toString(h.length + 1)
		var i_list = convertBasedRepr(i, h.length)

        if (i_list.length > K) {
			break;
		}

		// if (i_list.indexOf(0) !== -1) {
		// 	continue;
		// }
// console.log(i_list.length)
		if (i_list.length !== K) {
			continue;
		}

		var tmp = i_list.filter(function (x, n, self) {
            return self.indexOf(x) === n && n !== self.lastIndexOf(x);
        });

		if (tmp.length > 0) {
			continue;
		}

		if (i_list !== i_list.sort()) {
			continue;
		}

		// i_list = i_list.map(e => Number(e))
// console.log(i_list);
		var i_list_max = 0;
		var i_list_min = 0;

		for (var j = 0; j < i_list.length; j++) {
			var value = h[i_list[j]]
			if (j === 0) {
				i_list_max = i_list_min = value;
				continue;
			}
			if (value > i_list_max) {
				i_list_max = value;
			}
			if (value < i_list_min) {
				i_list_min = value;
			}
		}

		var tmp_diff = Number(i_list_max) - Number(i_list_min)

		if (result_diff === -1) {
			result_diff = tmp_diff
			continue
		}

		if (result_diff > tmp_diff) {
			result_diff = tmp_diff
		}
		// console.log(i_list.length)
		// console.log([Number(i_list_max) , Number(i_list_min)])
	}
	console.log(result_diff)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

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).


function main(arg) {
	arg = arg.trim().split("\n")
	var h = arg;
	var NK = arg.shift()
	NK = NK.split(" ")
	var N = NK[0]
	var K = Number(NK[1])

	var result_diff = -1

	for (var i = 0; i < 2000000; i++) {
		//添字作り
		var i_list = i.toString(h.length + 1)

        if (i_list.length > K) {
			break;
		}

		if (i_list.indexOf('0') !== -1) {
			continue;
		}

		if (i_list.length < K) {
			continue;
		}

		var tmp = i_list.split("").filter(function (x, n, self) {
            return self.indexOf(x) === n && n !== self.lastIndexOf(x);
        });

		if (tmp.length > 0) {
			continue;
		}

		if (i_list !== i_list.split("").sort().join("")) {
			continue;
		}

		i_list = i_list.split("").map(e => Number(e))

		var i_list_max = 0;
		var i_list_min = 0;

		for (var j = 0; j < i_list.length; j++) {
			var value = h[i_list[j] - 1]
			if (j === 0) {
				i_list_max = i_list_min = value;
				continue;
			}
			if (value > i_list_max) {
				i_list_max = value;
			}
			if (value < i_list_min) {
				i_list_min = value;
			}
		}

		var tmp_diff = Number(i_list_max) - Number(i_list_min)

		if (result_diff === -1) {
			result_diff = tmp_diff
			continue
		}

		if (result_diff > tmp_diff) {
			result_diff = tmp_diff
		}
		// console.log(i_list.length)
		// console.log([Number(i_list_max) , Number(i_list_min)])
	}
	console.log(result_diff)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0].split(" ")[0]);
  var X = parseInt(input[0].split(" ")[1]);
  bans=new Array(50);
  all=new Array(50);
  bans[0]=1;
  all[0]=1;
  var ans = 0;
  for(i=1;i<=50;i++){
    bans[i]=bans[i-1]*2+1;
    all[i]=all[i-1]*2+3;
  }
  var full=all[N];
  var bs=bans[N];
  var flag=0;
  if(X%2==0){
    X=all[N]-X;
    flag=1;
  }
  while(X>0&&full>0){

    if(X>(full-1)/2){
      X=X-(full-1)/2-1;
      ans=ans+(bs-1)/2+1;
      full=(full-1)/2-1;
      bs=(bs-1)/2
    }else{
      X=X-1;
      full=(full-1)/2-1;
      bs=(bs-1)/2
    }
  }
  if(flag==1){
    ans=bans[N]-ans;
  }
  console.log('%s', ans);
}

// "実行する"ボタンを押した時に実行される関数 (デバッグ用)
function debug(){
  var input = document.getElementById("input").value;
  Main(input);
}
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.


function main(input){
    input=input.split(' ');
    x=parseInt(input[0],10)
    if (x==3 ||x==5 || x==7){
        console.log("YES")
    }else{
        console.log("NO")
    }

}

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

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.


"use strict";
const input = Number(require("fs").readFileSync("/dev/stdin","UTF-8").trim());

if (input === 3 || input === 5 || input === 7) console.log("YES");
else console.log("NO");


function Main(input) {
  if(input == 7 || input == 5 || input == 3) {
    console.log("YES");
  } else {
    console.log("NO");
  }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


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

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

reader.on('line', (line) => {
  lines.push(line);
});

reader.on('close', () => {
  var N = lines[0];
  var diff = [];
  for(let i=0; i<N.length-2; i++){
    var pick_num = N.slice(i, i+3);
    var sabun = Math.abs(753-pick_num);
    diff.push(sabun);
  }
  console.log(Math.min(...diff));
});

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.


function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim();}
function myout(t){console.log(t);}//standard output
function myerr(t){console.log(t);}//standard error
//[no]param
//0:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
function myconv(i,no){switch(no){case 0:return i;case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));}}

function Main(input) {
  input = myconv(input,1);
  var primeCountList = {
  	"1" : 1
  };
  for(var i = 1; i <= input; i++){
    var tmpI = i;
    var div = 2;
    while(tmpI != 1){
       if(tmpI % div == 0){
         if(primeCountList[div] == null){
           primeCountList[div] = 1;
         }else{
           primeCountList[div]++;
         }
         tmpI /= div;
       }else{
         div = (div == 2) ? div+1 : div+2;
       }
    }
  }
  //myout(primeCountList);
  var primeList = Object.keys(primeCountList);

  var result442 = 0;//P1^4,P2^4,P3^2
  var result242 = 0;//P1^24,P3^2
  var result144 = 0;//P1^14,P2^4,
  var result74 = 0;//P1^74
  var result2 = 0;
  var result4 = 0;
  var result14 = 0;
  var result24 = 0;
  var result74 = 0;
  for(var i = 0; i < primeList.length; i++){
    if(primeCountList[primeList[i]] >= 2){
       result2++;
    }
    if(primeCountList[primeList[i]] >= 4){
       result4++;
    }
    if(primeCountList[primeList[i]] >= 14){
       result14++;
    }
    if(primeCountList[primeList[i]] >= 24){
       result24++;
    }
    if(primeCountList[primeList[i]] >= 74){
       result74++;
    }
  }
  result442 = (result4 * (result4 -1)) / 2 * (result2 -2);
  result242 = result24 * (result2 -1);
  result144 = result14 * (result4 -1);

  myout(result442 + result242 + result144 + result74);

}

function getPrimeFactorization(val){
	var primeList = {
		"1" : 1
	};
	var div = 2;
	while(val != 1){
		if(val % div == 0){
			if(primeList[div] == null){
				primeList[div] = 1;
			}else{
				primeList[div]++;
			}
			val /= div;
		}else{
			div = (div == 2) ? div+1 : div+2;
		}
    }
  return primeList;
}

for(var i = 1; i <= 10; i++){
  //Main(i);
}

Main(myin());

Score : 400 points

Problem Statement

You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there?

Here, a Shichi-Go number is a positive integer that has exactly 75 divisors.

Note

When a positive integer A divides a positive integer B, A is said to a divisor of B.
For example, 6 has four divisors: 1, 2, 3 and 6.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of the Shichi-Go numbers that are divisors of N!.

Sample Input 1

9

Sample Output 1

0

There are no Shichi-Go numbers among the divisors of 9! = 1 \times 2 \times ... \times 9 = 362880.

Sample Input 2

10

Sample Output 2

1

There is one Shichi-Go number among the divisors of 10! = 3628800: 32400.

Sample Input 3

100

Sample Output 3

543


"use strict";
function main(input) {
  const inputs = input.split("\n").filter(x => x !== "");
  let N = Number(inputs[0]);

  function resolve(n) {
    let result = Array(n + 1).fill(0);
    for (let i = 2; i <= n; i++) {
      let cur = i;
      for (let j = 2; j <= i; j++) {
        while (cur % j === 0) {
          result[j] += 1;
          cur = cur / j;
        }
      }
    }
    return result;
  }

  function findLargerThan(num, array) {
    return array.filter(element => element >= num).length;
  }

  function combination(numA, numB) {
    let result = 1;
    for (let i = numA; i > numA - numB; i = i - 1) {
      result = result * i;
    }

    for (let i = numB; i > 0; i = i - 1) {
      result = result / i;
    }
    return result;
  }

  let result = resolve(N);

  let l74 = findLargerThan(74, result);
  let l24 = findLargerThan(24, result);
  let l14 = findLargerThan(14, result);
  let l4 = findLargerThan(4, result);
  let l2 = findLargerThan(2, result);

  let r5x5x3 = (l4 * (l4 - 1) * (l2 - 2)) / 2;
  let r15x5 = l14 * (l4 - 1);
  let r25x3 = l24 * (l2 - 1);
  let r75 = l74;

  console.log(
    l74 + l24 * (l2 - 1) + l14 * (l4 - 1) + (l4 * (l4 - 1) * (l2 - 2)) / 2
  );
}

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


function main(input){
    var lines = input.replace('\n',' ');
    lines = lines.split(" ");
    var N = Number(lines[0]);
    var K = Number(lines[1]);
    lines.splice(0,2);

    var utu=[K];

    var max=0;
    var mem=0;
    var w=0;
    for (var i=0;i<N ;i++ ) {
    	var k=i+1;
    	while(N-k>=0){
    		for (var u=i;u<k ;u++ ) {
    			mem+=Number(lines[u]);
    		}
    		k++;
    		utu[w]=mem;
    		w++;
    		mem=0;
    	}
    }
    utu=utu.sort(compareNumbers);
    var g=N*(N+1)/2-1;
    max=utu[g];
    for (var i=1;i<K;i++){
    	var v=g-i;
    	max&=utu[v];
    }
    console.log(max);
}

function compareNumbers(a, b) {
  return a - b;
}

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

Score : 400 points

Problem Statement

One day, Niwango-kun, an employee of Dwango Co., Ltd., found an integer sequence (a_1, ..., a_N) of length N.
He is interested in properties of the sequence a.

For a nonempty contiguous subsequence a_l, ..., a_r (1 \leq l \leq r \leq N) of the sequence a, its beauty is defined as a_l + ... + a_r. Niwango-kun wants to know the maximum possible value of the bitwise AND of the beauties of K nonempty contiguous subsequences among all N(N+1)/2 nonempty contiguous subsequences. (Subsequences may share elements.)

Find the maximum possible value for him.

Constraints

2 \leq N \leq 1000

1 \leq a_i \leq 10^9

1 \leq K \leq N(N+1)/2

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 ... a_N

Output

Print the answer.

Sample Input 1

4 2
2 5 2 5

Sample Output 1

12

There are 10 nonempty contiguous subsequences of a. Let us enumerate them:

contiguous subsequences starting from the first element: \{2\}, \{2, 5\}, \{2, 5, 2\}, \{2, 5, 2, 5\}

contiguous subsequences starting from the second element: \{5\}, \{5, 2\}, \{5, 2, 5\}

contiguous subsequences starting from the third element: \{2\}, \{2, 5\}

contiguous subsequences starting from the fourth element: \{5\}

(Note that even if the elements of subsequences are equal, subsequences that have different starting indices are considered to be different.)

The maximum possible bitwise AND of the beauties of two different contiguous subsequences is 12.
This can be achieved by choosing \{5, 2, 5\} (with beauty 12) and \{2, 5, 2, 5\} (with beauty 14).

Sample Input 2

8 4
9 1 8 2 7 5 6 4

Sample Output 2

32


'use strict';

function Main(INPUT) {
    const input = INPUT.split("\n");
    const N = Number(input[0].split(" ")[0]);
    let K = Number(input[0].split(" ")[1]);
    const A = input[1].split(" ").map(n => Number(n));
    let tmpary = [];
    for (let i = 0; i < N; i++) {
        let tmp = 0;
        for (let j = i; j < N; j++) {
            tmp += A[j];
            tmpary.push(tmp);
        }
    }
    tmpary.sort((a, b) => b - a);
    let ans = [];
    for (let i = 0; i <= N - K; i++) {
        ans[i] = tmpary[i];
        for (let j = i; j < K; j++) {
            ans[i] = ans[i] & tmpary[j];
        }
    }
    ans.sort((a, b) => b - a);
    console.log(ans[0]);
}

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


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

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

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

rl.on('close', function () {
    var X = Number(lines[0].split(" ")[0]);
    var Y = Number(lines[0].split(" ")[1]);

    result = X + Y / 2;
    console.log(result);
});

Score: 100 points

Problem Statement

There is a train going from Station A to Station B that costs X yen (the currency of Japan).

Also, there is a bus going from Station B to Station C that costs Y yen.

Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then travels from Station B to Station C by bus.

How much does it cost to travel from Station A to Station C if she uses this ticket?

Constraints

1 \leq X,Y \leq 100

Y is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If it costs x yen to travel from Station A to Station C, print x.

Sample Input 1

81 58

Sample Output 1

110

The train fare is 81 yen.

The train fare is 58 ⁄ 2=29 yen with the 50% discount.

Thus, it costs 110 yen to travel from Station A to Station C.

Sample Input 2

4 54

Sample Output 2

31


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

const list = input.split(' ');

console.log(Number(list[0]) + Number(list[1]) / 2);


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

const temp = (T, x) => T-x*0.006

const Main = () => {
    const N = nextInt()
    const [T, A] = nextIntArray()
    const h = nextIntArray()
    let closest = Number.POSITIVE_INFINITY
    let idx = -1
    for(let i = 0; i<h.length; i++){
        let diff = Math.abs(A-temp(T, h[i]))
        if(diff < closest){
            closest = diff
            idx = i
        }
    }
    console.log(idx+1)
}
Main()

Score: 200 points

Problem Statement

A country decides to build a palace.

In this country, the average temperature of a point at an elevation of x meters is T-x \times 0.006 degrees Celsius.

There are N places proposed for the place. The elevation of Place i is H_i meters.

Among them, Princess Joisino orders you to select the place whose average temperature is the closest to A degrees Celsius, and build the palace there.

Print the index of the place where the palace should be built.

It is guaranteed that the solution is unique.

Constraints

1 \leq N \leq 1000

0 \leq T \leq 50

-60 \leq A \leq T

0 \leq H_i \leq 10^5

All values in input are integers.

The solution is unique.

Input

Input is given from Standard Input in the following format:

N
T A
H_1 H_2 ... H_N

Output

Print the index of the place where the palace should be built.

Sample Input 1

2
12 5
1000 2000

Sample Output 1

1

The average temperature of Place 1 is 12-1000 \times 0.006=6 degrees Celsius.

The average temperature of Place 2 is 12-2000 \times 0.006=0 degrees Celsius.

Thus, the palace should be built at Place 1.

Sample Input 2

3
21 -11
81234 94124 52141

Sample Output 2

3


function Main(inp) {
    var input = inp.split("\n");
    var n = Number(input[0]);
    var t = Number(input[1].split(' ')[0]);
    var a = Number(input[1].split(' ')[1]);
    var heights = input[2].split(' ').map(function(n) { return Number(n);});
    var diff = Number.MAX_VALUE;
    var index = -1;
    heights.forEach(function (h, i) {
        var d = Math.pow(t - h * 0.006, 2) - Math.pow(a, 2);
        if (d < diff) {
            diff = d;
            index = i;
        }
    });
    console.log(index + 1);
}

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


'use strict';

function Main(INPUT) {
    const input = INPUT.split("\n");
    const N = Number(input[0]);
    const T = Number(input[1].split(" ")[0]);
    const A = Number(input[1].split(" ")[1]);
    const H = input[2].split(" ").map(n => Number(n));
    let ans = 1;

    for (let i = 1; i < H.length; i++) {
        if (Math.abs(A - (T - H[i] * 0.006)) < Math.abs(A - (T - H[i - 1] * 0.006))) {
            ans = i + 1;
        }
    }
    console.log(ans);
}

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


'use strict'
function main(input) {
  input = input.trim().split('\n')
  input.shift()
  let count = []
  input = input
    .map(c => {
      let arr = c.split(' ').map(w => w - 0)
      if (count[arr[0]] === undefined) count[arr[0]] = []
      count[arr[0]].push(arr[1])
      return arr
    })
  count.forEach(v => v.sort((a, b) => a - b))
  input = input.map(c => {
    let id = ('000000' + c[0]).slice(-6)
    id += ('000000' + (count[c[0]].indexOf(c[1]) + 1)).slice(-6)
    console.log(id)
  })
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score: 300 points

Problem Statement

In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.

City i is established in year Y_i and belongs to Prefecture P_i.

You can assume that there are no multiple cities that are established in the same year.

It is decided to allocate a 12-digit ID number to each city.

If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.

Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.

Find the ID numbers for all the cities.

Note that there can be a prefecture with no cities.

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq P_i \leq N

1 \leq Y_i \leq 10^9

Y_i are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
P_1 Y_1
:
P_M Y_M

Output

Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).

Sample Input 1

2 3
1 32
2 63
1 12

Sample Output 1

000001000002
000002000001
000001000001

As City 1 is the second established city among the cities that belong to Prefecture 1, its ID number is 000001000002.

As City 2 is the first established city among the cities that belong to Prefecture 2, its ID number is 000002000001.

As City 3 is the first established city among the cities that belong to Prefecture 1, its ID number is 000001000001.

Sample Input 2

2 3
2 55
2 77
2 99

Sample Output 2

000002000001
000002000002
000002000003