const main = function (input) {
 const num = parseInt(input)
const numOfEven=Math.round(num/2)
numOfEven/num
  console.log(numOfEven);
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));

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

Score : 100 points

Problem Statement

Given is an integer N.

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

Find the probability that a is odd.

Constraints

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

4

Sample Output 1

0.5000000000

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

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000

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.


process.stdin.resume();

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

reader.on("line", line => {
  var num = parseInt(line);
  var odd = 0;
  for (var i = 1; i <= num; i++) {
    if (i % 2 !== 0) {
      odd++;
    }
  }
  p = odd / num;
  console.log(p);
});


function Main(input) {
    input = input.split("\n");
    var b = input[1].split(" ").map(e=>parseInt(e,10));

    var c = ""
    b.forEach((ele,ind)=>{
        c+=" "+(b.findIndex(e=>e==ind+1)+1)
    })

    console.log(c.slice(1))
}

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

Score : 300 points

Problem Statement

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

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

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

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

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

Constraints

1 \le N \le 10^5

1 \le A_i \le N

A_i \neq A_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

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

Sample Input 1

3
2 3 1

Sample Output 1

3 1 2

First, student number 3 entered the classroom.

Then, student number 1 entered the classroom.

Finally, student number 2 entered the classroom.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

1 2 3 4 5

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

8 2 4 5 6 7 3 1


function reverse(a){
  return a === 0 ? 1 : 0;
}

function Main(input) {
  const tmp = input.split("\n")[0].split(" ").map((v) => (parseInt(v)));
  const h = tmp[0];
  const w = tmp[1];
  const a = tmp[2];
  const b = tmp[3];

  const ans = [...Array(h).keys()].map((v) => v < b ? 0 : 1).map((v) => {
    return [...Array(w).keys()].map((x) => x < a ? v : reverse(v))
  })

  console.log(ans.map((v) => v.join("")).join("\n") + "\n");
}

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

Score : 300 points

Problem Statement

We have a square grid with H rows and W columns.
Snuke wants to write 0 or 1 in each of the squares.
Here, all of the following conditions have to be satisfied:

For every row, the smaller of the following is A: the number of 0s contained in the row, and the number of 1s contained in the row. (If these two numbers are equal, “the smaller” should be read as “either”.)

For every column, the smaller of the following is B: the number of 0s contained in the column, and the number of 1s contained in the column.

Determine if these conditions can be satisfied by writing 0 or 1 in each of the squares. If the answer is yes, show one way to fill the squares so that the conditions are satisfied.

Constraints

1 \leq H,W \leq 1000

0 \leq A

2 \times A \leq W

0 \leq B

2 \times B \leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W A B

Output

If the conditions cannot be satisfied by writing 0 or 1 in each of the squares, print -1.

If the conditions can be satisfied, print one way to fill the squares so that the conditions are satisfied, in the following format:

s_{11}s_{12}\cdots s_{1W}
s_{21}s_{22}\cdots s_{2W}
\vdots
s_{H1}s_{H2}\cdots s_{HW}

Here s_{ij} is the digit written in the square at the i-th row from the top and the j-th column from the left in the grid.

If multiple solutions exist, printing any of them will be accepted.

Sample Input 1

3 3 1 1

Sample Output 1

100
010
001

Every row contains two 0s and one 1, so the first condition is satisfied.
Also, every column contains two 0s and one 1, so the second condition is satisfied.

Sample Input 2

1 5 2 0

Sample Output 2

01010


function Main(arg) {

    arg = arg.split("\n")[0];
    var H = arg.split(" ")[0]-0;
    var W = arg.split(" ")[1]-0;
    var A = arg.split(" ")[2]-0;
    var B = arg.split(" ")[3]-0;

    var tmp = new Array(W).fill(0);
    var ans = [];
    for (var i = 0; i < H; i++){
        for (var j = 0; j < W; j++){

            if (j < A && i < B) {
                tmp[j] = 0;
            }
            else if(j >= A && i < B) {
                tmp[j] = 1;
            }
            else if(j < A && i >= B) {
                tmp[j] = 1;
            }
            else if(j >= A && i >= B) {
                tmp[j] = 0;
            }

        }
        ans[i] = tmp.slice();
        tmp.fill(0);
    }

    for (var i = 0; i < H; i++) {
        console.log(ans[i].join(""));
    }
}

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


"use strict"

