function Main(input) {
  input = input.split("\n");
  const n = input[0].split(" ")[0];
  const k = input[0].split(" ")[1];
  const s = input[1].split("");

  var happyRCount = 0;
  var happyLCount = 0;

  for (var i = 0; i < n - 1 ; i ++) {
    if (s[i] === "R" && s[i + 1] === "R") {
      happyRCount = happyRCount + 1;
    }
  }

  for (var i = n-1; i > 0 ; i --) {
    if (s[i] === "L" && s[i - 1] === "L") {
      happyLCount = happyLCount + 1;
    }
  }

  var happyCount = happyRCount + happyLCount;

  var maxHappyCount = 0;

  if (happyCount + k * 2 > n -1 ) {
    maxHappyCount = n -1;
  } else {
    maxHappyCount = happyCount + k * 2;
  }
  console.log(maxHappyCount);
}

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

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


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

var lines = [];
reader.on('line', function(line) {
  lines.push(line);
});

reader.on('close', function() {
  var ans = 0;
  for(var i=0; i<3; ++i) if(lines[0][i]==lines[1][i]) ++ans;
  console.log(ans);
});

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

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

Submitted source-code file size, in bytes.

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

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


function Main(input) {
    input = input.split("\n")
    var S = input[0];
    var T = input[1];
    var count = 0;
    if(S[0] == T[0]){
      count++
    }
    if(S[1] == T[1]){
      count++
    }
    if(S[2] == T[2]){
      count++
    }
    console.log(count)
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
	input = input.split("\n");
	const S = input[0]
	const T = input[1]
	var n = 0
	for(i=0; i < 3; i++){
		if(S[i] == T[i]) n++
	}
	console.log(n)
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  input = input.replace(/\n/g, ' ');
  input = input.split(" ");
  var A = input[0];
  var B = input[1];
  var i=0;
  while(true){
    if(B<=(A*i-(i-1))){
      break;
    }
    i++;
  }
  console.log(i);

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

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


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


function Main(input){
var N = input.trim();
N = parseInt(N,10);
var values = 0;
for(i=1;i<=(N-1);i++){
  values += i;
}
console.log(values);
}
  Main(require('fs').readFileSync('/dev/stdin','utf8'));

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


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.


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);}
var n,x=[],y=[],c=[];
var q = 360000*3;

console.log(main());
function main(){
  n = o.a();
  for(var i = 0; i < n; i++){
    var a = o.a(), b = o.a();
    if(a === 0 && b === 0)continue;
    x.push(a);
    y.push(b);
    c.push(f(a,b));
  }
  n = x.length;
  var ans = 0;
  for(var i = 0; i < q; i++){
    var v = i*360/q;
    var tx = 0, ty = 0;
    for(var j = 0; j < n; j++){
      if((v-90 <= c[j] && c[j] <= v+90) || v+270 <= c[j]){
        tx += x[j], ty += y[j];
      }
    }
    var z = tx*tx+ty*ty;
    if(ans < z)ans = z;
  }
  return Math.sqrt(ans);
}

function f(x,y){
  if(x === 0){
    return y > 0 ? 90 : 270;
  }
  if(y === 0){
    return x > 0 ? 0 : 180;
  }
  var r = Math.atan(y/x)/Math.PI*180;
  if(x < 0)r += 180;
  if(r < 0)r += 360;
  return r;
}

Score: 600 points

Problem Statement

E869120 is initially standing at the origin (0, 0) in a two-dimensional plane.

He has N engines, which can be used as follows:

When E869120 uses the i-th engine, his X- and Y-coordinate change by x_i and y_i, respectively. In other words, if E869120 uses the i-th engine from coordinates (X, Y), he will move to the coordinates (X + x_i, Y + y_i).

E869120 can use these engines in any order, but each engine can be used at most once. He may also choose not to use some of the engines.

He wants to go as far as possible from the origin.
Let (X, Y) be his final coordinates. Find the maximum possible value of \sqrt{X^2 + Y^2}, the distance from the origin.

Constraints

1 \leq N \leq 100

-1 \ 000 \ 000 \leq x_i \leq 1 \ 000 \ 000

-1 \ 000 \ 000 \leq y_i \leq 1 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
: :
x_N y_N

Output

Print the maximum possible final distance from the origin, as a real value.
Your output is considered correct when the relative or absolute error from the true answer is at most 10^{-10}.

Sample Input 1

3
0 10
5 -5
-5 -5

Sample Output 1

10.000000000000000000000000000000000000000000000000

The final distance from the origin can be 10 if we use the engines in one of the following three ways:

Use Engine 1 to move to (0, 10).

Use Engine 2 to move to (5, -5), and then use Engine 3 to move to (0, -10).

Use Engine 3 to move to (-5, -5), and then use Engine 2 to move to (0, -10).

The distance cannot be greater than 10, so the maximum possible distance is 10.

Sample Input 2

5
1 1
1 0
0 1
-1 0
0 -1

Sample Output 2

2.828427124746190097603377448419396157139343750753

The maximum possible final distance is 2 \sqrt{2} = 2.82842....
One of the ways to achieve it is:

Use Engine 1 to move to (1, 1), and then use Engine 2 to move to (2, 1), and finally use Engine 3 to move to (2, 2).

Sample Input 3

5
1 1
2 2
3 3
4 4
5 5

Sample Output 3

21.213203435596425732025330863145471178545078130654

If we use all the engines in the order 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5, we will end up at (15, 15), with the distance 15 \sqrt{2} = 21.2132... from the origin.

Sample Input 4

3
0 0
0 1
1 0

Sample Output 4

1.414213562373095048801688724209698078569671875376

There can be useless engines with (x_i, y_i) = (0, 0).

Sample Input 5

1
90447 91000

Sample Output 5

128303.000000000000000000000000000000000000000000000000

Note that there can be only one engine.

Sample Input 6

2
96000 -72000
-72000 54000

Sample Output 6

120000.000000000000000000000000000000000000000000000000

There can be only two engines, too.

Sample Input 7

10
1 2
3 4
5 6
7 8
9 10
11 12
13 14
15 16
17 18
19 20

Sample Output 7

148.660687473185055226120082139313966514489855137208


//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();
  for(var i = 1; i <= N - 1; i++){
    var output = new Array(N - i);
    for(var j = i + 1; j <= N; j++){
      for(var k = 0; k < 10; k++){
        if(((i ^ j) >> k) % 2 != 0){
          output[j - i - 1] = k + 1;
          break;
        }
      }
    }
    myout(myconv(output, 8));
  }

}

Score: 600 points

Problem Statement

AtCoder's head office consists of N rooms numbered 1 to N. For any two rooms, there is a direct passage connecting these rooms.

For security reasons, Takahashi the president asked you to set a level for every passage, which is a positive integer and must satisfy the following condition:

For each room i\ (1 \leq i \leq N), if we leave Room i, pass through some passages whose levels are all equal and get back to Room i, the number of times we pass through a passage is always even.

Your task is to set levels to the passages so that the highest level of a passage is minimized.

Constraints

N is an integer between 2 and 500 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print one way to set levels to the passages so that the objective is achieved, as follows:

a_{1,2} a_{1,3} ... a_{1,N}
a_{2,3} ... a_{2,N}
.
.
.
a_{N-1,N}

Here a_{i,j} is the level of the passage connecting Room i and Room j.

If there are multiple solutions, any of them will be accepted.

Sample Input 1

3

Sample Output 1

1 2
1

The following image describes this output:

For example, if we leave Room 2, traverse the path 2 \to 3 \to 2 \to 3 \to 2 \to 1 \to 2 while only passing passages of level 1 and get back to Room 2, we pass through a passage six times.


main = input => {
  input = input.split('\n');
  var v = input[1].split(' ').map(parseFloat);

  for(var i = 0;v.length !== 1;i++){
    v.sort((a,b) => a < b);
    var num1 = v.pop();
    var num2 = v.pop();
    v.push((num1 + num2)/2);
  }
  console.log(v[0])
}
main(require('fs').readFileSync('/dev/stdin','utf8'));

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


function Main(input) {
	var inputdata = input.split(/\s/);
	var ip = inputdata.slice(1);
	ip.sort((a,b)=>a-b);
	var c = parseFloat(ip[0])*1000000;
	for(var i=1;i<inputdata[0];i++){
	    c = (parseFloat(c)+parseFloat(ip[i])*1000000)/2;
	}
  if(c!==c)process.exit(1);
	console.log(c/1000000);
}

function compareFunc(a, b) {
    return parseFloat(a) - parseFloat(b);
}

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


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	var input2 = input.split("\n");
	//文字列から10進数に変換するときはparseIntを使います
	var input3 = input2[1].split(" ");

  	input3.sort()

  var num = parseInt(input3[0],10)
  	for(var i=1; i< parseInt(input2[0],10); i++){

      num = (num + parseInt(input3[parseInt(i,10)],10))/2
      input3.shift();
      input3.push(num);
      input3.sort()
    }

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