function Main(input) {
  input = input.trim();
  if(input === 'Sunny') console.log('Cloudy');
  if(input === 'Rainy') console.log('Sunny');
  if(input === 'Cloudy') console.log('Rainy');
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score: 100 points

Problem Statement

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

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

Constraints

S is Sunny, Cloudy, or Rainy.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

Sunny

Sample Output 1

Cloudy

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

Sample Input 2

Rainy

Sample Output 2

Sunny


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

function Main(input) {
	S = input.split(" ");
	if (S == 'Sunny'){console.log('Cloudy');
	               }
	      else if (S == 'Cloudy'){console.log('Rainy ');
	                           }

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

  	   }    //    1

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


function Main(input) {
  var od = ['R', 'U', 'D'];
  var ev = ['L', 'U', 'D'];
  input = input.split('');

  var results = 'Yes';
  for (var i = 0; i < input.length; i++) {
    if (input[i] == 'U' || input[i] == 'D') {
      continue;
    }
    if (input[i] == 'R') {
      if ((i + 1) % 2 == 0) {
        results = 'No';
        break;
      }
    } else if (input[i] == 'L') {
      if ((i + 1) % 2 != 0) {
        results = 'No';
        break;
      }

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

Score: 200 points

Problem Statement

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

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

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

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

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

Constraints

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

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

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

RUDLUDR

Sample Output 1

Yes

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

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

Thus, S is easily playable.

Sample Input 2

DULL

Sample Output 2

No

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

Sample Input 3

UUUUUUUUUUUUUUU

Sample Output 3

Yes

Sample Input 4

ULURU

Sample Output 4

No

Sample Input 5

RDULULDURURLRDULRLR

Sample Output 5

Yes


function Main(input) {
  input = input.split("\n");//一行目はinput[0]に、二行目はinput[1]に
var tmp = input[0].split(" ");//一行目の要素一つ目をk[0]に、二つ目をk[1]に……
var N = tmp[0];
var K = tmp[1];
var Q = tmp[2];
if(Q <= K){
  while(N = 0){
    console.log("Yes");
    N --;
  }
}else{
  while(Q = 0){

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

Score: 300 points

Problem Statement

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

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

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 10^9

1 \leq Q \leq 10^5

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

Input

Input is given from Standard Input in the following format:

N K Q
A_1
A_2
.
.
.
A_Q

Output

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

Sample Input 1

6 3 4
3
1
3
2

Sample Output 1

No
No
Yes
No
No
No

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

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

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

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

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

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

Sample Input 2

6 5 4
3
1
3
2

Sample Output 2

Yes
Yes
Yes
Yes
Yes
Yes

Sample Input 3

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

Sample Output 3

No
No
No
No
Yes
No
No
No
Yes
No


Score : 100 points

Problem Statement

Takahashi is going to set a 3-character password.

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

Constraints

1 \leq N \leq 9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of possible passwords.

Sample Input 1

2

Sample Output 1

8

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

Sample Input 2

1

Sample Output 2

1

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


function Main(input){
  //パラメータの受け取り
  input = input.split("\n");
  inputStr = input[0].split(" ");
  const N = Number.parseInt(inputStr[0]);
  inputStr = input[1].split(" ");
  const A  = inputStr.map(inputStr => Number.parseInt(inputStr));
  inputStr = input[2].split(" ");
  const B  = inputStr.map(inputStr => Number.parseInt(inputStr));
  inputStr = input[3].split(" ");
  const C  = inputStr.map(inputStr => Number.parseInt(inputStr));
  //計算処理
  var ans = B[A[0]-1];
  for(var i=1 ; i<N ; i++){
    ans += B[A[i]-1];
    if( A[i] === A[i-1]+1){
      ans += C[(A[i]-1)-1];
    }
  }
  //結果出力
  console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 200 points

Problem Statement

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

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

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

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

Find the sum of the satisfaction points he gained.

Constraints

All values in input are integers.

2 \leq N \leq 20

1 \leq A_i \leq N

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

1 \leq B_i \leq 50

1 \leq C_i \leq 50

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

3
3 1 2
2 5 4
3 6

Sample Output 1

14

Takahashi gained 14 satisfaction points in total, as follows:

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

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

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

Sample Input 2

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

Sample Output 2

74

Sample Input 3

2
1 2
50 50
50

Sample Output 3

150


"use strict"

const arg_str = require('fs').readFileSync('/dev/stdin', 'UTF-8')
const args_lines = arg_str.split('\n')
const N = args_lines[0]
const a = args_lines[1]
const a_s = a.split(' ')
const b = args_lines[2]
const b_s = b.split(' ')
const c = args_lines[3]
const c_s = c.split(' ')

let sum = 0
let last_val = -1

a_s.map(x=>{
    if(b_s[x-1]){
        sum += parseInt(b_s[x-1])
    }
    if(x - 1 == last_val + 1){
        if(c_s.length > 0 && c_s[last_val]){
            sum += parseInt(c_s[last_val])
        }else{
            sum += parseInt(c_s)
        }
    }
    last_val = x - 1
})

console.log(sum)


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


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


input = require('fs').readFileSync('/dev/stdin', 'utf8')
lines = input.split('\n')
line = lines.shift().split(' ')
N = line[0] * 1
K = line[1] * 1
S = lines.shift()

cnt = 0
s = S[0]
for (i=1; i<N; i++) {
    if (s != S[i]) {
        cnt++
        s = S[i]
    }
}

d = cnt - 2 * K
if (d < 1) {
    d = 0
}

console.log(N - 1 - d)

Score : 400 points

Problem Statement

There are N people standing in a queue from west to east.

Given is a string S of length N representing the directions of the people.
The i-th person from the west is facing west if the i-th character of S is L, and east if that character of S is R.

A person is happy if the person in front of him/her is facing the same direction.
If no person is standing in front of a person, however, he/she is not happy.

You can perform the following operation any number of times between 0 and K (inclusive):

Operation: Choose integers l and r such that 1 \leq l \leq r \leq N, and rotate by 180 degrees the part of the queue: the l-th, (l+1)-th, ..., r-th persons. That is, for each i = 0, 1, ..., r-l, the (l + i)-th person from the west will stand the (r - i)-th from the west after the operation, facing east if he/she is facing west now, and vice versa.

What is the maximum possible number of happy people you can have?

Constraints

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

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

|S| = N

Each character of S is L or R.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of happy people after at most K operations.

Sample Input 1

6 1
LRLRRL

Sample Output 1

3

If we choose (l, r) = (2, 5), we have LLLRLL, where the 2-nd, 3-rd, and 6-th persons from the west are happy.

Sample Input 2

13 3
LRRLRLRRLRLLR

Sample Output 2

9

Sample Input 3

10 1
LLLLLRRRRR

Sample Output 3

9

Sample Input 4

9 2
RRRLRLRLL

Sample Output 4

7


function SumAbs(i, tmp){
  var sum = 0;
  sum  = Math.abs(tmp[i])
  if(i+1<tmp.length){
    sum += Math.abs(tmp[i+1])
  }
  if(i+2<tmp.length){
    sum += Math.abs(tmp[i+2]);
  }
  return sum;
}
function Main(input){
  input = input.split("\n");
  inputStr = input[0].split(" ");
  const N = Number.parseInt(inputStr[0]);
  const K = Number.parseInt(inputStr[1]);
  inputStr = input[1].split(" ");
  const S = inputStr[0];
  //文字列Sを重み付けして配列に格納する。Lは正、Rは負とする。
  var tmp = [];
  var lst = S.substr(0,1)
  var cnt = 1;
  for(var i=1 ; i<N ; i++){
    if( S.substr(i,1) != S.substr(i-1,1) ){
      //if( S.substr(i-1,1) === 'R'){
      //  cnt *= -1;
      //}
      tmp.push(cnt);
      cnt = 0;
    }
    cnt += 1;
  }
  //最後の文字列確認
  if( cnt != 0){
      tmp.push(cnt);
  }
  //本体処理
  var ans = 0;
  var cnt = 0;
  if(tmp.length <= 2){
    ans = N-1;
  } else {
    //累積和処理
    for(var j=0 ; j<K ; j++){
      var last = SumAbs(0,tmp);
      var posi = 0;
      for(var i=1 ; i < tmp.length ; i++){
        var now = SumAbs(i,tmp);
        if(last < now){
          last = now;
          posi = i;
        }
      }
      //配列の置き換え
      tmp.splice(posi,3,last);
    }
    //結果出力
    ans = tmp.reduce(function(a, b) {
              return a + b;
    });
    ans -= tmp.length;
  }
  console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n↑入力 ↓出力');
  Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var list = nextIntArray();
  list.sort(function(a,b){
    return a - b;
  });
  var check = [];
  check.push(list[list.length - 1]);
  list[list.length - 1] = -1;
  for(var i = 0; i < N; i++){
    var check2 = makeClone(check);
    check2.sort(function(a,b){
      return a - b;
    });
    var index = (1 << N) - 1;
    while(check2.length > 0 && index >= 0){
      if(list[index] == -1){
        index--;
        continue;
      }
      if(list[index] < check2[check2.length - 1]){
        check.push(list[index]);
        check2.pop();
        list[index] = -1;
      }
      index--;
    }
    if(check2.length > 0){
      myout("No");
      return;
    }
  }
  //myerr(check);
  myout("Yes");
}

Score : 600 points

Problem Statement

We have one slime.

You can set the health of this slime to any integer value of your choice.

A slime reproduces every second by spawning another slime that has strictly less health. You can freely choose the health of each new slime. The first reproduction of our slime will happen in one second.

Determine if it is possible to set the healths of our first slime and the subsequent slimes spawn so that the multiset of the healths of the 2^N slimes that will exist in N seconds equals a multiset S.

Here S is a multiset containing 2^N (possibly duplicated) integers: S_1,~S_2,~...,~S_{2^N}.

Constraints

All values in input are integers.

1 \leq N \leq 18

1 \leq S_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
S_1 S_2 ... S_{2^N}

Output

If it is possible to set the healths of the first slime and the subsequent slimes spawn so that the multiset of the healths of the 2^N slimes that will exist in N seconds equals S, print Yes; otherwise, print No.

Sample Input 1

2
4 2 3 1

Sample Output 1

Yes

We will show one way to make the multiset of the healths of the slimes that will exist in 2 seconds equal to S.

First, set the health of the first slime to 4.

By letting the first slime spawn a slime whose health is 3, the healths of the slimes that exist in 1 second can be 4,~3.

Then, by letting the first slime spawn a slime whose health is 2, and letting the second slime spawn a slime whose health is 1, the healths of the slimes that exist in 2 seconds can be 4,~3,~2,~1, which is equal to S as multisets.

Sample Input 2

2
1 2 3 1

Sample Output 2

Yes

S may contain multiple instances of the same integer.

Sample Input 3

1
1 1

Sample Output 3

No

Sample Input 4

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

Sample Output 4

No


function Main(input) {
    const args = input.split('\n');
    const s = args[0];
    const t = args[1];
    var count = 0;
    for(var i = 0; i < s.length; i++){
        if(s.charAt(i) == t.charAt(i)){
            count++;
        }
    }

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

Score : 100 points

Problem Statement

You will be given a string S of length 3 representing the weather forecast for three days in the past.

The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

You will also be given a string T of length 3 representing the actual weather on those three days.

The i-th character (1 \leq i \leq 3) of S represents the actual weather on the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

Print the number of days for which the forecast was correct.

Constraints

S and T are strings of length 3 each.

S and T consist of S, C, and R.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the number of days for which the forecast was correct.

Sample Input 1

CSS
CSR

Sample Output 1

2

For the first day, it was forecast to be cloudy, and it was indeed cloudy.

For the second day, it was forecast to be sunny, and it was indeed sunny.

For the third day, it was forecast to be sunny, but it was rainy.

Thus, the forecast was correct for two days in this case.

Sample Input 2

SSR
SSR

Sample Output 2

3

Sample Input 3

RRR
SSS

Sample Output 3

0


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

var m = 0
for(var i in stringList[0]) {
  if(stringList[0][i] === stringList[1][i]) {
    m += 1
  }
}

console.log(m)


function *main() {

  const [A, B] = (yield).split(" ").map(s => +s);
  console.log(Math.ceil((B-1)/(A-1)));

}

const iter = main();
iter.next();
require("readline").createInterface({input: process.stdin}).on("line", s => iter.next(s));

Score : 200 points

Problem Statement

Takahashi's house has only one socket.

Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.

One power strip with A sockets can extend one empty socket into A empty sockets.

Find the minimum number of power strips required.

Constraints

All values in input are integers.

2 \leq A \leq 20

1 \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of power strips required.

Sample Input 1

4 10

Sample Output 1

3

3 power strips, each with 4 sockets, extend the socket into 10 empty sockets.

Sample Input 2

8 9

Sample Output 2

2

2 power strips, each with 8 sockets, extend the socket into 15 empty sockets.

Sample Input 3

8 8

Sample Output 3

1


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 ab = lines[0].split(' ');
 var a = Number(ab[0]);
 var b = Number(ab[1]);
var outlet = 1;
var ans = 0;

while(outlet < b){
  outlet--;
  outlet += a;
  ans++;
}

console.log(ans);

});


'use strict'

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

	while (true) {
		if (sum >= B) break
		sum--
		sum += A
		num++
	}

	console.log(num)
}

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


const main = input =>{

    const arr = input.split(" ").map(n => Number(n));
    const num = arr[0];
    const need = arr[1];

    var output = 0;
    var result = 0;

    for(var i = 0; i < 20; i++ ){
        result ++;
        output += num;
        if(output >= need){
            break;
        }

        output --;
    }

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


function Main(input) {
  input=input.split("\n");
  if(input[input.length-1]===''){
    input.pop();
  }
  const N=input[0].split(' ')[0]-0;
  const S=input[1].split(' ').map(e=>{
    return e-0;
  });
  var max=0;
  var previous=0;
  var temp=0;
  for(var i=0;i<N;i++){
    if(previous>=S[i]){
      temp++;
    }else{
      max=Math.max(max,temp);
      temp=0;
    }
    previous=S[i];
  }
  max=Math.max(max,temp);

  console.log(max);

}

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

Score : 300 points

Problem Statement

There are N squares arranged in a row from left to right.

The height of the i-th square from the left is H_i.

You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.

Find the maximum number of times you can move.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq H_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the maximum number of times you can move.

Sample Input 1

5
10 4 8 7 3

Sample Output 1

2

By landing on the third square from the left, you can move to the right twice.

Sample Input 2

7
4 4 5 6 6 5 5

Sample Output 2

3

By landing on the fourth square from the left, you can move to the right three times.

Sample Input 3

4
1 2 3 4

Sample Output 3

0


function Main(input) {
	var data = input.split("\n");
	var n = data[0];
	var masu =  data[1].split(" ").map((n) => parseInt(n, 10));
	var max = 0;
	var t = 0;
	for(var i = (n - 1); i>=0; i--){
		console.log(masu[i], masu[i-1])
		if(masu[i] <= masu[i-1]){
			t++;
			if(t>max) max = t;
		}else if(masu[i] > masu[i-1]){
			t = 0;
		}
	}
	console.log(max)
}

// Don't edit this line!
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
    input = input.split("\n");
    var n = parseInt(input[0], 10);
    var h = input[1].split(" ");
    var count = 0;
    var max = c;
    for (var i = 0; i < (n - 1); i++) {
        if (h[i] >= h[i + 1]) {
            count++;
        } else {
            count = 0;
        }
        if (count > max) {
            max = count;
        }
    }
    //出力
    console.log('%s', max);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const line = require('fs').readFileSync('/dev/stdin','utf8').trim()

const n = parseInt(line)

var answer = n * (n - 1) >> 1

console.log(answer)

Score : 400 points

Problem Statement

For an integer N, we will choose a permutation \{P_1, P_2, ..., P_N\} of \{1, 2, ..., N\}.

Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i.

Find the maximum possible value of M_1 + M_2 + \cdots + M_N.

Constraints

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

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible value of M_1 + M_2 + \cdots + M_N.

Sample Input 1

2

Sample Output 1

1

When the permutation \{P_1, P_2\} = \{2, 1\} is chosen, M_1 + M_2 = 1 + 0 = 1.

Sample Input 2

13

Sample Output 2

78

Sample Input 3

1

Sample Output 3

0


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

console.log(main());
function main(){
  var n=o.a();
  var t=o.m(n);
  var graph=xArray("{from:[],to:[]}",n*(n-1)/2);
  for(var i=0;i<n;i++){
    var b=f(t[i][0]-1,i);
    for(var j=1;j<n-1;j++){
      var a=f(t[i][j]-1,i);
      graph[b].to.push(a);
      graph[a].from.push(b);
      b=a;
    }
  }
  var g=topologicalSort(graph);
  if(g===-1)return -1;
  return g[g.length-1][1]+1;
}

function f(a,b){
  var mx=Math.max(a,b);
  return (mx*(mx-1)>>1)+Math.min(a,b);
}

function topologicalSort(g){
  var n=g.length;
  var a=Array(n).fill(0);
  var q=[];
  for(var i=0;i<n;i++){
    if(g[i].from.length)a[i]=g[i].from.length;
    else q.push([i,0]);
  }
  for(i=0;i<q.length;i++){
    var v=q[i][0];
    for(var j=0;j<g[v].to.length;j++){
      var V=g[v].to[j];
      if(--a[V]===0)q.push([V,q[i][1]+1]);
    }
  }
  return q.length<n?-1:q;
}

Score : 500 points

Problem Statement

N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.

The tournament is round-robin format, and there will be N(N-1)/2 matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.

Each player plays at most one matches in a day.

Each player i (1 \leq i \leq N) plays one match against Player A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} in this order.

Constraints

3 \leq N \leq 1000

1 \leq A_{i, j} \leq N

A_{i, j} \neq i

A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} are all different.

Input

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} \ldots A_{1, N-1}
A_{2, 1} A_{2, 2} \ldots A_{2, N-1}
:
A_{N, 1} A_{N, 2} \ldots A_{N, N-1}

Output

If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.

Sample Input 1

3
2 3
1 3
1 2

Sample Output 1

3

All the conditions can be satisfied if the matches are scheduled for three days as follows:

Day 1: Player 1 vs Player 2

Day 2: Player 1 vs Player 3

Day 3: Player 2 vs Player 3

This is the minimum number of days required.

Sample Input 2

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

Sample Output 2

4

All the conditions can be satisfied if the matches are scheduled for four days as follows:

Day 1: Player 1 vs Player 2, Player 3 vs Player 4

Day 2: Player 1 vs Player 3

Day 3: Player 1 vs Player 4, Player 2 vs Player 3

Day 4: Player 2 vs Player 4

This is the minimum number of days required.

Sample Input 3

3
2 3
3 1
1 2

Sample Output 3

-1

Any scheduling of the matches violates some condition.


function Main(input) {
    input = input.split("\n");
    var a = parseInt(input[0]);
    var nums = input[1].split(' ').map(parseInt);
    var tmp = 0.0;
    for(let i=0; i<a; i++){
        tmp += 1/nums[i]
    }
    console.log(1/tmp);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 200 points

Problem Statement

Given is a sequence of N integers A_1, \ldots, A_N.

Find the (multiplicative) inverse of the sum of the inverses of these numbers, \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Constraints

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print a decimal number (or an integer) representing the value of \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

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

Sample Input 1

2
10 30

Sample Output 1

7.5

\frac{1}{\frac{1}{10} + \frac{1}{30}} = \frac{1}{\frac{4}{30}} = \frac{30}{4} = 7.5.

Printing 7.50001, 7.49999, and so on will also be accepted.

Sample Input 2

3
200 200 200

Sample Output 2

66.66666666666667

\frac{1}{\frac{1}{200} + \frac{1}{200} + \frac{1}{200}} = \frac{1}{\frac{3}{200}} = \frac{200}{3} = 66.6666....

Printing 6.66666e+1 and so on will also be accepted.

Sample Input 3

1
1000

Sample Output 3

1000

\frac{1}{\frac{1}{1000}} = 1000.

Printing +1000.0 and so on will also be accepted.


function Main(input) {
  lines = input.split('\n')
  N = lines[0] * 1
  s = lines[1].split(" ").map(function(a) { return 1 / a * 1 })
  ans = s.reduce(function(i, a) {
      return i + a
  }, 0)
  console.log(1 / ans)
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"))


const readline = require('readline');

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

rl.question('', (N) => {
  rl.question('', (str) => {
    const arr = str.split(' ');
    const nums = arr.map((num) => parseInt(num));
    nums.sort((a, b) => a - b);
    var averSum = nums[0];
    // for(let i = 1; i < parseInt(N); i++) {
    //   averSum = (averSum + nums[i]) / 2;
    // }
    // console.log(averSum);
  });
});

Score : 300 points

Problem Statement

You have a pot and N ingredients. Each ingredient has a real number parameter called value, and the value of the i-th ingredient (1 \leq i \leq N) is v_i.

When you put two ingredients in the pot, they will vanish and result in the formation of a new ingredient. The value of the new ingredient will be (x + y) / 2 where x and y are the values of the ingredients consumed, and you can put this ingredient again in the pot.

After you compose ingredients in this way N-1 times, you will end up with one ingredient. Find the maximum possible value of this ingredient.

Constraints

2 \leq N \leq 50

1 \leq v_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
v_1 v_2 \ldots v_N

Output

Print a decimal number (or an integer) representing the maximum possible value of the last ingredient remaining.

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

Sample Input 1

2
3 4

Sample Output 1

3.5

If you start with two ingredients, the only choice is to put both of them in the pot. The value of the ingredient resulting from the ingredients of values 3 and 4 is (3 + 4) / 2 = 3.5.

Printing 3.50001, 3.49999, and so on will also be accepted.

Sample Input 2

3
500 300 200

Sample Output 2

375

You start with three ingredients this time, and you can choose what to use in the first composition. There are three possible choices:

Use the ingredients of values 500 and 300 to produce an ingredient of value (500 + 300) / 2 = 400. The next composition will use this ingredient and the ingredient of value 200, resulting in an ingredient of value (400 + 200) / 2 = 300.

Use the ingredients of values 500 and 200 to produce an ingredient of value (500 + 200) / 2 = 350. The next composition will use this ingredient and the ingredient of value 300, resulting in an ingredient of value (350 + 300) / 2 = 325.

Use the ingredients of values 300 and 200 to produce an ingredient of value (300 + 200) / 2 = 250. The next composition will use this ingredient and the ingredient of value 500, resulting in an ingredient of value (250 + 500) / 2 = 375.

Thus, the maximum possible value of the last ingredient remaining is 375.

Printing 375.0 and so on will also be accepted.

Sample Input 3

5
138 138 138 138 138

Sample Output 3

138


// inputに入力データ全体が入る
function Main(input) {
  var S = input;
  var arrayS = S.split('');
  var arrayR = [];
  var arrayQ = [];

  for(var i=0; i < arrayS.length; i++){
    if(i == 0){
      if(arrayS[i] != arrayS[i+1])
        arrayR.push(`${arrayS[i]}`);
      else if(arrayS[i] == arrayS[i+1]){
        arrayR.push(`${arrayS[i]}${arrayS[i+1]}`);
        i++
      }
    }
    else{
      if(arrayR.slice(-1)[0] != arrayS[i]){
        arrayR.push(`${arrayS[i]}`);
      }
      else if(arrayR.slice(-1)[0] == arrayS[i]){
        if(arrayS[i+1]){
          arrayR.push(`${arrayS[i]}${arrayS[i+1]}`);
          i++
        }
        else{
          arrayR.push(`${arrayS[i]}`);
        }
      }
      if(arrayR.slice(-1)[0] === arrayR.slice(-2)[0]){
        arrayR.pop();
        arrayR[arrayR.length-1] = `${arrayR[arrayR.length-1]}${arrayR[arrayR.length-1]}`;
      }
    }
  }

  for(var i=0; i < arrayS.length; i++){
    if(i == 0){
        arrayQ.push(`${arrayS[i]}`);
    }
    else{
      if(arrayQ.slice(-1)[0] != arrayS[i]){
        arrayQ.push(`${arrayS[i]}`);
      }
      else if(arrayQ.slice(-1)[0] == arrayS[i]){
        if(arrayS[i+1]){
          arrayQ.push(`${arrayS[i]}${arrayS[i+1]}`);
          i++
        }
        else{
          arrayQ.push(`${arrayS[i]}`);
        }
      }
      if(arrayQ.slice(-1)[0] === arrayQ.slice(-2)[0]){
        arrayQ.pop();
        arrayQ[arrayQ.length-1] = `${arrayQ[arrayQ.length-1]}${arrayQ[arrayQ.length-1]}`;
      }
    }
  }

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

Score : 300 points

Problem Statement

Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:

There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).

Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.

Constraints

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

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum positive integer K that satisfies the condition.

Sample Input 1

aabbaa

Sample Output 1

4

We can, for example, divide S into four strings aa, b, ba, and a.

Sample Input 2

aaaccacabaababc

Sample Output 2

12


function Main(input) {
	var inputdata = input.split(/\s/);
    var A = parseInt(inputdata[0]);
    var B = parseInt(inputdata[1]);
    var datas = ( A+B , A-B , A*B );
    console.log( Math.max.apply(null, datas) );
}

Score : 100 points

Problem Statement

We have two integers: A and B.

Print the largest number among A + B, A - B, and A \times B.

Constraints

All values in input are integers.

-100 \leq A,\ B \leq 100

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest number among A + B, A - B, and A \times B.

Sample Input 1

-13 3

Sample Output 1

-10

The largest number among A + B = -10, A - B = -16, and A \times B = -39 is -10.

Sample Input 2

1 -33

Sample Output 2

34

The largest number among A + B = -32, A - B = 34, and A \times B = -33 is 34.

Sample Input 3

13 3

Sample Output 3

39

The largest number among A + B = 16, A - B = 10, and A \times B = 39 is 39.


"use strict";
const Main = (input) =>{
   let xs = input.trim().split(' ').map(v=>parseInt(v,10));
   let ans = [];
   for(let i = 1; i < xs[0]; i++){
   ans.push(xs[1] - i);
   }
   ans.push(xs[1]);
   for(let i = 1; i < xs[0]; i++){
   ans.push(xs[1] + i);
   }
   const sort = (a,b) =>{
   return a - b;
   }
   ans.sort(sort);
   let ans1 = ans.join(' ');
   console.log(ans1);
}
Main(require('fs').readFileSync('/dev/stdin','utf8'));

Score : 200 points

Problem Statement

There are 2000001 stones placed on a number line. The coordinates of these stones are -1000000, -999999, -999998, \ldots, 999999, 1000000.

Among them, some K consecutive stones are painted black, and the others are painted white.

Additionally, we know that the stone at coordinate X is painted black.

Print all coordinates that potentially contain a stone painted black, in ascending order.

Constraints

1 \leq K \leq 100

0 \leq X \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K X

Output

Print all coordinates that potentially contain a stone painted black, in ascending order, with spaces in between.

Sample Input 1

3 7

Sample Output 1

5 6 7 8 9

We know that there are three stones painted black, and the stone at coordinate 7 is painted black. There are three possible cases:

The three stones painted black are placed at coordinates 5, 6, and 7.

The three stones painted black are placed at coordinates 6, 7, and 8.

The three stones painted black are placed at coordinates 7, 8, and 9.

Thus, five coordinates potentially contain a stone painted black: 5, 6, 7, 8, and 9.

Sample Input 2

4 0

Sample Output 2

-3 -2 -1 0 1 2 3

Negative coordinates can also contain a stone painted black.

Sample Input 3

1 100

Sample Output 3

100


function Main(input){
    const sn = input.split('\n');
    const N = sn.shift();
    let answer = 0;
    let box = new Map();
    for(let i=0; i<sn.length; i++){
        const sortStr = sn[i].split('').sort().join('');
        log(sortStr)
        if(box.has(sortStr)){
            answer++;
        }
        box.set(sortStr);
    }
    console.log(answer);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());

Score : 300 points

Problem Statement

We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.

For example, greenbin is an anagram of beginner. As seen here, when the same character occurs multiple times, that character must be used that number of times.

Given are N strings s_1, s_2, \ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Find the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Constraints

2 \leq N \leq 10^5

s_i is a string of length 10.

Each character in s_i is a lowercase English letter.

s_1, s_2, \ldots, s_N are all distinct.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Sample Input 1

3
acornistnt
peanutbomb
constraint

Sample Output 1

1

s_1 = acornistnt is an anagram of s_3 = constraint. There are no other pairs i, j such that s_i is an anagram of s_j, so the answer is 1.

Sample Input 2

2
oneplustwo
ninemodsix

Sample Output 2

0

If there is no pair i, j such that s_i is an anagram of s_j, print 0.

Sample Input 3

5
abaaaaaaaa
oneplustwo
aaaaaaaaba
twoplusone
aaaabaaaaa

Sample Output 3

4

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


const main = (N,S) => {
    var count = {}
    for(var i = 0;i<N;i++) {
      	var tmp = S[i].sort().join('')
        if(tmp in count) {
            count[tmp] = 1
        }else{
            count[tmp] += count[tmp]+1
        }
    }
  	return Object.values(count).filter(i => Number.isNaN(i) === false ).reduce((i,x) => { return x+i},0)
}

const input = require('fs').readFileSync('/dev/stdin','utf8').split("\n")
const N = Number(input[0])
const S = input.slice(1).map(x => Array.from(x))
console.log(main(N,S))


function Main(input) {
	var idata = input.split(/\n/);
	var N = parseInt(idata[0]);
	var box = [];
	var box2 =[];
	var same = 0;
	var count = 0;
	for(i = 1; i < N+1; i++){
		box[i] = idata[i].split("");
		box[i].sort();
		box2[i]=box[i].toString();
	}
	box2.sort();

	//合ってるか確認
	for(i=1;i<N+1;i++){
		if(box2[i-1]==box2[i]){
			count += 1;
		}else{
			same += count * ( count + 1 ) / 2;
			count = 0;
		}
	}
	console.log(same);
}

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


var input=`
5
abaaaaaaaa
oneplustwo
aaaaaaaaba
twoplusone
aaaabaaaaa
`;
var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.trim().split("\n").reverse();
var n=arr.pop()-0;
var s=arr.map(v=> v.split("").sort().join(""));
s.sort();
var sum=0;
var cnt=1;
s.reduce((a,b)=>{
   if(a==b)cnt++;
   else {
      sum+=(cnt*(cnt-1))/2;
      cnt=1;
   }
   return b;
});
sum+=(cnt*(cnt-1))/2;
console.log(sum);


function Main(input) {
  var output = 0;
  var list = [];
  var list2 = [];

  for(var i = 1; i <= parseInt(input.split("\n")[0]); i++){
    list.push(input.split("\n")[i]);
  }

  for(var i = 0; i < list.length; i++){
    var tmp = list[i];
    var tmpList = [];
    for(var j = 0; j < tmp.length; j++){
      tmpList.push(tmp.slice(j, j +1));
    }
    tmpList.sort();
    var tmp2 = "";
    for(var j = 0; j < tmpList.length; j++){
      tmp2 += tmpList[j];
    }
    list2.push(tmp2);
  }

  var outputList = {};
  var list3 = [];
  for(var i = 0; i < list2.length; i++){
    if(outputList[list2[i]] == null){
       outputList[list2[i]] = 0;
      list3.push(list2[i]);
       }else{
        outputList[list2[i]]++;
       }
  }
  console.log(outputList);

  for(var i = 0; i < list3.length; i++){

    output += pin(outputList[list3[i]]);
  }

  console.log(output);
  function pin(val){
    if(val == 0){
       return 0;
       }
    var ret = 0;
    for(var i = 1; i <= val; i++){
      ret += i;
    }
    return ret;
  }
}

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


"use strict";

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

const main = (inputs) => {
    let N = inputs[0];
    let word;
    let wordArr = [];
    let ans = 0;
    let index;

    let countArr = Array(Number(N)).fill(0);
    for (let i = 1; i <= N; i++) {
        word = inputs[i].split("").sort().join("");

        index = wordArr.findIndex(item => item === word);
        if (0 <= index) {
            ans++;
            countArr[index]++;
        }
        wordArr.push(word);
    }

    // 前のループで出現回数のみカウントしているので、組み合わせ分の回数を足す
    for (let j = 0; j < N; j++) {

        if (countArr[j] > 1) {
            let add = (countArr[j] + 1) * countArr[j] / 2;
            ans = ans + add - countArr[j];
        }
    }

    return ans;
};

console.log(main(inputs));


function Main(input) {
  lines = input.split('\n')
  N = lines.shift() * 1
  ans = 0
  for (i=0; i<N; i++) {
      lines[i] = lines[i].split('').sort().join('')
  }
  for (i=0; i<N; i++) {
      for (j=i+1; j<N; j++) {
          if (lines[i] == lines[j]) {
              ans++
          }
      }
  }
  console.log(ans)
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"))


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

console.log(main());
function main(){
  var n = o.a();
  var s = o.r(n,1).map(a=>a.split("").sort().join("")).sort();
  var ans = 0;
  var t = s[0], u = 0;
  for(var i = 1; i < n; i++){
    if(s[i] === t)u++;
    else{
      ans += u*(u+1)/2;
      u = 0;
      t = s[i];
    }
  }
  if(u)ans += u*(u+1)/2;
  return ans;
}


'use strict'

function main(input) {
  input = input
    .trim()
    .split('\n')
    .map(v => v.split(' ').map(v => ~~v))
  const N = ~~input[0][0]
  const M = ~~input[0][1]
  const jobs = input.slice(1).sort((a, b) => {
    return a[0] - b[0] || a[1] - b[1] // Aの昇順、Bの降順
  })
  // let _ = input.slice(1)
  // const jobs = []
  // for (let i = 0; i < N; i++) {
  //   if (!jobs[_[i][0]]) jobs[_[i][0]] = []
  //   jobs[_[i][0]].push(_[i][1])
  // }
  // console.log(N, M, jobs) // 1000000000 = 1e9

  let ans = 0

  let day = M - 1
  let marker = N // day が有効な、探索の開始位置

  for (let i = day; 0 <= i; i--) {
    // console.log(i)
    let _max = 0
    let _maxind = -1
    for (let j = 0; j < marker; j++) {
      if (M - i >= jobs[j][0]) {
        // console.log(M - i, jobs[j][0], jobs[j][1])
        // enable
        if (_max < jobs[j][1]) {
          _max = jobs[j][1]
          _maxind = j
        }
      } else {
        // // marker = j - 2 > 0 ? j - 2 : 0
        break
      }
    }
    if (_max >= 1) jobs[_maxind][1] = 0 // jobs.splice(_maxind, 1)
    // console.log(_max)
    ans += _max
  }
  // console.log('----')
  console.log(ans)
  // console.log('----')

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

Score : 400 points

Problem Statement

There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.

You can take and complete at most one of these jobs in a day.

However, you cannot retake a job that you have already done.

Find the maximum total reward that you can earn no later than M days from today.

You can already start working today.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i \leq 10^5

1 \leq B_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the maximum total reward that you can earn no later than M days from today.

Sample Input 1

3 4
4 3
4 1
2 2

Sample Output 1

5

You can earn the total reward of 5 by taking the jobs as follows:

Take and complete the first job today. You will earn the reward of 3 after four days from today.

Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today.

Sample Input 2

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

Sample Output 2

10

Sample Input 3

1 1
2 1

Sample Output 3

0


function Main(input) {
  var A = parseInt(input.split(" ")[0]);
  var B = parseInt(input.split(" ")[1]);
  var C = parseInt(input.split(" ")[2]);

  console.log(C - (A - B));

}

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

Score : 100 points

Problem Statement

We have two bottles for holding water.

Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water.

Bottle 2 contains C milliliters of water.

We will transfer water from Bottle 2 to Bottle 1 as much as possible.

How much amount of water will remain in Bottle 2?

Constraints

All values in input are integers.

1 \leq B \leq A \leq 20

1 \leq C \leq 20

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the integer representing the amount of water, in milliliters, that will remain in Bottle 2.

Sample Input 1

6 4 3

Sample Output 1

1

We will transfer two milliliters of water from Bottle 2 to Bottle 1, and one milliliter of water will remain in Bottle 2.

Sample Input 2

8 3 9

Sample Output 2

4

Sample Input 3

12 3 7

Sample Output 3

0


function Main(input) {
    var a = parseInt(input[0], 10);
    var b = parseInt(input[1], 10);
    var c = parseInt(input[2], 10);

    var utusu = a - b;
    console.log((c - utusu) < 0 ? 0 : (c - utusu));
}

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


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

	input = input.split(" ");

	//文字列から10進数に変換するときはparseIntを使います
	var N= parseInt(input[0], 10);

	var n = 0;
	if (N <= 99){var n = 9;
	                       }
	       else if ( N >= 100 && N<= 999 ){n = N-99+9;}
	          else if (N >= 1000 && N<=9999){n = 909;}

	               else if (N >=10000 && N <=99999){ n = N-9999  + 909;}
	               else{var n = 90909;}

   console.log(n);

     }

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

Score : 200 points

Problem Statement

Given is an integer N. Find the number of positive integers less than or equal to N that have an odd number of digits (in base ten without leading zeros).

Constraints

1 \leq N \leq 10^5

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of positive integers less than or equal to N that have an odd number of digits.

Sample Input 1

11

Sample Output 1

9

Among the positive integers less than or equal to 11, nine integers have an odd number of digits: 1, 2, \ldots, 9.

Sample Input 2

136

Sample Output 2

46

In addition to 1, 2, \ldots, 9, another 37 integers also have an odd number of digits: 100, 101, \ldots, 136.

Sample Input 3

100000

Sample Output 3

90909


'use strict'

function main(input) {
  const Num = input.trim()
  const L = Num.length
  const n = ~~Num
  let _mod = 0
  if (L % 2) {
    _mod = (n % Math.pow(10, L - 1)) + 1
  }
  const ll = Math.floor(L / 2)
  let _tmp = ''
  for (let i = 1; i <= ll * 2; i++) {
    _tmp += i % 2 ? '9' : '0'
  }

  _tmp = parseInt(
    _tmp
      .split('')
      .reverse()
      .join(''),
    10
  )
  console.log(_tmp + _mod)
}
main(require('fs').readFilexSync('/dev/stdin', 'utf8'))


const N = parseInt(require("fs").readFileSync("/dev/stdin", "utf8"), 10);

let total = 0;
for (let i = 0; i <= N; i++) {
  if ((Math.floor(Math.log10(i)) + 1) % 2 == 1) {
    total++;
  }
}
console.log(total);


"use strict";

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

const main = directions => {
  let result = Array(directions.length).fill(0);

  let pre = "";
  let cur = "";
  let nex = "";
  let d = "";
  let len = directions.length;
  for (let i = 0; i < len; i++) {
    // 1つづつ、配列から取り出す
    d = directions[i];

    if (d === "R") {
      // Rなら右に走査する
      for (let j = i; j < len; j++) {
        cur = directions[j];
        nex = directions[j + 1];
        if ("RL" === cur + nex) {
          // RL の場所をみつけたらループ終了
          // 開始地点の偶奇をもとに結果の箇所に加算

          if ((j - i) % 2 === 0) {
            result[j]++;
          } else {
            result[j + 1]++;
          }
          break;
        }
      }
    } else if (d === "L") {
      // Lなら左に走査する
      for (let k = i; k >= 0; k--) {
        pre = directions[k - 1];
        cur = directions[k];
        if ("RL" === pre + cur) {
          // RL の場所をみつけたらループ終了
          // 開始地点の偶奇をもとに結果の箇所に加算
          if ((i - k) % 2 === 0) {
            result[k]++;
          } else {
            result[k - 1]++;
          }
          break;
        }
      }
    }
  }

  return result.join(" ");
};

console.log(main(directions));

Score : 400 points

Problem Statement

Given is a string S consisting of L and R.

Let N be the length of S. There are N squares arranged from left to right, and the i-th character of S from the left is written on the i-th square from the left.

The character written on the leftmost square is always R, and the character written on the rightmost square is always L.

Initially, one child is standing on each square.

Each child will perform the move below 10^{100} times:

Move one square in the direction specified by the character written in the square on which the child is standing. L denotes left, and R denotes right.

Find the number of children standing on each square after the children performed the moves.

Constraints

S is a string of length between 2 and 10^5 (inclusive).

Each character of S is L or R.

The first and last characters of S are R and L, respectively.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of children standing on each square after the children performed the moves, in order from left to right.

Sample Input 1

RRLRL

Sample Output 1

0 1 2 1 1

After each child performed one move, the number of children standing on each square is 0, 2, 1, 1, 1 from left to right.

After each child performed two moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.

After each child performed 10^{100} moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.

Sample Input 2

RRLLLLRLRRLL

Sample Output 2

0 3 3 0 0 0 1 1 0 2 2 0

Sample Input 3

RRRLLRLLRRRLLLLL

Sample Output 3

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


var nums = require('fs').readFileSync('/dev/stdin','utf8').split(' '),
    a = parseInt(nums[0]),
    b = parseInt(nums[1]);

if ((a+b) % 2 !== 0)
  console.log('IMPOSSIBLE');
else
  console.log((a+b)/2);

Score: 100 points

Problem Statement

We have two distinct integers A and B.

Print the integer K such that |A - K| = |B - K|.

If such an integer does not exist, print IMPOSSIBLE instead.

Constraints

All values in input are integers.

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

A and B are distinct.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the integer K satisfying the condition.

If such an integer does not exist, print IMPOSSIBLE instead.

Sample Input 1

2 16

Sample Output 1

9

|2 - 9| = 7 and |16 - 9| = 7, so 9 satisfies the condition.

Sample Input 2

0 3

Sample Output 2

IMPOSSIBLE

No integer satisfies the condition.

Sample Input 3

998244353 99824435

Sample Output 3

549034394


"use strict"

function isSortable(args, sorted_args){
  let not_match_cnt = 0
  sorted_args.map((item, key)=>{
    if(sorted_args[key] != args[key]){
      not_match_cnt++
    }
  })
  if(not_match_cnt == 0 || not_match_cnt == 2){
    return true
  }else{
    return false
  }
}

const YES = 'YES'
const NO = 'NO'

const arg_str = require('fs').readFileSync('/dev/stdin', 'UTF-8')
const args_lines = arg_str.split('\n')
const n = args_lines[0]
const target = args_lines[1].split(' ')

if(target.length != n){
  console.log(NO)
  return
}

if(Math.min(...target) != 1 || Math.max(...target) != n){
  console.log(NO)
  return
}

if(n < 2 ||  50 < n){
  console.log(NO)
  return
}

const args_asc = target.slice().sort((a,b)=>a-b)
const args_desc = target.slice().sort((a,b)=>b-a)

const is_sortable_asc = isSortable(target, args_asc)
const is_sortable_desc = isSortable(target, args_desc)

if(is_sortable_asc || is_sortable_desc){
  console.log(YES)
}else{
  console.log(NO)
}

Score : 200 points

Problem Statement

We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}.

You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it.

Print YES if you can sort p in ascending order in this way, and NO otherwise.

Constraints

All values in input are integers.

2 \leq N \leq 50

p is a permutation of {1,\ 2,\ ...,\ N}.

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

Print YES if you can sort p in ascending order in the way stated in the problem statement, and NO otherwise.

Sample Input 1

5
5 2 3 4 1

Sample Output 1

YES

You can sort p in ascending order by swapping p_1 and p_5.

Sample Input 2

5
2 4 3 5 1

Sample Output 2

NO

In this case, swapping any two elements does not sort p in ascending order.

Sample Input 3

7
1 2 3 4 5 6 7

Sample Output 3

YES

p is already sorted in ascending order, so no operation is needed.


function Main(input) {
	input = input.split("\n");
    var N = input[0];
	var vals = input[1].split(" ");
	var org = input[1].split(" ");

  	var count = 0;
  	vals.sort();
  	for(var i=0; i<N; i++)
    {
      if( vals[i] !== org[i] ) count++;
    }

  	var ans = (count===0 || count===2) ? "YES" : "NO";
  	//出力
	console.log(ans);
}

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


const main = (N,A,B) =>  {
    count = 0
    for(var i = 0;i<N;i++) {
        diff = Math.abs(A[i],B[i])
        count+=diff
        A[i] -= diff
        B[i] -= diff
        diff = Math.min(a[i+1],B[i])
        count+=diff
        a[i+1] = diff
    }

    return count

}

const input = require('fs').readFileSync('/dev/stdin','utf8').split("\n")
const N = Number(input[0])
const A = input[1].split(" ").map( x => Number(x))
const B = input[2].split(" ").map(x => Number(x))
console.log(main(N,A,B))

Score : 300 points

Problem Statement

There are N+1 towns. The i-th town is being attacked by A_i monsters.

We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters.

What is the maximum total number of monsters the heroes can cooperate to defeat?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N+1}
B_1 B_2 ... B_N

Output

Print the maximum total number of monsters the heroes can defeat.

Sample Input 1

2
3 5 2
4 5

Sample Output 1

9

If the heroes choose the monsters to defeat as follows, they can defeat nine monsters in total, which is the maximum result.

The first hero defeats two monsters attacking the first town and two monsters attacking the second town.

The second hero defeats three monsters attacking the second town and two monsters attacking the third town.

Sample Input 2

3
5 6 3 8
5 100 8

Sample Output 2

22

Sample Input 3

2
100 1 1
1 100

Sample Output 3

3


function Main(input) {
  input = input.split('\n')
  var N = parseInt(input[0])
  var A = input[1].split(' ').map(str => parseInt(str))
  var B = input[2].split(' ').map(str => parseInt(str))
  var allMonster = A.reduce((prev, current) => prev + current)

  for (var i = 0; i < N; i++) {
    if (A[i] <= B[i]) {
      B[i] -= A[i]
      A[i] = 0
      if (A[i + 1] <= B[i]) {
        A[i + 1] = 0
      } else {
        A[i + 1] -= B[i]
      }
    } else {
      A[i] -= B[i]
    }
  }

  var remainMonster = A.reduce((prev, current) => prev + current)
  console.log(allMonster - remainMonster)
}

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


function main(input){
  input = input.split("\n");
  const n = parseInt(input[0]);
  var a = input[1].split(" ").map(x => parseInt(x))
  var b = input[2].split(" ").map(x => parseInt(x))
  var cnt = 0;
//  console.log(n);

  for (var i = 0; i < n; i++) {
    // a[i]とb[i]の比較
    if (a[i] > b[i]) {
      cnt += b[i];
      a[i] -= b[i];
      b[i] = 0;
    }else {
      cnt += a[i];
      b[i] -= a[i];
      a[i] = 0;
    }

    // a[i+1]とb[i]の比較
    if (a[i+1] > b[i]) {
      cnt += b[i];
      a[i+1] -= b[i];
      b[i] = 0;
    }else {
      cnt += a[i+1];
      b[i] -= a[i+1];
      a[i+1] = 0;
    }

  }

//  console.log(a);
// console.log(b);

  console.log(cnt);

}

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


// 入力とかに使うもの
var reader = require('readline').createInterface({ input: process.stdin, output: process.stdout });
var lines = [];
reader.on('line', function (line) { lines.push(line); });

// メイン
reader.on('close', function () {
	var s = Number(lines[0]);
	var x = 1;
	while(s/x >= 1000000000) x++;
	console.log("0 0 "+x+" 0 0 "+(s/x));
});

Score : 400 points

Problem Statement

Given is an integer S.
Find a combination of six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfies all of the following conditions:

0 \leq X_1,Y_1,X_2,Y_2,X_3,Y_3 \leq 10^9

The area of the triangle in a two-dimensional plane whose vertices are (X_1,Y_1),(X_2,Y_2), and (X_3,Y_3) is S/2.

We can prove that there always exist six integers that satisfy the conditions under the constraints of this problem.

Constraints

1 \leq S \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

S

Output

Print six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfy the conditions, in this order, with spaces in between.
If multiple solutions exist, any of them will be accepted.

Sample Input 1

3

Sample Output 1

1 0 2 2 0 1

The area of the triangle in a two-dimensional plane whose vertices are (1,0),(2,2), and (0,1) is 3/2.
Printing 3 0 3 1 0 1 or 1 0 0 1 2 2 will also be accepted.

Sample Input 2

100

Sample Output 2

0 0 10 0 0 10

Sample Input 3

311114770564041497

Sample Output 3

314159265 358979323 846264338 327950288 419716939 937510582


// 入力とかに使うもの
var reader = require('readline').createInterface({ input: process.stdin, output: process.stdout });
var lines = [];
reader.on('line', function (line) { lines.push(line); });

// メイン
reader.on('close', function () {
	var s = Number(lines[0].split(" ")[0]);
	var x = 1;
	conseole.log("0 0 1 0 0 "+s);
});


//↓見なくていいよ！ここから--------------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error("\n");
  var start = new Date();
  Main();
  var end = new Date() - start;

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

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var r = nextInt();
	myout(r*r*3);
}

Score : 100 points

Problem Statement

It is known that the area of a regular dodecagon inscribed in a circle of radius a is 3a^2.

Given an integer r, find the area of a regular dodecagon inscribed in a circle of radius r.

Constraints

1 \leq r \leq 100

r is an integer.

Input

Input is given from Standard Input in the following format:

r

Output

Print an integer representing the area of the regular dodecagon.

Sample Input 1

4

Sample Output 1

48

The area of the regular dodecagon is 3 \times 4^2 = 48.

Sample Input 2

15

Sample Output 2

675

Sample Input 3

80

Sample Output 3

19200


function main(input){
  input = input.split("\n");
  var r = parseInt(input[0]);

  console.log(3 * r * r);
}

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


function Main(input) {
  var dataList = input.split("\n");
  dataList.shift();
  dataList.pop();
  for (var i = 0; i < dataList.length; i++) {
    dataList[i] = Number(dataList[i]);
  }
  for (var i = 0; i < dataList.length; i++) {
    console.log(gatMax(dataList[i]));
  }
  function gatMax(exclude) {
    var max = 0;
    for (var i = 0; i < dataList.length; i++) {
      if (i === 0) max = dataList[i];
      if (dataList[i] == exclude) continue;
      if (dataList[i] > max) max = dataList[i];
    }
    return max;
  }
}

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

Score : 300 points

Problem Statement

You are given a sequence of length N: A_1, A_2, ..., A_N.
For each integer i between 1 and N (inclusive), answer the following question:

Find the maximum value among the N-1 elements other than A_i in the sequence.

Constraints

2 \leq N \leq 200000

1 \leq A_i \leq 200000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print N lines. The i-th line (1 \leq i \leq N) should contain the maximum value among the N-1 elements other than A_i in the sequence.

Sample Input 1

3
1
4
3

Sample Output 1

4
3
4

The maximum value among the two elements other than A_1, that is, A_2 = 4 and A_3 = 3, is 4.

The maximum value among the two elements other than A_2, that is, A_1 = 1 and A_3 = 3, is 3.

The maximum value among the two elements other than A_3, that is, A_1 = 1 and A_2 = 4, is 4.

Sample Input 2

2
5
5

Sample Output 2

5
5


function Main(input) {
	var inputArr = input.split("\n");

    inputArr.map( str => parseInt(str, 10) );
    var n = inputArr[0];
  　inputArr.shift();
    var max = 0;
    var next = 0;
  　for(var v of inputArr) {
      if (max < v) {
         next = max;
         max = v;
      } else if (next < v) {
         next = v;
      }
    }
  　for(var v of inputArr) {
      console.log(max === v ? next : max);
    }
}

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


function Main(input){
	var tmp = input.split('\n');
  var N = Number(tmp.shift());
  tmp.pop();
  var D = tmp.map(a=>Number(a));
  var arr = [];
  for(var i=0;i<N;i++){
    var tmp = D.filter((a,b,c)=>b!=i);
    arr.push(tmp.reduce((a,b)=>a>b?a:b));
  }
  for(var i=0;i<N;i++){
    console.log(arr[i]);
  }
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
  input = input.split("\n");
  var N = Number(input[0]);
  input.shift();
  var MaxNum = Math.max.apply(null, input);
  var hasMaxNum = 0;
  var subMaxNum = 0;

  for(var j = 0; j < input.length; j++){
    if(subMaxNum < input[j] && input[j] != MaxNum){
      subMaxNum = input[j];
    }
    if(Number(input[j]) == MaxNum && hasMaxNum < 2){
      hasMaxNum = hasMaxNum + 1;
    }
  }

  for(var i = 0; i < input.length; i++){
    if(Number(input[i]) != MaxNum){
      console.log(MaxNum);
    }
    else{
      if(hasMaxNum == 2){
        console.log(MaxNum);
      }
      else{
        console.log(subMaxNum);
      }
    }
  }

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


// inputに入力データ全体が入る
function Main(input) {
	input = input.split("\n"); // 1行目がinput[0], 2行目がinput[1], …に入る
    // ここに処理を書く
    var N = input[0]
    var array = []

    for (var i = 1; i <= input.length-1; i++) {
        array.push(input[i]);
     }

     for (var i = 0; i < N; i++) {
        var arr = array.slice();
        arr.splice(i, 1);
        console.log(arr.slice(0).sort(function(a, b) {return b - a;})[0])
     }
}

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


// inputに入力データ全体が入る
function Main(input) {
	input = input.split("\n"); // 1行目がinput[0], 2行目がinput[1], …に入る
    // ここに処理を書く
    var N = input[0]
    var array = []
    var ans = []

    for (var i = 1; i <= input.length-1; i++) {
        array.push(input[i]);
     }

     for (var i = 0; i < N; i++) {
        var max = 0
        for (var q = 0; q <= N; q++) {
            if(q == i) {
                continue
            }
            if(q==N){
                ans.push(max)
                break
            }

            if (max < Number(array[q])) {
                max = Number(array[q])
            }

        }
     }
    // console.logは標準出力に1行出力します (自動的に最後に改行が入ります)
    for (var i = 0; i < ans.length; i++) {
        console.log(ans[i]);
        // more statements
     }

}

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


function Main(input) {
	input = input.split("\n");
	const N = parseInt(input[0])
	const As = input.slice(1).map(x => parseInt(x))
	var max = 0
	var second = 0
	As.forEach((e,i) => {
		if(As[max] < e){
			second = max
			max = i
		}else if(As[second] < e){
			second = i
		}
	})
	for(i=0; i < N; i++){
		if(i == max){
			console.log(As[second])
		}else{
			console.log(As[max])
		}
	}
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


console.log((args=>{
  const [[N],a] = args.trim().split('\n').map(r=>r.split(' ').map(v=>v|0));
  const b = [], c = Array(N).fill(0);
  for ( let i = N-1; i >= 0; i-- ) {
    let s = 0;
    for ( let j = i; j < N; j+=i+1 ) s ^= c[j];
    c[i] = s ^ a[i];
    if ( c[i] ) b.push(i+1);
  }
  return b.length + '\n' + b.join` `;
})(require('fs').readFileSync('/dev/stdin', 'utf8')));

Score : 400 points

Problem Statement

There are N empty boxes arranged in a row from left to right.
The integer i is written on the i-th box from the left (1 \leq i \leq N).

For each of these boxes, Snuke can choose either to put a ball in it or to put nothing in it.

We say a set of choices to put a ball or not in the boxes is good when the following condition is satisfied:

For every integer i between 1 and N (inclusive), the total number of balls contained in the boxes with multiples of i written on them is congruent to a_i modulo 2.

Does there exist a good set of choices? If the answer is yes, find one good set of choices.

Constraints

All values in input are integers.

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

a_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If a good set of choices does not exist, print -1.

If a good set of choices exists, print one such set of choices in the following format:

M
b_1 b_2 ... b_M

where M denotes the number of boxes that will contain a ball, and b_1,\ b_2,\ ...,\ b_M are the integers written on these boxes, in any order.

Sample Input 1

3
1 0 0

Sample Output 1

1
1

Consider putting a ball only in the box with 1 written on it.

There are three boxes with multiples of 1 written on them: the boxes with 1, 2, and 3. The total number of balls contained in these boxes is 1.

There is only one box with a multiple of 2 written on it: the box with 2. The total number of balls contained in these boxes is 0.

There is only one box with a multiple of 3 written on it: the box with 3. The total number of balls contained in these boxes is 0.

Thus, the condition is satisfied, so this set of choices is good.

Sample Input 2

5
0 0 0 0 0

Sample Output 2

0

Putting nothing in the boxes can be a good set of choices.


console.log((args=>{
  const [[N],a] = args.trim().split('\n').map(r=>r.split(' ').map(v=>v|0));
  const b = [];
  for ( let i = 0; i < N; i++ ) {
    let s = 0;
    for ( let j = i; j < N; j+=i+1 ) s ^= a[j];
    if ( s !== a[i] ) return '-1';
    else if ( s ) b.push(i+1);
  }
  return b.length + '\n' + b.join` `;
})(require('fs').readFileSync('/dev/stdin', 'utf8')));


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  var a = input[1].split(" ").map(i => parseInt(i));
  var bb = new Array(N).fill(0);
  var bsub = new Array();
  var num = 0;
  for(var i=N;i>0;i--){
    var cnt =0;
    for(var j=1;j*i<=N;j++){
      cnt+=bb[j*i-1];
    }
    if(cnt%2!=a[i-1]){
      num++;
      bsub.push(i);
      bb[i-1]++;
    }
  }
  var b = bsub.join(" ");
  var ans = num+"\n"+b;
  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"));


"use strict";

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

    // 逆から考える
    A.reverse();

    let answer = [];
    let list = [];

    for(let i in A) {
        let alreadyIn = 0;

        for(let j=i-(N - i); j>=0; j -= (N - i)) {
            if(list[j] === 1) {
                alreadyIn++;
            }
        }

        if(alreadyIn % 2 === 0) {
            if(A[i] !== 0) {
                answer.push(N - i);
                list.push(1);
            } else {
                list.push(0);
            }
        } else {
            if(A[i] === 0) {
                answer.push(N - i);
                list.push(1);
            } else {
                list.push(0);
            }
        }
    }

    const cnt = answer.length;
    answer.sort((a,b)=>a-b);

    console.log(cnt);
    console.log(answer.join("\n"));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  input.shift();
  var A = input.map(i => parseInt(i));
  A.splice(N,A.length);
  var ans=1;
  var b=Math.pow(10,9)+1;
  for(var i=1;i<N;i++){
    if(A[i]<=A[i-1]&&A[i]<=b){
      ans++;
      b=A[i-1];
    }
  }

  console.log('%s', ans);
  return ans;
}

function debug(n){
  var input = document.getElementById("input"+n).value;
  var ans=Main(input);
  var result="WA";
  if(ans==document.getElementById("output"+n).value.split("\n")[0]){
    result="AC";
  }
  document.getElementById("result"+n).innerHTML=result;
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 500 points

Problem Statement

You are given a sequence with N integers: A = \{ A_1, A_2, \cdots, A_N \}.
For each of these N integers, we will choose a color and paint the integer with that color. Here the following condition must be satisfied:

If A_i and A_j (i < j) are painted with the same color, A_i < A_j.

Find the minimum number of colors required to satisfy the condition.

Constraints

1 \leq N \leq 10^5

0 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the minimum number of colors required to satisfy the condition.

Sample Input 1

5
2
1
4
5
3

Sample Output 1

2

We can satisfy the condition with two colors by, for example, painting 2 and 3 red and painting 1, 4, and 5 blue.

Sample Input 2

4
0
0
0
0

Sample Output 2

4

We have to paint all the integers with distinct colors.


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 list = nextIntArray();
  var count = {};
  for(var i = 0; i < N; i++){
    if(count[list[i]] == null){
      count[list[i]] = 1;
    }else{
      count[list[i]]++;
    }
  }
  var keys = Object.keys(count);
  myerr(keys);
  if(keys.length > 3){
    myout("No");
  }else if(keys.length == 3){

    if((keys[0] ^ keys[1]) == keys[2] && count[keys[0]] == count[keys[1]] && count[keys[1]] == count[keys[2]]){
      myout("Yes");
    }else{
      myout("No");
    }
  }else if(keys.length == 2){
    if(keys.indexOf("0") != -1){

      var zeroCount = count["0"];
      var notZeroCount;
      if(keys[0] != 0){
         notZeroCount = count[keys[0]];
      }else{
         notZeroCount = count[keys[1]];
      }
      myerr(zeroCount);
      myerr(notZeroCount);
      if(notZeroCount / 2 == zeroCount){
        myout("Yes");
      }else{
        myout("No");
      }
    }else{
      myout("No");
    }
  }else{
    if(keys[0] == 0){
      myout("Yes");
    }else{
      myout("No");
    }
  }
}

Score : 300 points

Problem Statement

Snuke has N hats. The i-th hat has an integer a_i written on it.

There are N camels standing in a circle.
Snuke will put one of his hats on each of these camels.

If there exists a way to distribute the hats to the camels such that the following condition is satisfied for every camel, print Yes; otherwise, print No.

The bitwise XOR of the numbers written on the hats on both adjacent camels is equal to the number on the hat on itself.

What is XOR?

The bitwise XOR x_1 \oplus x_2 \oplus \ldots \oplus x_n of n non-negative integers x_1, x_2, \ldots, x_n is defined as follows:

- When x_1 \oplus x_2 \oplus \ldots \oplus x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.

For example, 3 \oplus 5 = 6.

Constraints

All values in input are integers.

3 \leq N \leq 10^{5}

0 \leq a_i \leq 10^{9}

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_{N}

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

Yes

If we put the hats with 1, 2, and 3 in this order, clockwise, the condition will be satisfied for every camel, so the answer is Yes.

Sample Input 2

4
1 2 4 8

Sample Output 2

No

There is no such way to distribute the hats; the answer is No.


function Main(input) {
    const args = input.split(' ');
    var fee;
	var number = parseInt(args[0],10);
    var taxifee = parseInt(args[1],10);
   	var taxiAllFee = number * taxifee
    var trainAllfee = parseInt(args[2],10);

    if(taxiAllFee < trainAllfee){
      fee = taxiAllFee
    }else {
      fee = trainAllfee
    }

	console.log(fee);
}

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

Score : 100 points

Problem Statement

N of us are going on a trip, by train or taxi.

The train will cost each of us A yen (the currency of Japan).

The taxi will cost us a total of B yen.

How much is our minimum total travel expense?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq A \leq 50

1 \leq B \leq 50

Input

Input is given from Standard Input in the following format:

N A B

Output

Print an integer representing the minimum total travel expense.

Sample Input 1

4 2 9

Sample Output 1

8

The train will cost us 4 \times 2 = 8 yen, and the taxi will cost us 9 yen, so the minimum total travel expense is 8 yen.

Sample Input 2

4 2 7

Sample Output 2

7

Sample Input 3

4 2 8

Sample Output 3

8


"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 dist = (y,z) => {
    let sum = 0
    for(let i = 0; i<y.length; i++){
        sum += (y[i]-z[i])**2
    }
    return Math.sqrt(sum)
}
const Main = () => {
    const [N, D] = nextIntArray()
    let x = []
    while(hasNext()){
        x.push(nextIntArray())
    }
    let cnt = 0
    for(let i =0;i<x.length;i++){
        for(let j = i+1; j<x.length;j++){
            if(i == j) continue
            if(Number.isInteger(dist(x[i], x[j]))) cnt++
        }
    }
    console.log(cnt)
}
Main()

Score : 200 points

Problem Statement

There are N points in a D-dimensional space.

The coordinates of the i-th point are (X_{i1}, X_{i2}, ..., X_{iD}).

The distance between two points with coordinates (y_1, y_2, ..., y_D) and (z_1, z_2, ..., z_D) is \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}.

How many pairs (i, j) (i < j) are there such that the distance between the i-th point and the j-th point is an integer?

Constraints

All values in input are integers.

2 \leq N \leq 10

1 \leq D \leq 10

-20 \leq X_{ij} \leq 20

No two given points have the same coordinates. That is, if i \neq j, there exists k such that X_{ik} \neq X_{jk}.

Input

Input is given from Standard Input in the following format:

N D
X_{11} X_{12} ... X_{1D}
X_{21} X_{22} ... X_{2D}
\vdots
X_{N1} X_{N2} ... X_{ND}

Output

Print the number of pairs (i, j) (i < j) such that the distance between the i-th point and the j-th point is an integer.

Sample Input 1

3 2
1 2
5 5
-2 8

Sample Output 1

1

The number of pairs with an integer distance is one, as follows:

The distance between the first point and the second point is \sqrt{|1-5|^2 + |2-5|^2} = 5, which is an integer.

The distance between the second point and the third point is \sqrt{|5-(-2)|^2 + |5-8|^2} = \sqrt{58}, which is not an integer.

The distance between the third point and the first point is \sqrt{|-2-1|^2+|8-2|^2} = 3\sqrt{5}, which is not an integer.

Sample Input 2

3 4
-3 7 8 2
-12 1 10 2
-2 8 9 3

Sample Output 2

2

Sample Input 3

5 1
1
2
3
4
5

Sample Output 3

10


function main(input) {
   input = input.trim();
  const a = input.split("");
  a.sort();
  console.log(a[0] == a[1]
		    &&a[2] == a[3]
		    &&!(a[0] == a[2])?"Yes":"No");
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

You are given a 4-character string S consisting of uppercase English letters.
Determine if S consists of exactly two kinds of characters which both appear twice in S.

Constraints

The length of S is 4.

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S consists of exactly two kinds of characters which both appear twice in S, print Yes; otherwise, print No.

Sample Input 1

ASSA

Sample Output 1

Yes

S consists of A and S which both appear twice in S.

Sample Input 2

STOP

Sample Output 2

No

Sample Input 3

FFEE

Sample Output 3

Yes

Sample Input 4

FREE

Sample Output 4

No


'use strict';

function ary_counter(ary) {
  let c = 0;
  ary.forEach(a => ++c);
  return c;
}

function main(stdin) {
  const l = [];
  let res = 'Yes';

  for (let i = 0; i < 4; ++i) {
    const c = stdin.charCodeAt(i);
    l[c] = l[c] || 0;
    ++l[c];
  }

  if (ary_counter(l) !== 2) res = 'No';

  console.log(res);
}

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


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

var a = input.substr( 0,1 );
  var b = input.substr( 1, 1 );
  var c = input.substr(2, 1 );
  var d = input.substr( 3, 1 );

 var str = input;
// 0文字目から4文字分を指定

 var str = [a,b,c,d];
str.sort();

 var a= str[0];
  var b= str[1];
 var c= str[2];
  var d= str[3];
 //  console.log(a,b,c,d)
var f = 0;
  if (a == b) {
              if (a==c) {console.log('No');}
                        else if (c==d){
                          //console.log('Yes');
                                     var f=1;
                                    }

                            }

     if (f == 1){console.log('Yes')}else{console.log('No');}

}

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


'use strict'

function main(input) {
  input = input
    .split('')
    .slice(0, -1)
    .sort()

  const ans =
    input[0] === input[1] && input[2] === input[3] && input[1] !== input[2]
      ? 'Yes'
      : 'No'
  //Yes // No
  console.log(ans)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'))


// inputに入力データ全体が入る
function Main(input) {
    var S = input;
    var targetStr = S[0]
    var targetStr2 = S[2]
    var count = (S.match(new RegExp(targetStr, "g" ))||[]).length;
    var count2 = (S.match(new RegExp(targetStr2, "g" ))||[]).length;
    if(count == 2 && count2 == 2){
        console.log("Yes")
    }else{
        console.log("No")
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict'

const INF = 900719925474099;
function mapint(temp){
    return temp.split(' ').map((v)=>parseInt(v));
}

function lower_bound(d,a,b,e){
    for(var c;1<b-a;)
        d[c=0|(a+b)/2]<e ? a=c : b=c;
    return d[a]<e?b:a
};

const MOD = 1000000007;

function steps(target,step){

}

function Main(input){
    let temp = input.trim().split('\n');
    let tt = mapint(temp[0]);
    let n = tt[0];
    let m = tt[1];

    let g = [...new Array(n)].map(()=>new Array(0));
    let nt = new Array(n).fill(-1);
    for(let i=1;i<=m;i++){
      tt = mapint(temp[i]);
      g[tt[0]-1].push(tt[1]-1);
    }
    tt = mapint(temp[m+1]);
    let s = tt[0]-1;
    let t = tt[1]-1;
    //console.log(g.map(v=>v.join(' ')),[...nt]);

    let next = [s];
    nt[s] = 0;
    let l = 1;
    let step = 0;
    let f=false;
    let next2 = new Set;
    while(l>0){
    //for(let k=0;k<10;k++){
      next2.clear();
      step++;
      for(let i=0;i<l;i++){
        let ll = g[next[i]].length;
        //console.log('step:',step,' next:',g[next[i]].join(' '));
        for(let j=0;j<ll;j++){
          let gn = g[next[i]][j];
          if(gn == t && step%3 == 0){
            f=true;
            break;
          }
          if(nt[gn] < 0){
            next2.add(gn);
            nt[gn] = step;
          }else{
            if((step - nt[gn])%3 != 0){
              next2.add(gn);
              nt[gn] = step;
            }
          }
        }
        //console.log(nt.join(' '));
        //console.log('---------------------');
        if(f) break;
      }
      if(f) break;
      next = [...next2];
      l = next.length;
      //console.log('loop----------------------------next:',next.join(' '));
    }
    //console.log('exit');
    if(f) console.log(step/3);
    else console.log(-1);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 500 points

Problem Statement

Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G.
G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.

First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.

Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq \min(10^5, N (N-1))

1 \leq u_i, v_i \leq N(1 \leq i \leq M)

u_i \neq v_i (1 \leq i \leq M)

If i \neq j, (u_i, v_i) \neq (u_j, v_j).

1 \leq S, T \leq N

S \neq T

Input

Input is given from Standard Input in the following format:

N M
u_1 v_1
:
u_M v_M
S T

Output

If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1.
If he can, print the minimum number of ken-ken-pa needed to reach vertex T.

Sample Input 1

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

Sample Output 1

2

Ken can reach Vertex 3 from Vertex 1 in two ken-ken-pa, as follows: 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 in the first ken-ken-pa, then 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 in the second ken-ken-pa. This is the minimum number of ken-ken-pa needed.

Sample Input 2

3 3
1 2
2 3
3 1
1 2

Sample Output 2

-1

Any number of ken-ken-pa will bring Ken back to Vertex 1, so he cannot reach Vertex 2, though he can pass through it in the middle of a ken-ken-pa.

Sample Input 3

2 0
1 2

Sample Output 3

-1

Vertex S and Vertex T may be disconnected.

Sample Input 4

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

Sample Output 4

2


function Main(input){
	var array = [];
	var difficultFlag = 0;
	for(var i = 0; i<2;i++){
		array.push(input.slice(i,i+3));
      	if(array[0] == array[1] || array[1] == array[2]){
        	difficultFlag = 1;
        }
    }
  	if(difficultFlag == 1){
     console.log('Bad');
    }else{
     console.log('Good');
    }

}

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

Score : 100 points

Problem Statement

The door of Snuke's laboratory is locked with a security code.

The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same.

You are given the current security code S. If S is hard to enter, print Bad; otherwise, print Good.

Constraints

S is a 4-character string consisting of digits.

Input

Input is given from Standard Input in the following format:

S

Output

If S is hard to enter, print Bad; otherwise, print Good.

Sample Input 1

3776

Sample Output 1

Bad

The second and third digits are the same, so 3776 is hard to enter.

Sample Input 2

8080

Sample Output 2

Good

There are no two consecutive digits that are the same, so 8080 is not hard to enter.

Sample Input 3

1333

Sample Output 3

Bad

Sample Input 4

0024

Sample Output 4

Bad


function Main(input){
   	input = input;

  	var num = String(input[0]);
    var j = 1;
  	var judge = 0;
  	var array = num.split('');

  		for(var i=0;i<3;i++){
			if(array[i] == array[j]){
        		judge++;
        	}
          	else{
    			j++;
            }
		}

  	if(judge == 0){
      console.log('good');
    }
    else{
      console.log('bad');
    }
}
 Main(require("fs").readFileSync("/dev/stdin","utf-8"));


function Main(input){
   	input = input;

  	var num = String(input);
    var j = 1;
  	var judge = 0;
  	var array = num.split('');

  		for(var i=0;i<3;i++){
			if(array[i] == array[j]){
        		judge++;
        	}
          	else{
    			j++;
            }
		}

  	if(judge == 0){
      console.log('good');
    }
    else{
      console.log('bad');
    }
}
 Main(require("fs").readFileSync("/dev/stdin","utf-8"));


'use strict'
const inputs = require('fs').readFileSync(0, 'utf8').split('\n')
inputs.shift()
const tasks = []
for (const input of inputs) {
  const ab = input.split(' ')
  tasks.push({a: ab[0], b: parseInt(ab[1], 10)})
}
tasks.sort(function(x, y) {return x.b - y.b})
let time = 0
for (const task of tasks) {
  time += parseInt(task.a, 10)
  if (time > task.b) return console.log('No')
}
return console.log('Yes')

Score: 400 points

Problem Statement

Kizahashi, who was appointed as the administrator of ABC at National Problem Workshop in the Kingdom of AtCoder, got too excited and took on too many jobs.

Let the current time be time 0. Kizahashi has N jobs numbered 1 to N.

It takes A_i units of time for Kizahashi to complete Job i. The deadline for Job i is time B_i, and he must complete the job before or at this time.

Kizahashi cannot work on two or more jobs simultaneously, but when he completes a job, he can start working on another immediately.

Can Kizahashi complete all the jobs in time? If he can, print Yes; if he cannot, print No.

Constraints

All values in input are integers.

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

1 \leq A_i, B_i \leq 10^9 (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
.
.
.
A_N B_N

Output

If Kizahashi can complete all the jobs in time, print Yes; if he cannot, print No.

Sample Input 1

5
2 4
1 9
1 8
4 9
3 12

Sample Output 1

Yes

He can complete all the jobs in time by, for example, doing them in the following order:

Do Job 2 from time 0 to 1.

Do Job 1 from time 1 to 3.

Do Job 4 from time 3 to 7.

Do Job 3 from time 7 to 8.

Do Job 5 from time 8 to 11.

Note that it is fine to complete Job 3 exactly at the deadline, time 8.

Sample Input 2

3
334 1000
334 1000
334 1000

Sample Output 2

No

He cannot complete all the jobs in time, no matter what order he does them in.

Sample Input 3

30
384 8895
1725 9791
170 1024
4 11105
2 6
578 1815
702 3352
143 5141
1420 6980
24 1602
849 999
76 7586
85 5570
444 4991
719 11090
470 10708
1137 4547
455 9003
110 9901
15 8578
368 3692
104 1286
3 4
366 12143
7 6649
610 2374
152 7324
4 7042
292 11386
334 5720

Sample Output 3

Yes