function Main(input) {

    var s = input.split('\n')[0];
    var str = s;
    var t = input.split('\n')[1];

    var set = new Set(t.split(''));

    for (var x of set) {
        if (s.indexOf(x) === -1) {
            console.log(-1);
            return;
        }
    }

    var ans = 0;
    var f = true;
    var first = 0;
    while (1) {
        var tmp = s.length;
        for (var i = 0; i < t.length; i++){
            var a = s.substr(0, tmp).lastIndexOf(t[t.length - 1 - i]);
            if (tmp < a || a === -1) {
                f = false;
                break;
            }
            if (i === 0) first = a;
            tmp = a;
        }
        if (f) {
            ans = tmp;
            break;
        }
        s = s + str;
        f = true;
    }

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

Score : 500 points

Problem Statement

Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.

Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').

Notes

A subsequence of a string a is a string obtained by deleting zero or more characters from a and concatenating the remaining characters without changing the relative order. For example, the subsequences of contest include net, c, and contest.

Constraints

1 \leq |s| \leq 10^5

1 \leq |t| \leq 10^5

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print -1.

Sample Input 1

contest
son

Sample Output 1

10

t = son is a subsequence of the string contestcon (the first 10 characters in s' = contestcontestcontest...), so i = 10 satisfies the condition.

On the other hand, t is not a subsequence of the string contestco (the first 9 characters in s'), so i = 9 does not satisfy the condition.

Similarly, any integer less than 9 does not satisfy the condition, either. Thus, the minimum integer i satisfying the condition is 10.

Sample Input 2

contest
programming

Sample Output 2

-1

t = programming is not a substring of s' = contestcontestcontest.... Thus, there is no integer i satisfying the condition.

Sample Input 3

contest
sentence

Sample Output 3

33

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


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const S = arg[0];

    let before  = "";
    let current = "";
    let list   = [];

    for(let i=0; i<S.length; i++) {
        current += S[i];

        if(current === before) {
            continue;
        }

        before = current;
        list.push(current);

        current = "";
    }

    console.log(list.length);
}
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


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const S = arg[0];

    let cnt     = 0;
    let before  = "";
    let current = "";
    let debug   = [];

    for(let i=0; i<S.length; i++) {
        current += S[i];

        if(current === before) {
            continue;
        }

        before = current;
        debug.push(current);

        current = "";

        cnt++;
    }

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


function main(input) {
  input=input.trim();
  const S=input.split('').map((n) => (n));
  var arr=[];
  var arrayNum=0;
  var memo=[];
  for(var i=0; i<S.length; i++){
    if(S[i]==S[i+1]){
      if(arr[arrayNum]==null){
        arr[arrayNum]=2
        memo.push(i)
      }else{
        if(i!=0 && S[i]!=S[i-1]){
          //この処理は、「1つ後が同じ数字だが、新しい塊の先頭の場合にarrを新しくする処理」
          arrayNum+=1;
          arr[arrayNum]=2;
          memo.push(i)
          //console.log("今は"+i+"番目で、新しく配列を作った"+arrayNum);
        }else{
          //通常処理
          arr[arrayNum]++
          //console.log("今は"+i+"番目で、通常処理を行った");
        }
      }
      }
  }
  //console.log(arr);

  //↑連続するものについて、その長さを書いた配列

  //console.log(memo);
  //↑連続配列の先頭の番号をメモした配列

  var minus=0
  //連続する塊同士が隣接し、かつそれが両方3で割った余りが2で、かつ連続する塊の3つ目でない場合
  for(var i=1; i<memo.length; i++){
    if(memo[i]==memo[i-1]+arr[i-1] && memo[i]%3==memo[i-1]%3==2){
      if(memo[i-1]!=memo[i-2]+arr[i-2]){
        minus++
      }
    }
  }

  //以下で、引く値の合計を計算。
  var ans=0;
  for(var i=0; i<arr.length; i++){
    if(arr[i]%3==0){
      arr[i]=arr[i]-(Math.floor(arr[i]/3)*2);
    }else{
      arr[i]=arr[i]-(Math.floor(arr[i]/3)*2+1);
    }
    ans+=arr[i]
  }

  //console.log(minus);
  console.log(S.length-ans+minus);

}

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


function main(input) {
  const [ math1Str, math2Str ] = input.split('-');
  const one = Number(math1Str);
  const tow = Number(math2Str);
  const item = [
    one + tow,
    one - tow,
    one * tow,
  ];
  console.log(Math.max(item));
}

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.


function Main(input) {
  input = input.split(" ");
  var a = input[0],
      b = input[1]
  console.log(Math.max(a + b, a * b, a - b))
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const A, B;

let result

const sum = A + B
const sub = A - B
const mul = A * B

let result = sum

if (result < sub)
  result = sub

if (result < mul)
  result = mul

return result


const main = (k,x) => {
    let r = []
    for(let i = x;i<x+k;i++) {
        r.push(i)
    }

    for(let i = x;i>x-k;i--) {
        r.push(i)
    }

    return r.filter( (elem,index,self) => {
        return self.indexOf(elem) === index

    })
}

const input = require('fs').readFileSync('/dev/stdin','utf8').split('\n')[0].split(" ")
const kx = input.map(x => parseInt(x,10))
console.log(main(kx[0],kx[1]).sort((a,b) => a - b).join(" "))

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


'use strict';
const main = input => {
  const n = parseInt(input[0], 10);
  input.shift();
  input.pop();
  let s = new Array(n);
  s = input;
  s = s.map(val => [...val].sort((x,y)=>x>y?1:-1).toString()).sort();
  // console.log(s);
  let t = s[0], val = 0, ans = 0;
  for(let i=1; i<n; i++) {
    if (s[i] == t) val++;
    else {
      ans += val*(val+1)/2;
      val = 0;
      t = s[i];
    }
  }
  if (val) ans += val*(val+1)/2;
  console.log(ans);

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

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.


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

  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);
    if(list3.indexOf(tmp2) == null){
       list3.push(tmp2);
       }
  }

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

  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'

function Main(input) {
  const N = Number(input.split("\n")[0])
  const list = input.split("\n").slice(1)
  let ans = 0

  for(let i=0; i<N; i++) {
    const alpha = agg(list[i])
    for(let j=i+1; j<N; j++) {
      const alpha2 = agg(list[j])
      const json1 = JSON.stringify(alpha)
      const json2 = JSON.stringify(alpha2)
      if(json1 === json2) {
        ans++
      }
    }
  }

  console.log(ans)
}

function agg(str) {
  const alpha = {}
  const converted = str.split("")
  for(let i=0; i<10; i++) {
    if(alpha[converted[i]] == null) {
      alpha[converted[i]] = 0
    }
    alpha[converted[i]]++
  }
  return Object.keys(alpha).sort()
}
Main(require("fs").readFileSync("/dev/stdin", "utf8").trim())


function Main(input) {
	var idata = input.split(/\s/);
	console.log(Math.max(0,parseInt(idata[2])-parseInt(idata[0])+parseInt(idata[1])));
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
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


var lines = [];
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
reader.on('line', (line) => {
  lines.push(line);
});
reader.on('close', () => {
  var amount = lines[2] - (lines[0] - lines[1]);
  if (amount < 0) {
    amount = 0
  }
  console.log(amount);
});


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


function Main(input) {
	var idata = parseInt(input);
	if(input.length==1){
		console.log(idata);
	}else if(input.length==2){
		console.log(9);
	}else if(input.length==3){
		console.log(idata-90);
	}else if(input.length==4){
		console.log(909);
	}else if(input.length==5){
		console.log(idata-9090);
	}else if(input.length==6){
		console.log(90909);
	}
}

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


function Main(input) {
	input = input.split("\n");
	var answer = 0;
 	for(var i=input; i>0; i--){
      if(i.toString().length%2 == 1){
        answer++;
      }
    }
	console.log(answer);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


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


function Main(input) {
	var idata = input.split("");
	var ninzuu = [];
	var nextninzuutemp = [];
	//人数の配列を生成
	for( let i=0; i<idata.length ; i++ ){
	    ninzuu.push(1);
	    nextninzuutemp.push(0);
	}
	var nextninzuu = nextninzuutemp.slice();
	//一回ごとに操作が行われる
	for( let turn=0; turn<10 ; turn++ ){
		for( let j=0; j<ninzuu.length ; j++ ){
			//着目しているマスに右に行けと書いてあった場合
			if(idata[j]=="R"){
				nextninzuu[j+1]+=ninzuu[j];
			}else if(idata[j]=="L"){
			    nextninzuu[j-1]+=ninzuu[j];
			}
		}
		if(ninzuu.toString()==nextninzuu.toString()){
			return console.log(ninzuu.join(' '));
		}
		ninzuu = nextninzuu.slice();
		nextninzuu = nextninzuutemp.slice();
	}
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const S = arg[0].split("");

    let Rstock = 0;
    let Lstock = 0;
    let splitPoint;
    let splitCount = 0;

    let answer = [...Array(S.length)].fill(0);

    for(let i=0; i<S.length-1; i++) {
        if(S[i] === "R") Rstock++;
        if(S[i] === "L") Lstock++;

        // RL の部分であるかどうか
        if(S[i] !== S[parseInt(i) + 1]) {
            splitCount++;

            if(splitCount === 1) {
                splitPoint = i;
            }
        }

        if(splitCount === 2) {
            if((Rstock + Lstock) % 2 === 0) {
                answer[splitPoint]     = (Rstock + Lstock) / 2;
                answer[splitPoint + 1] = (Rstock + Lstock) / 2;
            } else {
                if((Math.max(Rstock, Lstock) - 1) % 2 === 0) {
                    answer[splitPoint]     = Rstock;
                    answer[splitPoint + 1] = Lstock;
                } else {
                    answer[splitPoint]     = Lstock;
                    answer[splitPoint + 1] = Rstock;
                }
            }

            splitCount = 0;

            Rstock = 0;
            Lstock = 0;
        }

        if(i === S.length - 2) {
            Lstock++;

           if((Rstock + Lstock) % 2 === 0) {
                answer[splitPoint]     = (Rstock + Lstock) / 2;
                answer[splitPoint + 1] = (Rstock + Lstock) / 2;
            } else {
                answer[splitPoint]     = Lstock;
                answer[splitPoint + 1] = Rstock;
            }
        }
    }

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


function main(arg) {
    const A = parseInt( arg.split(/\s/)[0] );
    const B = parseInt( arg.split(/\s/)[1] );
    var ans = (A+B)/2;
    if(ans==parseInt(ans)){
        console.log(ans);
    }else{
        console.log("IMPOSSIBLE");
    }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

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


// inputに入力データ全体が入る
function Main(input) {
		input = input.split(" ");

	//文字列から10進数に変換するときはparseIntを使います
	    var A = parseInt(input[0], 10);
    var B = parseInt(input[1], 10);
  var c = 0;
  var c =(A +B)%2;
 // console.log(c);
  if (c== 0){console.log((A+B)/2);
            }else{console.log("IMPOSSIBLE");
                 }

  	   }    //    1

  //*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
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));
    const B = arg[2].split(" ").map(n=>parseInt(n));

    const sum = A.reduce((m,n)=>m+n);

    let cnt  = 0;
    let rest = 0;

    for(let i=0; i<N; i++) {
        if(A[i] >= B[i]) {
            cnt += B[i];
            continue;
        }

        let temp = B[i] - A[i];

        cnt += A[i];
        cnt += Math.min(temp, A[parseInt(i)+1]);

        A[parseInt(i)+1] = Math.max(A[parseInt(i)+1] - temp, 0);
    }

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

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


"use strict";
const input = parseInt(require("fs").readFileSync("/dev/stdin", "utf8"));
// const inputs = input.trim().split("\n").map(x => parseInt);
// const input = 3;

const main = (input) => {
  let a,b,c,d,left;
  let sqrt = Math.sqrt(input);
  a = Math.ceil(sqrt);
  d = Math.ceil(sqrt);
  left = a * d - input;
  if (left === 0) {
    b = 0;
    c = 0;
  } else {
    b = 1;
    c = left;
  }

  return `0 0 ${a} ${b} ${c} ${d}`;
};

console.log(main(input));

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


function main(input) {
   input = input.trim();
  const a = input.split(" ").map(Number);

  console.log(3*a[0]*a[0]);

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

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) {
	var inputSeparate = input.split(" ");
  	var N = inputSeparate[0];
  	var D = inputSeparate[1];
	var numOfPeople = Math.ceil(N/(D*2+1));
  	console.log(numOfPeople);

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

Score : 200 points

Problem Statement

There are N apple trees in a row. People say that one of them will bear golden apples.

We want to deploy some number of inspectors so that each of these trees will be inspected.

Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector deployed under the i-th tree (1 \leq i \leq N) will inspect the trees with numbers between i-D and i+D (inclusive).

Find the minimum number of inspectors that we need to deploy to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq D \leq 20

Input

Input is given from Standard Input in the following format:

N D

Output

Print the minimum number of inspectors that we need to deploy to achieve the objective.

Sample Input 1

6 2

Sample Output 1

2

We can achieve the objective by, for example, placing an inspector under Tree 3 and Tree 4.

Sample Input 2

14 3

Sample Output 2

2

Sample Input 3

20 4

Sample Output 3

3


"use strict";
const main = arg => {
  let N = arg.split(" ")[0]*1;
  let D = arg.split(" ")[1]*1 + 1;
  let count = 0;
  while(N >= 0){
  	N = N - 2*D;
    count++;
  }
  console.log(count);

}

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


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

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

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

reader.on('close', () => {
 var n = Number(lines[0]);
 var a = [];
 var count = 0;
 for(i=1; i<=n; i++){
   for(j=1; j<=n; j++){
     if(i === j){
       continue;
     }
     a.push(lines[j]);
   }
   // var max = array.sort((a, b)=> b - a)[0];
   console.log(Math.max(...a));
   a = [];
 }

});

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 N = input.split('\n');
  var A = input.split('\n');
  var As = input.split('\n');
  N = parseInt(N,10);
  A.shift();
  As.shift()
  for(i=0;i<N;i++){
    A[i] = parseInt(A[i],10);
    As[i] = parseInt(As[i],10);
  }
  As.sort((a,b)=>{
    return b - a;
  });

  var maxF = As[0];
  var maxS = As[1];

  A = A.map(x=>{
    if(x===maxF){
      return maxS;
    }else{
      return maxF;
    }
  });

  console.log(A.join('\n'));

}

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


function Main(input){
  input = input.split("\n");
  inputStr = input[0].split(" ");
  var N = Number.parseInt(inputStr[0]);
  var A = [];
  var fst = 2;
  var snd = 1;
  var now = 0;
  //パラメータを配列に確保しつつ最大値と２番目の値を変数に格納
  for( i=0 ; i<N ; i++ ){
    inputStr = input[i+1].split(" ");
    now = Number.parseInt(inputStr[0]);
    A.push(now);
    if( snd <= now ){
      snd = now;
    }
    if( fst <= now ){
      snd = fst;
      fst = now;
    }
  }
  //結果表示
  for( j = 0 ; j < N ; j++){
    if(A[j]===fst){
      console.log(snd);
    } else {
      console.log(fst);
    }
  }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input){
  const N=input.split('\n')[0]
  var nums = input.split('\n').map((n) => parseInt(n, 10));
  nums.shift();

  for(var i=0; i<N; i++){
    var temp=nums.concat();
    temp.splice(i,1);
    console.log(Math.max.apply(null, temp));
  }

}

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


function Main(input) {
  var n=parseInt(input.split("\n")[0]);
  for(var i=1;i<n;i++){
    var max=0;
    var tmp=input.split("\n");
    tmp[0]=0;
    tmp[i]=0;
    console.log(Math.max.apply(null,tmp));
}
  }

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


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

	var N = parseInt( inputs[0], 10 );

	var boxes = new Array( N );
	var inputArray = [];
	var inputCounter = 0;

	for ( var i = N; i > 0; i-- ) {
		var index = i - 1;
		var tmp = parseInt( inputs[i], 10 );

		var sum = 0;
		var counter = 2;
		while ( i * counter <= N) {
			sum += boxes[i * counter - 1];
			counter++;
		}

		if ( sum % 2 == tmp ) {
			boxes[index] = 0;
		} else {
			boxes[index] = 1;
			inputCounter++;
			inputArray.push(i);
		}

	}

	if ( inputCounter > 0 ){
		console.log('%d\n', inputCounter);

		var str = '';
		for ( var i = inputCounter - 1; i >= 0; i-- ) {
			str += inputArray[i];
			if ( i == 0 ) {
				str += '' + inputArray[i];
			} else {
				str += '' + inputArray[i];
				str += ' ';
			}
		}
		console.log(str);
	} else {
		console.log('%d', 0);
	}

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


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.


// inputに入力データ全体が入る
function Main(input) {
  var noList = input.split("\n")[1].split(" ");

  for(var i = 0; i < noList.length; i++){
    var mae = i - 1;
    if(mae == -1)mae = noList.length - 1;
    var ato = i + 1;
    if(ato == noList.length)ato = 0;

    if(noList[i] != (noList[mae] ^ noList[ato]).toString()){
       console.log("No");
       return;
    }
    if(noList.length % 2 == 0){
       console.log("No");
       return;
       }
  }
  console.log("Yes");
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";
(function(input){
  input=input.trim().split(/\s+/).map(x=>x-0);
  const N=input.shift();
  const A=(N%3===0),
        B=((input.reduce((a,c)=>a+c*c,0))===0);
  if((!A)&&(!B)){
    console.log("No");
    return;
  }
  const N=A;
})(require("fs").readFileSync("/dev/stdin","utf8"));


function Main(input) {

  input = input.split(" ");

  var N = parseInt(input[0],10);
  var A = parseInt(input[1],10);
  var B = parseInt(input[2],10);

  var D = A * N
  if ( D <= B ){
    console.log(D);
  }else {comsole.log(B)}

}

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


function Main(input) {
    N = input.split(' ')[0] * 1
    A = input.split(' ')[1] * 1
    B = input.split(' ')[2] * 1
    ans = A * N < B ? A * N : B
    console.log(ans)
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


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

	var valley = toIntAll(tmp);
	var sumValley=0;
	for(var i=0; i<valley.length; i++){
		sumValley += valley[i];
	}

	var tmpSum = 0;
	for(var i=1; i<valley.length; i+=2){
		tmpSum += valley[i];
	}
	tmpMountainZero = sumValley - (2*tmpSum);

	var tmpMountain = [];
	tmpMountain[0] = tmpMountainZero;
	for(var i=1; i<valley.length; i++){
		tmpMountain[i] = (valley[i-1] - (tmpMountain[i-1]/2)) * 2;
	}
	//出力
	console.log('%s', outputDelimiterSpace(tmpMountain));
}
function toIntAll(input){
  var out = []
  for(var i=0; i<input.length; i++){
    out[i] = parseInt(input[i]);
  }
  return out;
}
function outputDelimiterSpace(words){
  var out = words.join(' ');
  out += '\n';
  return out;
}

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

Score : 400 points

Problem Statement

There are N mountains in a circle, called Mountain 1, Mountain 2, ..., Mountain N in clockwise order. N is an odd number.

Between these mountains, there are N dams, called Dam 1, Dam 2, ..., Dam N. Dam i (1 \leq i \leq N) is located between Mountain i and i+1 (Mountain N+1 is Mountain 1).

When Mountain i (1 \leq i \leq N) receives 2x liters of rain, Dam i-1 and Dam i each accumulates x liters of water (Dam 0 is Dam N).

One day, each of the mountains received a non-negative even number of liters of rain.

As a result, Dam i (1 \leq i \leq N) accumulated a total of A_i liters of water.

Find the amount of rain each of the mountains received. We can prove that the solution is unique under the constraints of this problem.

Constraints

All values in input are integers.

3 \leq N \leq 10^5-1

N is an odd number.

0 \leq A_i \leq 10^9

The situation represented by input can occur when each of the mountains receives a non-negative even number of liters of rain.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print N integers representing the number of liters of rain Mountain 1, Mountain 2, ..., Mountain N received, in this order.

Sample Input 1

3
2 2 4

Sample Output 1

4 0 4

If we assume Mountain 1, 2, and 3 received 4, 0, and 4 liters of rain, respectively, it is consistent with this input, as follows:

Dam 1 should have accumulated \frac{4}{2} + \frac{0}{2} = 2 liters of water.

Dam 2 should have accumulated \frac{0}{2} + \frac{4}{2} = 2 liters of water.

Dam 3 should have accumulated \frac{4}{2} + \frac{4}{2} = 4 liters of water.

Sample Input 2

5
3 8 7 5 5

Sample Output 2

2 4 12 2 8

Sample Input 3

3
1000000000 1000000000 0

Sample Output 3

0 2000000000 0


function main(input){
  const arr=input.trim().split("");

  const hunya=arr.filter(function(a){
    return a !==arr[0];
  })
  const hunyahunya=hunya.filter(function(a){
    return a !== hunya[0];
  })
  if(hunyahunya.length==0 && hunya.length==2){
    console.log("Yes");
  }else{
    console.log("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


function Main(input) {
	var inputArr = input.split("");
    var ret = {};
    for (str of  inputArr) {
		ret[str] = ret[str] ? ret[str] + 1 : 1;
    }
    if (Object.keys(ret).length === 2 && ret[Object.keys(ret)[0]] === 2) {
        console.log('Yes');
    } else {
        console.log('No');
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";

const main = arg => {
  	let txtArr = arg.split("");
  	let ans = 'No';
	let NewArr = txtArr.sort();
  	if((NewArr[0] == NewArr[1]) && (NewArr[2] == NewArr[3]) && (NewArr[1] != NewArr[3])){
    	ans = 'Yes';
    }
  	console.log(ans);

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


'use strict'
const Main = (arg) => {
  let input = arg.trim().split('\n');
  let n = parseInt(input[0]);
  let pArr = input[1].split(' ').map(Number);
  // console.log({ n, pArr });
  let count = 0;
  for (let i = 1; i - 1 < n; i++) {
    if ((pArr[i - 1] < pArr[i] && pArr[i] < pArr[i + 1])
      || (pArr[i + 1] < pArr[i] && pArr[i] < pArr[i - 1])) {
      count += 1;
    }
  }
  console.log(count);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 200 points

Problem Statement

We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}.

Print the number of elements p_i (1 < i < n) that satisfy the following condition:

p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}.

Constraints

All values in input are integers.

3 \leq n \leq 20

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 the number of elements p_i (1 < i < n) that satisfy the condition.

Sample Input 1

5
1 3 5 4 2

Sample Output 1

2

p_2 = 3 is the second smallest number among p_1 = 1, p_2 = 3, and p_3 = 5. Also, p_4 = 4 is the second smallest number among p_3 = 5, p_4 = 4, and p_5 = 2. These two elements satisfy the condition.

Sample Input 2

9
9 6 3 2 5 8 7 4 1

Sample Output 2

5


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

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

reader.on('close', () => {

  var n = lines[1].split(' ')
  for (var k in n) n[k] = parseInt(n[k])

  var r = 0

  for (var i = 1; i < n.length - 1; i++) {
    var ary = [
      n[i - 1],
      n[i],
      n[i + 1]
    ].sort()
    var s = ary.filter(x => x === n[i])
    if (s.length > 1) continue
    if (ary[1] == n[i]) r++
  }

  console.log(r)

});


'use strict';
(function(input){
  input=input.trim().split(/\s+/).map(x=>x-0);
  const N=input[0],
        K=input[1],
        L=N-K+1,
        M=(1e9+7);
  function sum(a,b){
    return (a+b)%M;
  }
  function mult(a,b){
    let A=(a>>16),
        B=(b>>16),
        A_=a-(A<<16),
        B_=b-(B<<16),
        C=(((((A*B)%M)<<16)%M)<<16)%M,
        D=(((A*B_)%M)<<16)%M,
        E=(((A_*B)%M)<<16)%M,
        F=(A_*B_)%M,
        G=(C+D+E+F)%M;
    return G;
  }
  const combination=new Array(N+1).fill(0).map((zero,n)=>new Array(n+1).fill(1));
  for(let n=2;n<N+1;n++){
    for(let k=1;k<n;k++){
      combination[n][k]=sum(combination[n-1][k-1],combination[n-1][k]);
    }
  }
  const ans=[];
  for(let I=0;I<K;I++){
    let i=I+1;
    ans.push(mult(combination[L][i],combination[K-1][i-1]));
  }
  console.log(ans.join('\n'));
})(require('fs').readFileSync('/dev/stdin','utf8'));

Score : 400 points

Problem Statement

There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.

First, Snuke will arrange the N balls in a row from left to right.

Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible.

How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.

Constraints

1 \leq K \leq N \leq 2000

Input

Input is given from Standard Input in the following format:

N K

Output

Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7.

Sample Input 1

5 3

Sample Output 1

3
6
1

There are three ways to arrange the balls so that Takahashi will need exactly one move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B stands for red and blue, respectively).

There are six ways to arrange the balls so that Takahashi will need exactly two moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B), (B, R, B, B, R), and (B, R, R, B, B).

There is one way to arrange the balls so that Takahashi will need exactly three moves: (B, R, B, R, B).

Sample Input 2

2000 3

Sample Output 2

1998
3990006
327341989

Be sure to print the numbers of arrangements modulo 10^9+7.


'use strict'

function main(input){
  const s = input.split('').map(x => parseInt(s));

  if(s[0]==s[1] || s[1]==s[2] || s[2]==s[3]){
    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


// inputに入力データ全体が入る
function Main(input) {
  line = input.split(" ");
  var N = line[0];
  var L = +line[1];
  var array = [];
  var sum = 0;
  var min = 0;
  var includesZero = false;
  var lastIndexNegative = false;

  for(i=0; i<N; i++){
    array.push(L+i);
    sum += L+i
    if(L+i==0){
      min = 0;
      includesZero = true;
    }
    if(i+1 == N && L+i < 0){
      min = L+i;
      lastIndexNegative = true;
    }
  }

  if(includesZero == true){
  }else if(lastIndexNegative == true){
  }else{
    min = Math.min.apply(null, array);
  }

  console.log(sum-min);

}

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

Score : 200 points

Problem Statement

You have N apples, called Apple 1, Apple 2, Apple 3, ..., Apple N. The flavor of Apple i is L+i-1, which can be negative.

You can make an apple pie using one or more of the apples. The flavor of the apple pie will be the sum of the flavors of the apples used.

You planned to make an apple pie using all of the apples, but being hungry tempts you to eat one of them, which can no longer be used to make the apple pie.

You want to make an apple pie that is as similar as possible to the one that you planned to make. Thus, you will choose the apple to eat so that the flavor of the apple pie made of the remaining N-1 apples will have the smallest possible absolute difference from the flavor of the apple pie made of all the N apples.

Find the flavor of the apple pie made of the remaining N-1 apples when you choose the apple to eat as above.

We can prove that this value is uniquely determined.

Constraints

2 \leq N \leq 200

-100 \leq L \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N L

Output

Find the flavor of the apple pie made of the remaining N-1 apples when you optimally choose the apple to eat.

Sample Input 1

5 2

Sample Output 1

18

The flavors of Apple 1, 2, 3, 4, and 5 are 2, 3, 4, 5, and 6, respectively. The optimal choice is to eat Apple 1, so the answer is 3+4+5+6=18.

Sample Input 2

3 -1

Sample Output 2

0

The flavors of Apple 1, 2, and 3 are -1, 0, and 1, respectively. The optimal choice is to eat Apple 2, so the answer is (-1)+1=0.

Sample Input 3

30 -50

Sample Output 3

-1044


function main(input) {
  const lines = input.split('\n');
  lines.forEach(line => {
    if (line.length === 0) {
      return;
    }
    const vs = line.split(' ');
    console.log(flow(
      parseInt(vs[0], 10),
      parseInt(vs[1], 10),
      parseInt(vs[2], 10),
      parseInt(vs[3], 10)
    ));
  });
}

function flow(a, b, c, d) {
  return (b - a + 1) - count(a, b, c) - count(a, b, d) + count(a, b, c*d);
}

function count(min, max, devide) {
  const numberOfDevides = Math.floor(max / devide);
  var diff = Math.floor(min / devide);
  if (min % devide === 0) {
    diff--;
  }
  return numberOfDevides - diff;
}

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

Score : 300 points

Problem Statement

You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Constraints

1\leq A\leq B\leq 10^{18}

1\leq C,D\leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Sample Input 1

4 9 2 3

Sample Output 1

2

5 and 7 satisfy the condition.

Sample Input 2

10 40 6 8

Sample Output 2

23

Sample Input 3

314159265358979323 846264338327950288 419716939 937510582

Sample Output 3

532105071133627368


// 配列の重複を排除する
function uniq(array) {
  return Array.from(new Set(array));
}

function Main(input) {
  var A = parseInt(input[0], 10);
  var B = parseInt(input[1], 10);
  var C = parseInt(input[2], 10);
  var D = parseInt(input[3], 10);

  var cNum = A % C !== 0 ? Math.floor(A / C) + 1 : Math.floor(A / C);
  var dNum = A % D !== 0 ? Math.floor(A / D) + 1 : Math.floor(A / D);

  var baisuu = [];

  // A~Bの範囲のCの倍数を求める
  while (C * cNum <= B) {
    baisuu.push(C * cNum);
    cNum++;
  }
  // A~Bの範囲のCの倍数を求める
  while (D * dNum <= B) {
    baisuu.push(D * dNum);
    dNum++;
  }

  // console.log(JSON.stringify(baisuu));

  var uniqArray = uniq(baisuu);
  // console.log(JSON.stringify(uniqArray));

  console.log(B - A + 1 - uniqArray.length);

}

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


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  input.shift();
  var X = input.map(i => i.split(" ").map(i => parseInt(i)));
  X.splice(N,X.length-N);
  X.sort(function(a,b){
    if (a[1] < b[1]) return -1;
    if (a[1] > b[1]) return 1;
    return 0;
  });
  var ans = "Yes";
  var sum =0;
  for(var i=0;i<N;i++){
    sum+=X[i][0];
    if(sum>X[i][1]){
      ans="No";
      break;
    }
  }

  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: 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


//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");
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr("time : " + end + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException ‚There is no more input";}else{var returnInput = this.list[this.index++];return returnInput;}}
  };
  return returnObj;
}
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 one = nextIntArray();
  var N = one[0];
  var K = one[1];
  var maxK = (N - 1) * (N - 2) / 2;
  if(maxK < K){
    myout(-1);
    return;
  }
  var output = [N - 1];
  for(var i = 2; i <= N; i++){
    output.push("1 " + i);
  }
  var addK = maxK - K;
  var under = 2;
  while(addK > 0){
    for(var i = under + 1; i <= N; i++){
      output.push(under + " " + i);
      output[0]++;
      addK--;
      if(addK == 0){
        break;
      }
      under++;
    }
  }

  myout(myconv(output, 9));

}

Score: 500 points

Problem Statement

Does there exist an undirected graph with N vertices satisfying the following conditions?

The graph is simple and connected.

The vertices are numbered 1, 2, ..., N.

Let M be the number of edges in the graph. The edges are numbered 1, 2, ..., M, the length of each edge is 1, and Edge i connects Vertex u_i and Vertex v_i.

There are exactly K pairs of vertices (i,\ j)\ (i < j) such that the shortest distance between them is 2.

If there exists such a graph, construct an example.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq K \leq \frac{N(N - 1)}{2}

Input

Input is given from Standard Input in the following format:

N K

Output

If there does not exist an undirected graph with N vertices satisfying the conditions, print -1.

If there exists such a graph, print an example in the following format (refer to Problem Statement for what the symbols stand for):

M
u_1 v_1
:
u_M v_M

If there exist multiple graphs satisfying the conditions, any of them will be accepted.

Sample Input 1

5 3

Sample Output 1

5
4 3
1 2
3 1
4 5
2 3

This graph has three pairs of vertices such that the shortest distance between them is 2: (1,\ 4), (2,\ 4), and (3,\ 5). Thus, the condition is satisfied.

Sample Input 2

5 8

Sample Output 2

-1

There is no graph satisfying the conditions.


function main(input) {
  const args = input.split('\n');
  const [N, X] = args[0].split(' ');
  const L = args[1].split(' ');
  const n = Number(N);
  let count = 0;
  for (let i = 0; i < n + 1; i++) {
    if (X < count) {
      console.log(i)
      return;
    }
    count += Number(L[i]);
   }
  return;
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 200 points

Problem Statement

A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.

How many times will the ball make a bounce where the coordinate is at most X?

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 100

1 \leq X \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
L_1 L_2 ... L_{N-1} L_N

Output

Print the number of times the ball will make a bounce where the coordinate is at most X.

Sample Input 1

3 6
3 4 5

Sample Output 1

2

The ball will make a bounce at the coordinates 0, 3, 7 and 12, among which two are less than or equal to 6.

Sample Input 2

4 9
3 3 3 3

Sample Output 2

4

The ball will make a bounce at the coordinates 0, 3, 6, 9 and 12, among which four are less than or equal to 9.


function main(input) {
  const args = input.split('\n');
  const [N, X] = args[0].split(' ');
  const L = args[1].split(' ');
  const n = Number(N);
  let count = 0;
  for (let i = 0; i < n + 1; i++) {
    if (X <= count) {
      console.log(i)
      return;
    }
    count += Number(L[i]);
   }
  return;
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const main = (inputs) => {
  var W = inputs[0].split(" ")[0]-0;
  var H = inputs[0].split(" ")[1]-0;
  var x = inputs[0].split(" ")[2]-0;
  var y = inputs[0].split(" ")[3]-0;

  var ans = H*W/2;
  if(
    (x==0&&y==0)||(x==W&&y==0)||(x==0&&y==H)||(x==W&&y==H)
  ){
    console.log(ans+" 0");
  }else{
    console.log(ans+" 1");
  }
}

main(require('fs').readFileSync('/dev/stdin', 'UTF-8').trim().split("\n"));

Score : 300 points

Problem Statement

There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H).
You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the part whose area is not larger than that of the other. Additionally, determine if there are multiple ways to cut the rectangle and achieve that maximum.

Constraints

1 \leq W,H \leq 10^9

0\leq x\leq W

0\leq y\leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

W H x y

Output

Print the maximum possible area of the part whose area is not larger than that of the other, followed by 1 if there are multiple ways to cut the rectangle and achieve that maximum, and 0 otherwise.

The area printed will be judged correct when its absolute or relative error is at most 10^{-9}.

Sample Input 1

2 3 1 2

Sample Output 1

3.000000 0

The line x=1 gives the optimal cut, and no other line does.

Sample Input 2

2 2 1 1

Sample Output 2

2.000000 1


// inputに入力データ全体が入る
function Main(input) {
	var tmp = input.split(" ");
  var W = Number(tmp[0]);
  var H = Number(tmp[1]);
  var x = Number(tmp[2]);
  var y = Number(tmp[3]);

  var result = 0;

  var maxValue = 0;
  var maxCount = 0;

  if(x === W/2 && y === H/2) {
    maxValue = (W * H) / 2;
    maxCount = 1;
  }
  else if(x === W || y === H || x === W/2 || y === H/2){
    maxValue = (W * H) / 2;
  }
  else if( (x / y) === (W / H) || ((x/y) * x + y) === H ) {
    maxValue = (W * H) / 2;
  }
  else {
    maxCount = 1;
    var minSquireX = y/x * H;
    var minSquireY = x/y * W;
    var minSquire = 0;

    if(minSquireX < W){
      minSquire = (x - minSquireX) * (H -y);
    }
    else if(minSquireY < H){
      minSquire = (W - x) * (y - minSquireY);
    }

    var calc1 =  (W - x) * (H - y) / 2 + (x * y) + minSquire;

    var calc2 =  W * H - calc1;

    if(calc1 > calc2) {
      maxValue = calc1;
    }
    else {
      maxValue = calc2;
    }
  }
  result = (W * H) - maxValue;

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


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0].split(" ")[0]);
  var M = parseInt(input[0].split(" ")[1]);
  var S = input[1].split(" ").map(i => parseInt(i));
  var T = input[2].split(" ").map(i => parseInt(i));
  var mod = Math.pow(10,9)+7;
  var dp=new Array(N+1).fill(0);
  var sum=new Array(N+1).fill(0);
  for(var i=0;i<N+1;i++){
    var tmp=new Array(M+1).fill(0);
    dp[i]=tmp;
  }
  for(var i=0;i<N;i++){
    for(var j=0;j<M;j++){
      if(S[i]==T[j]){
        dp[i+1][j+1]=(dp[i][j+1]+dp[i+1][j]+1)%mod;
      }else{
        dp[i+1][j+1]=(dp[i][j+1]+dp[i+1][j]+(mod-dp[i][j]))%mod;
      }
    }
  }
  var ans=dp[N][M]+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 two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive).

In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content?

Here the subsequence of A is a sequence obtained by removing zero or more elements from A and concatenating the remaining elements without changing the order.

For both S and T, we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Since the answer can be tremendous, print the number modulo 10^9+7.

Constraints

1 \leq N, M \leq 2 \times 10^3

The length of S is N.

The length of T is M.

1 \leq S_i, T_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
S_1 S_2 ... S_{N-1} S_{N}
T_1 T_2 ... T_{M-1} T_{M}

Output

Print the number of pairs of a subsequence of S and a subsequence of T such that the subsequences are the same in content, modulo 10^9+7.

Sample Input 1

2 2
1 3
3 1

Sample Output 1

3

S has four subsequences: (), (1), (3), (1, 3).

T has four subsequences: (), (3), (1), (3, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 1 \times 1 pair of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (3), for a total of three pairs.

Sample Input 2

2 2
1 1
1 1

Sample Output 2

6

S has four subsequences: (), (1), (1), (1, 1).

T has four subsequences: (), (1), (1), (1, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 2 \times 2 pairs of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (1,1), for a total of six pairs.
Note again that we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Sample Input 3

4 4
3 4 5 6
3 4 5 6

Sample Output 3

16

Sample Input 4

10 9
9 6 5 7 5 9 8 5 6 7
8 6 8 5 5 7 9 9 7

Sample Output 4

191

Sample Input 5

20 20
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Sample Output 5

846527861

Be sure to print the number modulo 10^9+7.


"use strict"
function main(arg) {
    arg = arg.trim().split("\n")
    var N = Number(arg.shift())
    var data = arg.map((e1) => {
        return e1.split(" ").map(Number)
    })
    var pq = getPq(data)
    var p = pq[0]
    var q = pq[1]
    var tmp = []
    for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < data.length; j++) {
            if (i === j) continue
            var _p = data[i][0] - data[j][0]
            var _q = data[i][1] - data[j][1]
            if (p === _p && q === _q) {
                // console.log(i)
                tmp.push(i)
            }
        }
    }
    var b = tmp.filter(function (x, i, self) {
        return self.indexOf(x) === i;
    });
    console.log(data.length - b.length)
    // console.log(pq)
    return
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

function getPq(data) {
    var pq = []
    for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < data.length; j++) {
            if (i === j) continue
            var keyStr = [
                data[i][0] - data[j][0],
                data[i][1] - data[j][1]
            ].join(',')
            pq.push(keyStr)
            // console.log(keyStr)
        }
    }
    pq.sort()
    var pqcount = {}
    for (var i = 0; i < pq.length; i++) {
        var key = pq[i]
        if (pqcount[key] == null) {
            pqcount[key] = 0
        }
        pqcount[key] += 1
    }
    var result = ""
    var resultValue = 0
    for (var key in pqcount) {
        if (resultValue < pqcount[key]) {
            resultValue = pqcount[key]
            result = key
        }
    }
    // console.log(data.length - resultValue)
    return result.split(",").map(Number)
}

Score : 300 points

Problem Statement

There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i).

We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation:

Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates of this ball. If we collected a ball at coordinates (a - p, b - q) in the previous operation, the cost of this operation is 0. Otherwise, including when this is the first time to do this operation, the cost of this operation is 1.

Find the minimum total cost required to collect all the balls when we optimally choose p and q.

Constraints

1 \leq N \leq 50

|x_i|, |y_i| \leq 10^9

If i \neq j, x_i \neq x_j or y_i \neq y_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the minimum total cost required to collect all the balls.

Sample Input 1

2
1 1
2 2

Sample Output 1

1

If we choose p = 1, q = 1, we can collect all the balls at a cost of 1 by collecting them in the order (1, 1), (2, 2).

Sample Input 2

3
1 4
4 6
7 8

Sample Output 2

1

If we choose p = -3, q = -2, we can collect all the balls at a cost of 1 by collecting them in the order (7, 8), (4, 6), (1, 4).

Sample Input 3

4
1 1
1 2
2 1
2 2

Sample Output 3

2


function Main(input) {
  lines = input.split("\n")
  lines.pop()
  N = lines.shift() * 1
  if (N==1) {
    console.log(1)
    return
  }
  d = []
  for (i =0; i < N; i++) {
     l = lines[i].split(' ')
     d.push({ x: l[0], y: l[1]})
  }
  d = d.sort(function(a, b) {
    if (a.x == b.x) {
      return a.y - b.y
    }
    return a.x - b.x
  })
  a = {}
  for (i =0; i < N; i++) {
    for (j =0; j < N; j++) {
      if (i == j) continue
      x = d[i].x - d[j].x
      y = d[i].y - d[j].y
      k = x + ',' + y
      if (a[k]) {
        a[k] = a[k] + 1
      } else {
        a[k] = 1
      }
    }
  }
  arr = Object.keys(a)
  m = 0
  for (i=0; i< arr.length; i++) {
    if (m < a[arr[i]]) {
      m = a[arr[i]]
      k = arr[i]
    }
  }
  dx = k.split(',')[0]
  dy = k.split(',')[1]
  ans = 0
  while(d.length) {
     a = d.shift()
     for (i= 0; i < d.length; i++) {
       b = d[i]
       if (
         ((dx == 0 && b.x - a.x == 0) || (b.x - a.x) % dx == 0) &&
         ((dy == 0 && b.y - a.y == 0) || (b.y - a.y) % dy == 0)
       ) {
         d.splice(i, 1)
         i--
       }
     }
     ans++
  }
  console.log(ans)
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
    input = input.trim().split("\n");
    var N = parseInt(input[0], 10);
    var x = [];
    var y = [];
    for (var i = 0; i < N; i++){
        var tmp = input[i+1].split(" ");
        x[i] = parseInt(tmp[0], 10);
        y[i] = parseInt(tmp[1], 10);
    }

    var a = [];
    var k = 0;
    for (var i = 0; i < N-1; i++){
        for (var j = i+1; j < N; j++){
            a[k] = (y[j] - y[i]) / (x[j] - x[i]);
            k++;
        }
    }

    if (a.length == 0) {
        console.log(N);
    }
    else {
        var maxA = a[0];
        var maxCount = 0;
        for (var i = 0; i < a.length-1; i++) {
            var count = 0;
            for (var j = i+1; j < a.length; j++){
                if (a[i] == a[j]) {
                    count++;
                }
            }
            if (count > maxCount) {
                maxCount = count;
                maxA = a[i];
            }
        }

        var cost = [];
        for (var i = 0; i < N; i++){
            cost[i] = 1;
        }
        for (var i = 0; i < N - 1 ; i++){
            for (var j = i + 1; j < N; j++){
                if ((y[j] - y[i]) / (x[j] - x[i]) == maxA) {
                    cost[j] = 0;
                }
            }
        }

        var sumCost = 0;
        for (var i = 0; i < N; i++){
            sumCost += cost[i];
        }
        console.log(sumCost);
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict';

function main(stdin) {
  const input = stdin.split('\n')
  const N = input.shift();
  const pairs = input.map(c => c.split(' ').map(v => parseInt(v, 10)));
  const m = {'0,0': 1};

  for (let i = 0, l = pairs.length; i < l; ++i) {
    for (let j = i + 1; j < l; ++j) {
      const key = [pairs[j][0] - pairs[i][0], pairs[j][1] - pairs[i][1]].join(',');
      const c = m[key] || 0;
      m[key] = c + 1;
    }
  }

  const keys = Object.keys(m);
  const costs = [];

  keys.forEach((k, i) => costs[i] = m[k]);
  let max = -1;

  for (let i = 0, l = costs.length; i < l; ++i) {
    if (max < costs[i]) max = costs[i];
  }

  console.log(max);
}

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 a = o.l();
  a.sort((a,b)=>a-b);
  var ans = [-a[0]];
  for(var i = 1; i < n; i++){
    ans[0] += Math.abs(a[i]);
  }
  var s = a[0];
  for(var l = 1; l < n-1; l++){
    if(a[l] < 0)continue;
    var x = ans.length;
    if(x===1){
      ans.push(a[0]+" "+a[l]);
      s = a[0]-a[l];
    }else{
      ans.push(s+" "+a[l]);
      s -= a[l];
    }
  }
  ans.push(a[n-1]+" "+s);
  s = a[n-1]-s;
  for(var l = 1; ans.length !== n; l++){
    var x = ans.length;
    ans.push(s+" "+a[l]);
    s -= a[l];
  }
  return ans.join("\n")
}

Score : 500 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on a blackboard.

We will repeat the following operation N-1 times so that we have only one integer on the blackboard.

Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.

Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer.

Constraints

2 \leq N \leq 10^5

-10^4 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below.

Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively.

If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.

M
x_1 y_1
:
x_{N-1} y_{N-1}

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

If we choose x = -1 and y = 1 in the first operation, the set of integers written on the blackboard becomes (-2, 2).

Then, if we choose x = 2 and y = -2 in the second operation, the set of integers written on the blackboard becomes (4).

In this case, we have 4 as the final integer. We cannot end with a greater integer, so the answer is 4.

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0


function Main(input){
  A = input.split(' ').map(n => parseInt(n)).sort((a, b) => a - b);
  min = 200;
  for (i = 0; i < A.length; i++) {
    for (j = i + 1; j < A.length; j++) {
      sum = A[i] + A[j];
      if (sum < min) {
        min = sum;
      }
    }
  }
  console.log(min);
}

Main(require("fs").readFileSync("/dev/stdin","utf-8"));

Score : 100 points

Problem Statement

There are three airports A, B and C, and flights between each pair of airports in both directions.

A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.

Consider a route where we start at one of the airports, fly to another airport and then fly to the other airport.

What is the minimum possible sum of the flight times?

Constraints

1 \leq P,Q,R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

P Q R

Output

Print the minimum possible sum of the flight times.

Sample Input 1

1 3 4

Sample Output 1

4

The sum of the flight times in the route A \rightarrow B \rightarrow C: 1 + 3 = 4 hours

The sum of the flight times in the route A \rightarrow C \rightarrow C: 4 + 3 = 7 hours

The sum of the flight times in the route B \rightarrow A \rightarrow C: 1 + 4 = 5 hours

The sum of the flight times in the route B \rightarrow C \rightarrow A: 3 + 4 = 7 hours

The sum of the flight times in the route C \rightarrow A \rightarrow B: 4 + 1 = 5 hours

The sum of the flight times in the route C \rightarrow B \rightarrow A: 3 + 1 = 4 hours

The minimum of these is 4 hours.

Sample Input 2

3 2 3

Sample Output 2

5


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(){
  p = o.l();
  return p[0]+p[1]+p[2]-Math.max(...p);
}