function Main(input) {
  input = input.split("\n");
  var n = parseInt(input[0]);
  a = new Array(n).fill(0);
  b = new Array(n).fill(0);
  tmpa = input[1].split(" ");
  tmpb = input[2].split(" ");
  var suma=0;
  var sumb=0;
  var dif=0;
  var difp=0;
  var difm=0;

  for(i=0;i<n;i++){
    a[i]=parseInt(tmpa[i]);
    suma += a[i];
    b[i]=parseInt(tmpb[i]);
    sumb += b[i];
    dif+=Math.abs(a[i]-b[i]);
    difp+=Math.floor(Math.max(0,b[i]-a[i])/2);
    difm+=Math.max(0,a[i]-b[i]);
  }
  var ans ="No";
  if(difm<=difp){
    ans="Yes";
  }
  console.log('%s', ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

You are given two integer sequences of length N: a_1,a_2,..,a_N and b_1,b_2,..,b_N.
Determine if we can repeat the following operation zero or more times so that the sequences a and b become equal.

Operation: Choose two integers i and j (possibly the same) between 1 and N (inclusive), then perform the following two actions simultaneously:

Add 2 to a_i.

Add 1 to b_j.

Constraints

1 ≤ N ≤ 10 000

0 ≤ a_i,b_i ≤ 10^9 (1 ≤ i ≤ N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 .. a_N
b_1 b_2 .. b_N

Output

If we can repeat the operation zero or more times so that the sequences a and b become equal, print Yes; otherwise, print No.

Sample Input 1

3
1 2 3
5 2 2

Sample Output 1

Yes

For example, we can perform three operations as follows to do our job:

First operation: i=1 and j=2. Now we have a = \{3,2,3\}, b = \{5,3,2\}.

Second operation: i=1 and j=2. Now we have a = \{5,2,3\}, b = \{5,4,2\}.

Third operation: i=2 and j=3. Now we have a = \{5,4,3\}, b = \{5,4,3\}.

Sample Input 2

5
3 1 4 1 5
2 7 1 8 2

Sample Output 2

No

Sample Input 3

5
2 7 1 8 2
3 1 4 1 5

Sample Output 3

No


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

  var count=0;
  for(var i=0;i<=input[0];i++){
    for(var j=0;j<=input[1];j++){
      if(((input[3]-(500*i+100*j))%50==0)&&((input[3]-(500*i+100*j))/50<=input[2])&&(input[3]-(500*i+100*j)>=0)){
        count++;
      }
    }
  }
}

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

console.log(count);

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

Score : 100 points

Problem Statement

You went shopping to buy cakes and donuts with X yen (the currency of Japan).

First, you bought one cake for A yen at a cake shop.
Then, you bought as many donuts as possible for B yen each, at a donut shop.

How much do you have left after shopping?

Constraints

1 \leq A, B \leq 1 000

A + B \leq X \leq 10 000

X, A and B are integers.

Input

Input is given from Standard Input in the following format:

X
A
B

Output

Print the amount you have left after shopping.

Sample Input 1

1234
150
100

Sample Output 1

84

You have 1234 - 150 = 1084 yen left after buying a cake.
With this amount, you can buy 10 donuts, after which you have 84 yen left.

Sample Input 2

1000
108
108

Sample Output 2

28

Sample Input 3

579
123
456

Sample Output 3

0

Sample Input 4

7477
549
593

Sample Output 4

405

Submitted source-code file size, in bytes.

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

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


function Main(input){
	var xs = input.trim().split('\n').map(v=>parseInt(v,10));
    var ans = (xs[0] - xs[1]) % xs[2]
    console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin","utf8"));


function Main(input) {

    const lines = input.split('\n');
    let x = parseInt(lines[0], 10);
    const a = parseInt(lines[1], 10);
    const b = parseInt(lines[2], 10);

    x = x - a;
    x = x - b * Math.floor(x / b);

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


const readline = require("readline");

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

reader.on("line", function (line) {
    lines.push(line);
});

reader.on("close", function () {
    lines[0] -= lines[1];
    lines[0] %= lines[2];
    console.log(lines[0])
});


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	cnt = input[0]-0;
	var t = [0];
	var x = [0];
	var y = [0];
	//文字列から10進数に変換するときはparseIntを使います
	var ret = "Yes";
	for (i=1; i<=cnt; i++)
	{
		tmp = input[i].split(" ");
		t.push(tmp[0]-0);
		x.push(tmp[1]-0);
		y.push(tmp[2]-0);
		if ( Math.abs(t[i-1]-t[i]) < Math.abs(x[i-1]-x[i]) + Math.abs(y[i-1]-y[i]) )
		{
			ret = "No";
			break;
		}
		if ( (Math.abs(t[i-1]-t[i]) - (Math.abs(x[i-1]-x[i]) + Math.abs(y[i-1]-y[i]))) % 2 != 0 )
		{
			ret = "No";
			break;
		}
	}
	//出力
	console.log('%s',ret);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

AtCoDeer the deer is going on a trip in a two-dimensional plane.
In his plan, he will depart from point (0, 0) at time 0, then for each i between 1 and N (inclusive), he will visit point (x_i,y_i) at time t_i.

If AtCoDeer is at point (x, y) at time t, he can be at one of the following points at time t+1: (x+1,y), (x-1,y), (x,y+1) and (x,y-1).
Note that he cannot stay at his place.
Determine whether he can carry out his plan.

Constraints

1 ≤ N ≤ 10^5

0 ≤ x_i ≤ 10^5

0 ≤ y_i ≤ 10^5

1 ≤ t_i ≤ 10^5

t_i < t_{i+1} (1 ≤ i ≤ N-1)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
t_1 x_1 y_1
t_2 x_2 y_2
:
t_N x_N y_N

Output

If AtCoDeer can carry out his plan, print Yes; if he cannot, print No.

Sample Input 1

2
3 1 2
6 1 1

Sample Output 1

Yes

For example, he can travel as follows: (0,0), (0,1), (1,1), (1,2), (1,1), (1,0), then (1,1).

Sample Input 2

1
2 100 100

Sample Output 2

No

It is impossible to be at (100,100) two seconds after being at (0,0).

Sample Input 3

2
5 1 1
100 1 1

Sample Output 3

No


function Main(input){
	input = input.split("\n");
	input.shift();
	for(var i=0;i<input.length;i++){
	    input[i] = input[i].split(" ").map(Number);
	}
	var flag = true;
	for(var i=1;i<input.length;i++){
	    if((Math.abs(input[i-1][1]-input[i][1])+Math.abs(input[i-1][2]-input[i][2]))%2!=(input[i][0]-input[i-1][0])%2||(Math.abs(input[i-1][1]-input[i][1])+Math.abs(input[i-1][2]-input[i][2]))>(input[i][0]-input[i-1][0])){
	      //  console.log((Math.abs(input[i-1][1]-input[i][1])+Math.abs(input[i-1][2]-input[i][2])),(input[i]-input[i-1]))
	        flag = false;
	    }
	}
	console.log(flag?"Yes":"No")
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


// ABC 086

// inputに入力データ全体が入る
function Main(input) {
  var arr = input.split("\n");
  var x = 0;
  var y = 0;
  var result = "Yes";
  var before_tmp = 0;
  for(var i=1;i<arr.length;i++) {
    var tmp = arr[i].split(" ");
    var N = parseInt(tmp[0],10); //最初から何秒目
    var x_range = check(x,parseInt(tmp[1],10)); //現在地から行く地点までの差 x
    var y_range = check(y,parseInt(tmp[2],10)); //現在地から行く地点までの差 y
    N -= before_tmp; //今回移動する秒数

    // 時間は余っているが、到着地点に達した場合
    if(x_range+y_range < N) {

      // 残り時間を持て余せない場合はNo
      if(parseInt(N,10)-parseInt(x_range+y_range,10) % 2 != 0) {
        result = "No";
      }

      // 時間が足りない場合
    } else if(x_range+y_range > N) {
      result = "No";
    }

    x = tmp[1];
    y = tmp[2];
    before_tmp = N;
  }
  console.log(result);
}

function check(before,after) {

  // プラス方向に進んだ場合
  if(before < after) {
    return after - before;
  } else {
    return before - after;
  }
};

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


"use strict";

function main(input) {
  input = input.split(/\n/).slice(1);
  input = input.map(v => v.split(/\s/).map(v => ~~v));

  let ans = "Yes"; // 'Yes' or 'No'
  let distance = 0;
  let time = 0;
  let nextPosi = { x: 0, y: 0 };
  let nextTime = 0;
  let tmpPosi = { x: 0, y: 0 };
  let tmpTime = 0;

  for (let i = 0; i < input.length; i++) {
    nextPosi.x = input[i][1];
    nextPosi.y = input[i][2];

    distance = Math.abs(nextPosi.x - tmpPosi.x + nextPosi.y - tmpPosi.y);

    nextTime = input[i][0];
    time = nextTime - tmpTime;
    if (distance > time || time % 2 != distance % 2) {
      ans = "No";
      break;
    }

    tmpTime = nextTime;
    tmpPosi.x = nextPosi.x;
    tmpPosi.y = nextPosi.y;
  }

  console.log(ans);
}

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


"use strict";

function main(input) {
  input = input
    .split(/\n/)
    .slice(1)
    .map(v => v.split(/\s/).map(v => ~~v)); //

  let ans = "Yes"; // 'Yes' or 'No'
  let distance = 0; // distance
  let time = 0; // time
  let nextPosi = { x: 0, y: 0 };
  let nextTime = 0;
  let tmpPosi = { x: 0, y: 0 };
  let tmpTime = 0;

  for (let i = 0; i < input.length; i++) {
    nextPosi.x = input[i][1];
    nextPosi.y = input[i][2];

    distance = nextPosi.x - tmpPosi.x + nextPosi.y - tmpPosi.y;

    nextTime = input[i][0];
    time = nextTime - tmpTime;
    console.log(time % 2, distance % 2);
    if (distance > time) {
      // || time % 2 != distance % 2

      ans = "No";
      break;
    }

    tmpTime = nextTime;
    tmpPosi.x = nextPosi.x;
    tmpPosi.y = nextPosi.y;
  }

  console.log(ans);
}

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


// inputに入力データ全体が入る
function Main(input) {
	var args = input.split("\n");
	var N = parseInt(args,10);
	var history = args.slice(1,N+1);
	var answer;
	var flg = 1;
	for(var i=0;i<N-1;i++){
		var rec1 = parser(history[i]);
		var rec2 = parser(history[i+1]);
		var dt = rec2[0] - rec1[0];
		var dist = Math.abs(rec2[1]+rec2[2]-rec1[1]-rec1[2]);
		if (dt >= dist && dt % 2 === dist % 2){
		}else{
				flg = 0;
		}
	}
	answer = flg ? "Yes" : "No" ;
	//出力
	console.log(answer);
}
function parser(record){
	var args = record.split(" ");
	var return_val=[];
	return_val.push(parseInt(args[0],10));
	return_val.push(parseInt(args[1],10));
	return_val.push(parseInt(args[2],10));
	return return_val
}

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


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

Score : 500 points

Problem Statement

An adult game master and N children are playing a game on an ice rink.
The game consists of K rounds.
In the i-th round, the game master announces:

Form groups consisting of A_i children each!

Then the children who are still in the game form as many groups of A_i children as possible.
One child may belong to at most one group.
Those who are left without a group leave the game. The others proceed to the next round.
Note that it's possible that nobody leaves the game in some round.

In the end, after the K-th round, there are exactly two children left, and they are declared the winners.

You have heard the values of A_1, A_2, ..., A_K. You don't know N, but you want to estimate it.

Find the smallest and the largest possible number of children in the game before the start, or determine that no valid values of N exist.

Constraints

1 \leq K \leq 10^5

2 \leq A_i \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

K
A_1 A_2 ... A_K

Output

Print two integers representing the smallest and the largest possible value of N, respectively,
or a single integer -1 if the described situation is impossible.

Sample Input 1

4
3 4 3 2

Sample Output 1

6 8

For example, if the game starts with 6 children, then it proceeds as follows:

In the first round, 6 children form 2 groups of 3 children, and nobody leaves the game.

In the second round, 6 children form 1 group of 4 children, and 2 children leave the game.

In the third round, 4 children form 1 group of 3 children, and 1 child leaves the game.

In the fourth round, 3 children form 1 group of 2 children, and 1 child leaves the game.

The last 2 children are declared the winners.

Sample Input 2

5
3 4 100 3 2

Sample Output 2

-1

This situation is impossible.
In particular, if the game starts with less than 100 children, everyone leaves after the third round.

Sample Input 3

10
2 2 2 2 2 2 2 2 2 2

Sample Output 3

2 3


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

console.log(main());
function main(){
  var k = o.a() - 1;
  var a = o.l();
  if(a[k--] !== 2)return -1;
  var u = 3, d = 2;
  for(; k >= 0; k--){
    if(a[k] > u)return -1;
    d = a[k] * Math.ceil(d / a[k]);
    u = Math.max((a[k] * Math.ceil(u / a[k])), d + a[k]) - 1;
  }
  return d + " " + u;
}


// https://atcoder.jp/contests/abc085/tasks/abc085_a
"use strict"
function Main(input) {
  const date = input.split(`\n`)[0].replace(/^.{4}/, 2018 );
  console.log(date);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

On some day in January 2018, Takaki is writing a document. The document has a column where the current date is written in yyyy/mm/dd format. For example, January 23, 2018 should be written as 2018/01/23.

After finishing the document, she noticed that she had mistakenly wrote 2017 at the beginning of the date column. Write a program that, when the string that Takaki wrote in the date column, S, is given as input, modifies the first four characters in S to 2018 and prints it.

Constraints

S is a string of length 10.

The first eight characters in S are 2017/01/.

The last two characters in S are digits and represent an integer between 1 and 31 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

Replace the first four characters in S with 2018 and print it.

Sample Input 1

2017/01/07

Sample Output 1

2018/01/07

Sample Input 2

2017/01/31

Sample Output 2

2018/01/31


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

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

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

rl.on('close', function () {
    var S = lines[0];
    S = S.replace("2017", "2018");
    console.log(S);
});


'use strict'

function main(input) {

    input = input.split('/')
    console.log('2018' + '/' + input[1] + '/' + input[2])

}

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


let rl = require('readline');

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

reader.on('line', function (line) {
    console.log(line.replace(/^2017/, "2018"));
});


// inputに入力データ全体が入る
function Main(input) {
	var a = input.split('')
	a[3] = "8"
	console.log(a.join(''))
}

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


"use strict";

var input = require("fs").readFileSync("/dev/stdin", "utf8");
var cin = input.split(/ |\n/),
    cid = 0;

function next() {
    return +cin[cid++];
} // number一個取得
function nextstr() {
    return cin[cid++];
} // 文字列一個取得
function nextbig() {
    return BigInt(cin[cid++]);
} // BigInteger一個取得
// 長さnの配列として取得。aは文字列フラグ
function nexts(n, a) {
    return a ? cin.slice(cid, cid += n) : cin.slice(cid, cid += n).map(a => +a);
}
// 長さnのBigInt配列として取得。
function nextsbig(n) {
    return cin.slice(cid, cid += n).map(a => BigInt(a));
}
// w個ずつを組にして長さhの配列。aは文字列フラグ。
function nextm(h, w, a) {
    var r = [],
        i = 0;
    if (a)
        for (; i < h; i++) r.push(cin.slice(cid, cid += w));
    else
        for (; i < h; i++) r.push(cin.slice(cid, cid += w).map(a => +a));
    return r;
}
// 多次元配列。v,a1,a2,a3 なら、3次元。[[値vで長さa3の配列]をa2個並べた配列]をa1個並べた配列。
function xArray(v) {
    var a = arguments,
        l = a.length,
        r = "Array(a[" + --l + "]).fill().map(x=>{return " + v + ";})";
    while (--l) r = "Array(a[" + l + "]).fill().map(x=>" + r + ")";
    return eval(r);
}

console.log(main().toString());

function main() {
    let n = next(); //("00000" + nexts()).substr(-5).split("").map(x => +x);
    let a = new Set(nexts(n))
    let ans = a.size

    return ans;
}

Score : 200 points

Problem Statement

An X-layered kagami mochi (X ≥ 1) is a pile of X round mochi (rice cake) stacked vertically where each mochi (except the bottom one) has a smaller diameter than that of the mochi directly below it. For example, if you stack three mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, you have a 3-layered kagami mochi; if you put just one mochi, you have a 1-layered kagami mochi.

Lunlun the dachshund has N round mochi, and the diameter of the i-th mochi is d_i centimeters. When we make a kagami mochi using some or all of them, at most how many layers can our kagami mochi have?

Constraints

1 ≤ N ≤ 100

1 ≤ d_i ≤ 100

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
d_1
:
d_N

Output

Print the maximum number of layers in a kagami mochi that can be made.

Sample Input 1

4
10
8
8
6

Sample Output 1

3

If we stack the mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, we have a 3-layered kagami mochi, which is the maximum number of layers.

Sample Input 2

3
15
15
15

Sample Output 2

1

When all the mochi have the same diameter, we can only have a 1-layered kagami mochi.

Sample Input 3

7
50
30
50
100
50
80
30

Sample Output 3

4


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);
});
var sub_fn = (ary)=>{

}
reader.on('close', () => {
  lines.shift()
  var x = (lines.map((a)=>{return 1*a})).sort(function(a,b){
        if( a < b ) return -1;
        if( a > b ) return 1;
        return 0;
});
 //console.log(x)
  var cnt = 1;
  for(var i in x){
    if(i >0 && x[i-1]<x[i]){
    ++cnt}
  }

  console.log(cnt)
});


function Main(input) {
  input = input.split("\n");
  input.shift();
  x = input.filter((d,i,n)=>n.indexOf(d)==i);
  console.log(x.length);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const BKRT = "\n";
const SPAC = " ";
const NOSP = "";

function Main(input){
	input = [].concat(...input.split(BKRT).map(a=>a.split(SPAC)));
  const strShift = ()=>input.shift();
  const intShift = ()=>~~input.shift();

  var N = intShift();

  var d = Array.from({length:200},()=>false);

  for(var i = 0; i < N ; i++){
  	d[intShift()]=true;
  }

  return ~~(d.filter(a=>a).length);
}

// If you are interested in the algorithms I used,
// there is no need to read down from this line.

((b,c,d)=>"undefined"!=typeof require?console.log(Main(require("fs").readFileSync("/dev/stdin","utf8"))):[b=b.split("\n").slice(1,-1).join("\n"),c=function(){try{return Main(b)}catch(f){return f.stack||f.message}}(),d=typeof c,"string"==d||(c=JSON.stringify(c)),$("<form>").append([[10,b],0,[1,d],0,[10,c]].map(f=>$(f?"<textarea>":"<br>",f&&{rows:f[0],cols:40,text:f[1]}))).appendTo("body")])(`
7
50
30
50
100
50
80
30
`);


function main(input) {
    const args = input.split('\n');
    const N = args[0],
	  nums = args.slice(1,args.length - 1);

    console.log(nums.filter((n,i => nums.indexOf(n) === i).length);
}

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


function Main(input) {
    var input = input.split('\n').map(n => parseInt(n, 10));
    var n = input[0];
    var a = input.slice(1,input.length).sort((a, b) => {
        return (a < b ? -1 : 1);
    });
    var count = 1;
    for (i = 0; i < a.length; i++) {
        if (a[i] < a[i+1]) {
            count++
        }
    }
console.log(count);

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


"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}

var myOut = main();
if(myOut !== undefined)console.log(myOut);

function main(){
  var n = next();
  var ans = xArray(0,n);
  var c = nextm(n-1,3);
  for(var i = 0; i < n-1; i++){
    for(var j = 0; j <= i; j++){
      if(ans[j] < c[i][1])ans[j] = c[i][1];
      ans[j] = Math.ceil(ans[j] / c[i][2]) * c[i][2] + c[i][0];
    }
  }
  return ans.join("\n");
}

Score : 300 points

Problem Statement

A railroad running from west to east in Atcoder Kingdom is now complete.

There are N stations on the railroad, numbered 1 through N from west to east.

Tomorrow, the opening ceremony of the railroad will take place.

On this railroad, for each integer i such that 1≤i≤N-1, there will be trains that run from Station i to Station i+1 in C_i seconds. No other trains will be operated.

The first train from Station i to Station i+1 will depart Station i S_i seconds after the ceremony begins. Thereafter, there will be a train that departs Station i every F_i seconds.

Here, it is guaranteed that F_i divides S_i.

That is, for each Time t satisfying S_i≤t and t％F_i=0, there will be a train that departs Station i t seconds after the ceremony begins and arrives at Station i+1 t+C_i seconds after the ceremony begins, where A％B denotes A modulo B, and there will be no other trains.

For each i, find the earliest possible time we can reach Station N if we are at Station i when the ceremony begins, ignoring the time needed to change trains.

Constraints

1≤N≤500

1≤C_i≤100

1≤S_i≤10^5

1≤F_i≤10

S_i％F_i=0

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
C_1 S_1 F_1
:
C_{N-1} S_{N-1} F_{N-1}

Output

Print N lines. Assuming that we are at Station i (1≤i≤N) when the ceremony begins, if the earliest possible time we can reach Station N is x seconds after the ceremony begins, the i-th line should contain x.

Sample Input 1

3
6 5 1
1 10 1

Sample Output 1

12
11
0

We will travel from Station 1 as follows:

5 seconds after the beginning: take the train to Station 2.

11 seconds: arrive at Station 2.

11 seconds: take the train to Station 3.

12 seconds: arrive at Station 3.

We will travel from Station 2 as follows:

10 seconds: take the train to Station 3.

11 seconds: arrive at Station 3.

Note that we should print 0 for Station 3.

Sample Input 2

4
12 24 6
52 16 4
99 2 2

Sample Output 2

187
167
101
0

Sample Input 3

4
12 13 1
44 17 17
66 4096 64

Sample Output 3

4162
4162
4162
0


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

    var inp = input.split(" ");
    var a = parseInt(inp[0]);
    var b = parseInt(inp[1]);
    var c = parseInt(inp[2]);
    var d = parseInt(inp[3]);

    var L = a + b;
    var R = c + d;
    if ( L === R ) {
      console.log('%s', 'Balanced');
    } else if ( L > R ) {
      console.log('%s', 'Left');
    } else if ( L < R ) {
      console.log('%s', 'Right');
    }

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

Score : 100 points

Problem Statement

A balance scale tips to the left if L>R, where L is the total weight of the masses on the left pan and R is the total weight of the masses on the right pan. Similarly, it balances if L=R, and tips to the right if L<R.

Takahashi placed a mass of weight A and a mass of weight B on the left pan of a balance scale, and placed a mass of weight C and a mass of weight D on the right pan.

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Constraints

1\leq A,B,C,D \leq 10

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Sample Input 1

3 8 7 1

Sample Output 1

Left

The total weight of the masses on the left pan is 11, and the total weight of the masses on the right pan is 8. Since 11>8, we should print Left.

Sample Input 2

3 4 5 2

Sample Output 2

Balanced

The total weight of the masses on the left pan is 7, and the total weight of the masses on the right pan is 7. Since 7=7, we should print Balanced.

Sample Input 3

1 7 6 4

Sample Output 3

Right

The total weight of the masses on the left pan is 8, and the total weight of the masses on the right pan is 10. Since 8<10, we should print Right.


module.exports=function(t){var e={};function r(o){if(e[o])return e[o].exports;var n=e[o]={i:o,l:!1,exports:{}};return t[o].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=t,r.c=e,r.d=function(t,e,o){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:o})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var o=Object.create(null);if(r.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var n in t)r.d(o,n,function(e){return t[e]}.bind(null,n));return o},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=0)}([function(t,e,r){r(1)(r(4).readFileSync("/dev/stdin","UTF-8"))},function(t,e,r){var o=r(2);t.exports=function(t){for(var e=t.split("\n")[0].split(" "),r=o(e[0]),n=o(e[1]),i=0;n.greaterOrEquals(r);)r=r.multiply(2),i+=1;console.log(i)}},function(t,e,r){(function(t){var r,o=function(t){"use strict";var e=1e7,r=7,n=9007199254740992,i=y(n),u="0123456789abcdefghijklmnopqrstuvwxyz",p="function"==typeof BigInt;function a(t,e,r,o){return void 0===t?a[0]:void 0!==e&&(10!=+e||r)?F(t,e,r,o):Q(t)}function s(t,e){this.value=t,this.sign=e,this.isSmall=!1}function l(t){this.value=t,this.sign=t<0,this.isSmall=!0}function f(t){this.value=t}function v(t){return-n<t&&t<n}function y(t){return t<1e7?[t]:t<1e14?[t%1e7,Math.floor(t/1e7)]:[t%1e7,Math.floor(t/1e7)%1e7,Math.floor(t/1e14)]}function h(t){c(t);var r=t.length;if(r<4&&x(t,i)<0)switch(r){case 0:return 0;case 1:return t[0];case 2:return t[0]+t[1]*e;default:return t[0]+(t[1]+t[2]*e)*e}return t}function c(t){for(var e=t.length;0===t[--e];);t.length=e+1}function g(t){for(var e=new Array(t),r=-1;++r<t;)e[r]=0;return e}function m(t){return t>0?Math.floor(t):Math.ceil(t)}function d(t,r){var o,n,i=t.length,u=r.length,p=new Array(i),a=0,s=e;for(n=0;n<u;n++)a=(o=t[n]+r[n]+a)>=s?1:0,p[n]=o-a*s;for(;n<i;)a=(o=t[n]+a)===s?1:0,p[n++]=o-a*s;return a>0&&p.push(a),p}function b(t,e){return t.length>=e.length?d(t,e):d(e,t)}function w(t,r){var o,n,i=t.length,u=new Array(i),p=e;for(n=0;n<i;n++)o=t[n]-p+r,r=Math.floor(o/p),u[n]=o-r*p,r+=1;for(;r>0;)u[n++]=r%p,r=Math.floor(r/p);return u}function S(t,r){var o,n,i=t.length,u=r.length,p=new Array(i),a=0,s=e;for(o=0;o<u;o++)(n=t[o]-a-r[o])<0?(n+=s,a=1):a=0,p[o]=n;for(o=u;o<i;o++){if(!((n=t[o]-a)<0)){p[o++]=n;break}n+=s,p[o]=n}for(;o<i;o++)p[o]=t[o];return c(p),p}function q(t,r,o){var n,i,u=t.length,p=new Array(u),a=-r,f=e;for(n=0;n<u;n++)i=t[n]+a,a=Math.floor(i/f),i%=f,p[n]=i<0?i+f:i;return"number"==typeof(p=h(p))?(o&&(p=-p),new l(p)):new s(p,o)}function M(t,r){var o,n,i,u,p=t.length,a=r.length,s=g(p+a),l=e;for(i=0;i<p;++i){u=t[i];for(var f=0;f<a;++f)o=u*r[f]+s[i+f],n=Math.floor(o/l),s[i+f]=o-n*l,s[i+f+1]+=n}return c(s),s}function N(t,r){var o,n,i=t.length,u=new Array(i),p=e,a=0;for(n=0;n<i;n++)o=t[n]*r+a,a=Math.floor(o/p),u[n]=o-a*p;for(;a>0;)u[n++]=a%p,a=Math.floor(a/p);return u}function E(t,e){for(var r=[];e-- >0;)r.push(0);return r.concat(t)}function O(t,r,o){return new s(t<e?N(r,t):M(r,y(t)),o)}function P(t){var r,o,n,i,u=t.length,p=g(u+u),a=e;for(n=0;n<u;n++){o=0-(i=t[n])*i;for(var s=n;s<u;s++)r=i*t[s]*2+p[n+s]+o,o=Math.floor(r/a),p[n+s]=r-o*a;p[n+u]=o}return c(p),p}function I(t,r){var o,n,i,u,p=t.length,a=g(p),s=e;for(i=0,o=p-1;o>=0;--o)i=(u=i*s+t[o])-(n=m(u/r))*r,a[o]=0|n;return[a,0|i]}function B(t,r){var o,n=Q(r);if(p)return[new f(t.value/n.value),new f(t.value%n.value)];var i,u=t.value,v=n.value;if(0===v)throw new Error("Cannot divide by zero");if(t.isSmall)return n.isSmall?[new l(m(u/v)),new l(u%v)]:[a[0],t];if(n.isSmall){if(1===v)return[t,a[0]];if(-1==v)return[t.negate(),a[0]];var d=Math.abs(v);if(d<e){i=h((o=I(u,d))[0]);var b=o[1];return t.sign&&(b=-b),"number"==typeof i?(t.sign!==n.sign&&(i=-i),[new l(i),new l(b)]):[new s(i,t.sign!==n.sign),new l(b)]}v=y(d)}var w=x(u,v);if(-1===w)return[a[0],t];if(0===w)return[a[t.sign===n.sign?1:-1],a[0]];i=(o=u.length+v.length<=200?function(t,r){var o,n,i,u,p,a,s,l=t.length,f=r.length,v=e,y=g(r.length),c=r[f-1],m=Math.ceil(v/(2*c)),d=N(t,m),b=N(r,m);for(d.length<=l&&d.push(0),b.push(0),c=b[f-1],n=l-f;n>=0;n--){for(o=v-1,d[n+f]!==c&&(o=Math.floor((d[n+f]*v+d[n+f-1])/c)),i=0,u=0,a=b.length,p=0;p<a;p++)i+=o*b[p],s=Math.floor(i/v),u+=d[n+p]-(i-s*v),i=s,u<0?(d[n+p]=u+v,u=-1):(d[n+p]=u,u=0);for(;0!==u;){for(o-=1,i=0,p=0;p<a;p++)(i+=d[n+p]-v+b[p])<0?(d[n+p]=i+v,i=0):(d[n+p]=i,i=1);u+=i}y[n]=o}return d=I(d,m)[0],[h(y),h(d)]}(u,v):function(t,r){for(var o,n,i,u,p,a=t.length,s=r.length,l=[],f=[],v=e;a;)if(f.unshift(t[--a]),c(f),x(f,r)<0)l.push(0);else{i=f[(n=f.length)-1]*v+f[n-2],u=r[s-1]*v+r[s-2],n>s&&(i=(i+1)*v),o=Math.ceil(i/u);do{if(x(p=N(r,o),f)<=0)break;o--}while(o);l.push(o),f=S(f,p)}return l.reverse(),[h(l),h(f)]}(u,v))[0];var q=t.sign!==n.sign,M=o[1],E=t.sign;return"number"==typeof i?(q&&(i=-i),i=new l(i)):i=new s(i,q),"number"==typeof M?(E&&(M=-M),M=new l(M)):M=new s(M,E),[i,M]}function x(t,e){if(t.length!==e.length)return t.length>e.length?1:-1;for(var r=t.length-1;r>=0;r--)if(t[r]!==e[r])return t[r]>e[r]?1:-1;return 0}function A(t){var e=t.abs();return!e.isUnit()&&(!!(e.equals(2)||e.equals(3)||e.equals(5))||!(e.isEven()||e.isDivisibleBy(3)||e.isDivisibleBy(5))&&(!!e.lesser(49)||void 0))}function Z(t,e){for(var r,n,i,u=t.prev(),p=u,a=0;p.isEven();)p=p.divide(2),a++;t:for(n=0;n<e.length;n++)if(!t.lesser(e[n])&&!(i=o(e[n]).modPow(p,t)).isUnit()&&!i.equals(u)){for(r=a-1;0!=r;r--){if((i=i.square().mod(t)).isUnit())return!1;if(i.equals(u))continue t}return!1}return!0}s.prototype=Object.create(a.prototype),l.prototype=Object.create(a.prototype),f.prototype=Object.create(a.prototype),s.prototype.add=function(t){var e=Q(t);if(this.sign!==e.sign)return this.subtract(e.negate());var r=this.value,o=e.value;return e.isSmall?new s(w(r,Math.abs(o)),this.sign):new s(b(r,o),this.sign)},s.prototype.plus=s.prototype.add,l.prototype.add=function(t){var e=Q(t),r=this.value;if(r<0!==e.sign)return this.subtract(e.negate());var o=e.value;if(e.isSmall){if(v(r+o))return new l(r+o);o=y(Math.abs(o))}return new s(w(o,Math.abs(r)),r<0)},l.prototype.plus=l.prototype.add,f.prototype.add=function(t){return new f(this.value+Q(t).value)},f.prototype.plus=f.prototype.add,s.prototype.subtract=function(t){var e=Q(t);if(this.sign!==e.sign)return this.add(e.negate());var r=this.value,o=e.value;return e.isSmall?q(r,Math.abs(o),this.sign):function(t,e,r){var o;return x(t,e)>=0?o=S(t,e):(o=S(e,t),r=!r),"number"==typeof(o=h(o))?(r&&(o=-o),new l(o)):new s(o,r)}(r,o,this.sign)},s.prototype.minus=s.prototype.subtract,l.prototype.subtract=function(t){var e=Q(t),r=this.value;if(r<0!==e.sign)return this.add(e.negate());var o=e.value;return e.isSmall?new l(r-o):q(o,Math.abs(r),r>=0)},l.prototype.minus=l.prototype.subtract,f.prototype.subtract=function(t){return new f(this.value-Q(t).value)},f.prototype.minus=f.prototype.subtract,s.prototype.negate=function(){return new s(this.value,!this.sign)},l.prototype.negate=function(){var t=this.sign,e=new l(-this.value);return e.sign=!t,e},f.prototype.negate=function(){return new f(-this.value)},s.prototype.abs=function(){return new s(this.value,!1)},l.prototype.abs=function(){return new l(Math.abs(this.value))},f.prototype.abs=function(){return new f(this.value>=0?this.value:-this.value)},s.prototype.multiply=function(t){var r,o,n,i=Q(t),u=this.value,p=i.value,l=this.sign!==i.sign;if(i.isSmall){if(0===p)return a[0];if(1===p)return this;if(-1===p)return this.negate();if((r=Math.abs(p))<e)return new s(N(u,r),l);p=y(r)}return o=u.length,n=p.length,new s(-.012*o-.012*n+15e-6*o*n>0?function t(e,r){var o=Math.max(e.length,r.length);if(o<=30)return M(e,r);o=Math.ceil(o/2);var n=e.slice(o),i=e.slice(0,o),u=r.slice(o),p=r.slice(0,o),a=t(i,p),s=t(n,u),l=t(b(i,n),b(p,u)),f=b(b(a,E(S(S(l,a),s),o)),E(s,2*o));return c(f),f}(u,p):M(u,p),l)},s.prototype.times=s.prototype.multiply,l.prototype._multiplyBySmall=function(t){return v(t.value*this.value)?new l(t.value*this.value):O(Math.abs(t.value),y(Math.abs(this.value)),this.sign!==t.sign)},s.prototype._multiplyBySmall=function(t){return 0===t.value?a[0]:1===t.value?this:-1===t.value?this.negate():O(Math.abs(t.value),this.value,this.sign!==t.sign)},l.prototype.multiply=function(t){return Q(t)._multiplyBySmall(this)},l.prototype.times=l.prototype.multiply,f.prototype.multiply=function(t){return new f(this.value*Q(t).value)},f.prototype.times=f.prototype.multiply,s.prototype.square=function(){return new s(P(this.value),!1)},l.prototype.square=function(){var t=this.value*this.value;return v(t)?new l(t):new s(P(y(Math.abs(this.value))),!1)},f.prototype.square=function(t){return new f(this.value*this.value)},s.prototype.divmod=function(t){var e=B(this,t);return{quotient:e[0],remainder:e[1]}},f.prototype.divmod=l.prototype.divmod=s.prototype.divmod,s.prototype.divide=function(t){return B(this,t)[0]},f.prototype.over=f.prototype.divide=function(t){return new f(this.value/Q(t).value)},l.prototype.over=l.prototype.divide=s.prototype.over=s.prototype.divide,s.prototype.mod=function(t){return B(this,t)[1]},f.prototype.mod=f.prototype.remainder=function(t){return new f(this.value%Q(t).value)},l.prototype.remainder=l.prototype.mod=s.prototype.remainder=s.prototype.mod,s.prototype.pow=function(t){var e,r,o,n=Q(t),i=this.value,u=n.value;if(0===u)return a[1];if(0===i)return a[0];if(1===i)return a[1];if(-1===i)return n.isEven()?a[1]:a[-1];if(n.sign)return a[0];if(!n.isSmall)throw new Error("The exponent "+n.toString()+" is too large.");if(this.isSmall&&v(e=Math.pow(i,u)))return new l(m(e));for(r=this,o=a[1];!0&u&&(o=o.times(r),--u),0!==u;)u/=2,r=r.square();return o},l.prototype.pow=s.prototype.pow,f.prototype.pow=function(t){var e=Q(t),r=this.value,o=e.value,n=BigInt(0),i=BigInt(1),u=BigInt(2);if(o===n)return a[1];if(r===n)return a[0];if(r===i)return a[1];if(r===BigInt(-1))return e.isEven()?a[1]:a[-1];if(e.isNegative())return new f(n);for(var p=this,s=a[1];(o&i)===i&&(s=s.times(p),--o),o!==n;)o/=u,p=p.square();return s},s.prototype.modPow=function(t,e){if(t=Q(t),(e=Q(e)).isZero())throw new Error("Cannot take modPow with modulus 0");var r=a[1],o=this.mod(e);for(t.isNegative()&&(t=t.multiply(a[-1]),o=o.modInv(e));t.isPositive();){if(o.isZero())return a[0];t.isOdd()&&(r=r.multiply(o).mod(e)),t=t.divide(2),o=o.square().mod(e)}return r},f.prototype.modPow=l.prototype.modPow=s.prototype.modPow,s.prototype.compareAbs=function(t){var e=Q(t),r=this.value,o=e.value;return e.isSmall?1:x(r,o)},l.prototype.compareAbs=function(t){var e=Q(t),r=Math.abs(this.value),o=e.value;return e.isSmall?r===(o=Math.abs(o))?0:r>o?1:-1:-1},f.prototype.compareAbs=function(t){var e=this.value,r=Q(t).value;return(e=e>=0?e:-e)===(r=r>=0?r:-r)?0:e>r?1:-1},s.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=Q(t),r=this.value,o=e.value;return this.sign!==e.sign?e.sign?1:-1:e.isSmall?this.sign?-1:1:x(r,o)*(this.sign?-1:1)},s.prototype.compareTo=s.prototype.compare,l.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=Q(t),r=this.value,o=e.value;return e.isSmall?r==o?0:r>o?1:-1:r<0!==e.sign?r<0?-1:1:r<0?1:-1},l.prototype.compareTo=l.prototype.compare,f.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=this.value,r=Q(t).value;return e===r?0:e>r?1:-1},f.prototype.compareTo=f.prototype.compare,s.prototype.equals=function(t){return 0===this.compare(t)},f.prototype.eq=f.prototype.equals=l.prototype.eq=l.prototype.equals=s.prototype.eq=s.prototype.equals,s.prototype.notEquals=function(t){return 0!==this.compare(t)},f.prototype.neq=f.prototype.notEquals=l.prototype.neq=l.prototype.notEquals=s.prototype.neq=s.prototype.notEquals,s.prototype.greater=function(t){return this.compare(t)>0},f.prototype.gt=f.prototype.greater=l.prototype.gt=l.prototype.greater=s.prototype.gt=s.prototype.greater,s.prototype.lesser=function(t){return this.compare(t)<0},f.prototype.lt=f.prototype.lesser=l.prototype.lt=l.prototype.lesser=s.prototype.lt=s.prototype.lesser,s.prototype.greaterOrEquals=function(t){return this.compare(t)>=0},f.prototype.geq=f.prototype.greaterOrEquals=l.prototype.geq=l.prototype.greaterOrEquals=s.prototype.geq=s.prototype.greaterOrEquals,s.prototype.lesserOrEquals=function(t){return this.compare(t)<=0},f.prototype.leq=f.prototype.lesserOrEquals=l.prototype.leq=l.prototype.lesserOrEquals=s.prototype.leq=s.prototype.lesserOrEquals,s.prototype.isEven=function(){return 0==(1&this.value[0])},l.prototype.isEven=function(){return 0==(1&this.value)},f.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},s.prototype.isOdd=function(){return 1==(1&this.value[0])},l.prototype.isOdd=function(){return 1==(1&this.value)},f.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},s.prototype.isPositive=function(){return!this.sign},l.prototype.isPositive=function(){return this.value>0},f.prototype.isPositive=l.prototype.isPositive,s.prototype.isNegative=function(){return this.sign},l.prototype.isNegative=function(){return this.value<0},f.prototype.isNegative=l.prototype.isNegative,s.prototype.isUnit=function(){return!1},l.prototype.isUnit=function(){return 1===Math.abs(this.value)},f.prototype.isUnit=function(){return this.abs().value===BigInt(1)},s.prototype.isZero=function(){return!1},l.prototype.isZero=function(){return 0===this.value},f.prototype.isZero=function(){return this.value===BigInt(0)},s.prototype.isDivisibleBy=function(t){var e=Q(t);return!e.isZero()&&(!!e.isUnit()||(0===e.compareAbs(2)?this.isEven():this.mod(e).isZero()))},f.prototype.isDivisibleBy=l.prototype.isDivisibleBy=s.prototype.isDivisibleBy,s.prototype.isPrime=function(t){var e=A(this);if(void 0!==e)return e;var r=this.abs(),n=r.bitLength();if(n<=64)return Z(r,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var i=Math.log(2)*n.toJSNumber(),u=Math.ceil(!0===t?2*Math.pow(i,2):i),p=[],a=0;a<u;a++)p.push(o(a+2));return Z(r,p)},f.prototype.isPrime=l.prototype.isPrime=s.prototype.isPrime,s.prototype.isProbablePrime=function(t){var e=A(this);if(void 0!==e)return e;for(var r=this.abs(),n=void 0===t?5:t,i=[],u=0;u<n;u++)i.push(o.randBetween(2,r.minus(2)));return Z(r,i)},f.prototype.isProbablePrime=l.prototype.isProbablePrime=s.prototype.isProbablePrime,s.prototype.modInv=function(t){for(var e,r,n,i=o.zero,u=o.one,p=Q(t),a=this.abs();!a.isZero();)e=p.divide(a),r=i,n=p,i=u,p=a,u=r.subtract(e.multiply(u)),a=n.subtract(e.multiply(a));if(!p.isUnit())throw new Error(this.toString()+" and "+t.toString()+" are not co-prime");return-1===i.compare(0)&&(i=i.add(t)),this.isNegative()?i.negate():i},f.prototype.modInv=l.prototype.modInv=s.prototype.modInv,s.prototype.next=function(){var t=this.value;return this.sign?q(t,1,this.sign):new s(w(t,1),this.sign)},l.prototype.next=function(){var t=this.value;return t+1<n?new l(t+1):new s(i,!1)},f.prototype.next=function(){return new f(this.value+BigInt(1))},s.prototype.prev=function(){var t=this.value;return this.sign?new s(w(t,1),!0):q(t,1,this.sign)},l.prototype.prev=function(){var t=this.value;return t-1>-n?new l(t-1):new s(i,!0)},f.prototype.prev=function(){return new f(this.value-BigInt(1))};for(var j=[1];2*j[j.length-1]<=e;)j.push(2*j[j.length-1]);var J=j.length,L=j[J-1];function U(t){return Math.abs(t)<=e}function T(t,e,r){e=Q(e);for(var n=t.isNegative(),i=e.isNegative(),u=n?t.not():t,p=i?e.not():e,a=0,s=0,l=null,f=null,v=[];!u.isZero()||!p.isZero();)a=(l=B(u,L))[1].toJSNumber(),n&&(a=L-1-a),s=(f=B(p,L))[1].toJSNumber(),i&&(s=L-1-s),u=l[0],p=f[0],v.push(r(a,s));for(var y=0!==r(n?1:0,i?1:0)?o(-1):o(0),h=v.length-1;h>=0;h-=1)y=y.multiply(L).add(o(v[h]));return y}s.prototype.shiftLeft=function(t){var e=Q(t).toJSNumber();if(!U(e))throw new Error(String(e)+" is too large for shifting.");if(e<0)return this.shiftRight(-e);var r=this;if(r.isZero())return r;for(;e>=J;)r=r.multiply(L),e-=J-1;return r.multiply(j[e])},f.prototype.shiftLeft=l.prototype.shiftLeft=s.prototype.shiftLeft,s.prototype.shiftRight=function(t){var e,r=Q(t).toJSNumber();if(!U(r))throw new Error(String(r)+" is too large for shifting.");if(r<0)return this.shiftLeft(-r);for(var o=this;r>=J;){if(o.isZero()||o.isNegative()&&o.isUnit())return o;o=(e=B(o,L))[1].isNegative()?e[0].prev():e[0],r-=J-1}return(e=B(o,j[r]))[1].isNegative()?e[0].prev():e[0]},f.prototype.shiftRight=l.prototype.shiftRight=s.prototype.shiftRight,s.prototype.not=function(){return this.negate().prev()},f.prototype.not=l.prototype.not=s.prototype.not,s.prototype.and=function(t){return T(this,t,function(t,e){return t&e})},f.prototype.and=l.prototype.and=s.prototype.and,s.prototype.or=function(t){return T(this,t,function(t,e){return t|e})},f.prototype.or=l.prototype.or=s.prototype.or,s.prototype.xor=function(t){return T(this,t,function(t,e){return t^e})},f.prototype.xor=l.prototype.xor=s.prototype.xor;var _=1<<30,k=(e&-e)*(e&-e)|_;function C(t){var r=t.value,o="number"==typeof r?r|_:"bigint"==typeof r?r|BigInt(_):r[0]+r[1]*e|k;return o&-o}function D(t,e){return t=Q(t),e=Q(e),t.greater(e)?t:e}function z(t,e){return t=Q(t),e=Q(e),t.lesser(e)?t:e}function R(t,e){if(t=Q(t).abs(),e=Q(e).abs(),t.equals(e))return t;if(t.isZero())return e;if(e.isZero())return t;for(var r,o,n=a[1];t.isEven()&&e.isEven();)r=z(C(t),C(e)),t=t.divide(r),e=e.divide(r),n=n.multiply(r);for(;t.isEven();)t=t.divide(C(t));do{for(;e.isEven();)e=e.divide(C(e));t.greater(e)&&(o=e,e=t,t=o),e=e.subtract(t)}while(!e.isZero());return n.isUnit()?t:t.multiply(n)}s.prototype.bitLength=function(){var t=this;return t.compareTo(o(0))<0&&(t=t.negate().subtract(o(1))),0===t.compareTo(o(0))?o(0):o(function t(e,r){if(r.compareTo(e)<=0){var n=t(e,r.square(r)),i=n.p,u=n.e,p=i.multiply(r);return p.compareTo(e)<=0?{p:p,e:2*u+1}:{p:i,e:2*u}}return{p:o(1),e:0}}(t,o(2)).e).add(o(1))},f.prototype.bitLength=l.prototype.bitLength=s.prototype.bitLength;var F=function(t,e,r,o){r=r||u,t=String(t),o||(t=t.toLowerCase(),r=r.toLowerCase());var n,i=t.length,p=Math.abs(e),a={};for(n=0;n<r.length;n++)a[r[n]]=n;for(n=0;n<i;n++){if("-"!==(f=t[n])&&(f in a&&a[f]>=p)){if("1"===f&&1===p)continue;throw new Error(f+" is not a valid digit in base "+e+".")}}e=Q(e);var s=[],l="-"===t[0];for(n=l?1:0;n<t.length;n++){var f;if((f=t[n])in a)s.push(Q(a[f]));else{if("<"!==f)throw new Error(f+" is not a valid character");var v=n;do{n++}while(">"!==t[n]&&n<t.length);s.push(Q(t.slice(v+1,n)))}}return $(s,e,l)};function $(t,e,r){var o,n=a[0],i=a[1];for(o=t.length-1;o>=0;o--)n=n.add(t[o].times(i)),i=i.times(e);return r?n.negate():n}function G(t,e){if((e=o(e)).isZero()){if(t.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(e.equals(-1)){if(t.isZero())return{value:[0],isNegative:!1};if(t.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-t.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var r=Array.apply(null,Array(t.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return r.unshift([1]),{value:[].concat.apply([],r),isNegative:!1}}var n=!1;if(t.isNegative()&&e.isPositive()&&(n=!0,t=t.abs()),e.isUnit())return t.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(t.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:n};for(var i,u=[],p=t;p.isNegative()||p.compareAbs(e)>=0;){i=p.divmod(e),p=i.quotient;var a=i.remainder;a.isNegative()&&(a=e.minus(a).abs(),p=p.next()),u.push(a.toJSNumber())}return u.push(p.toJSNumber()),{value:u.reverse(),isNegative:n}}function H(t,e,r){var o=G(t,e);return(o.isNegative?"-":"")+o.value.map(function(t){return function(t,e){return t<(e=e||u).length?e[t]:"<"+t+">"}(t,r)}).join("")}function K(t){if(v(+t)){var e=+t;if(e===m(e))return p?new f(BigInt(e)):new l(e);throw new Error("Invalid integer: "+t)}var o="-"===t[0];o&&(t=t.slice(1));var n=t.split(/e/i);if(n.length>2)throw new Error("Invalid integer: "+n.join("e"));if(2===n.length){var i=n[1];if("+"===i[0]&&(i=i.slice(1)),(i=+i)!==m(i)||!v(i))throw new Error("Invalid integer: "+i+" is not a valid exponent.");var u=n[0],a=u.indexOf(".");if(a>=0&&(i-=u.length-a-1,u=u.slice(0,a)+u.slice(a+1)),i<0)throw new Error("Cannot include negative exponent part for integers");t=u+=new Array(i+1).join("0")}if(!/^([0-9][0-9]*)$/.test(t))throw new Error("Invalid integer: "+t);if(p)return new f(BigInt(o?"-"+t:t));for(var y=[],h=t.length,g=r,d=h-g;h>0;)y.push(+t.slice(d,h)),(d-=g)<0&&(d=0),h-=g;return c(y),new s(y,o)}function Q(t){return"number"==typeof t?function(t){if(p)return new f(BigInt(t));if(v(t)){if(t!==m(t))throw new Error(t+" is not an integer.");return new l(t)}return K(t.toString())}(t):"string"==typeof t?K(t):"bigint"==typeof t?new f(t):t}s.prototype.toArray=function(t){return G(this,t)},l.prototype.toArray=function(t){return G(this,t)},f.prototype.toArray=function(t){return G(this,t)},s.prototype.toString=function(t,e){if(void 0===t&&(t=10),10!==t)return H(this,t,e);for(var r,o=this.value,n=o.length,i=String(o[--n]);--n>=0;)r=String(o[n]),i+="0000000".slice(r.length)+r;return(this.sign?"-":"")+i},l.prototype.toString=function(t,e){return void 0===t&&(t=10),10!=t?H(this,t,e):String(this.value)},f.prototype.toString=l.prototype.toString,f.prototype.toJSON=s.prototype.toJSON=l.prototype.toJSON=function(){return this.toString()},s.prototype.valueOf=function(){return parseInt(this.toString(),10)},s.prototype.toJSNumber=s.prototype.valueOf,l.prototype.valueOf=function(){return this.value},l.prototype.toJSNumber=l.prototype.valueOf,f.prototype.valueOf=f.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};for(var V=0;V<1e3;V++)a[V]=Q(V),V>0&&(a[-V]=Q(-V));return a.one=a[1],a.zero=a[0],a.minusOne=a[-1],a.max=D,a.min=z,a.gcd=R,a.lcm=function(t,e){return t=Q(t).abs(),e=Q(e).abs(),t.divide(R(t,e)).multiply(e)},a.isInstance=function(t){return t instanceof s||t instanceof l||t instanceof f},a.randBetween=function(t,r){var o=z(t=Q(t),r=Q(r)),n=D(t,r).subtract(o).add(1);if(n.isSmall)return o.add(Math.floor(Math.random()*n));for(var i=G(n,e).value,u=[],p=!0,s=0;s<i.length;s++){var l=p?i[s]:e,f=m(Math.random()*l);u.push(f),f<l&&(p=!1)}return o.add(a.fromArray(u,e,!1))},a.fromArray=function(t,e,r){return $(t.map(Q),Q(e||10),r)},a}();t.hasOwnProperty("exports")&&(t.exports=o),void 0===(r=function(){return o}.apply(e,[]))||(t.exports=r)}).call(this,r(3)(t))},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e){t.exports=require("fs")}]);

Score : 300 points

Problem Statement

As a token of his gratitude, Takahashi has decided to give his mother an integer sequence.
The sequence A needs to satisfy the conditions below:

A consists of integers between X and Y (inclusive).

For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.

Find the maximum possible length of the sequence.

Constraints

1 \leq X \leq Y \leq 10^{18}

All input values are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the maximum possible length of the sequence.

Sample Input 1

3 20

Sample Output 1

3

The sequence 3,6,18 satisfies the conditions.

Sample Input 2

25 100

Sample Output 2

3

Sample Input 3

314159265 358979323846264338

Sample Output 3

31


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

	var ans = 0;
	while(lower <= upper){
		lower = (lower * 2).toFixed(0);
		ans++;
	}
	console.log(ans);
}

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


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

 console.log(Math.ceil((a[0]+a[1])/2));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

You are given two positive integers a and b.
Let x be the average of a and b.
Print x rounded up to the nearest integer.

Constraints

a and b are integers.

1 \leq a, b \leq 100

Input

Input is given from Standard Input in the following format:

a b

Output

Print x rounded up to the nearest integer.

Sample Input 1

1 3

Sample Output 1

2

The average of 1 and 3 is 2.0, and it will be rounded up to the nearest integer, 2.

Sample Input 2

7 4

Sample Output 2

6

The average of 7 and 4 is 5.5, and it will be rounded up to the nearest integer, 6.

Sample Input 3

5 5

Sample Output 3

5


function main(input){
  var lines = input.split('\n');
  var s = lines[0].split(""); // change to array
  var t = lines[1].split("");
  s = s.sort();
  t = t.reverse();
//  console.log(s,t);
  for(i=0; i<Math.min(s.length,t.length); i++){
//    console.log(s[i], t[i]);
    if (t[i].localeCompare(s[i]) > 0) {  // -1 0 1
      return console.log('Yes');
    }
  }

  if (t[i-1]==s[i-1] && t.length>s.length){
    return console.log('Yes');
  }

  return console.log('No');

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

Score : 200 points

Problem Statement

You are given strings s and t, consisting of lowercase English letters.
You will create a string s' by freely rearranging the characters in s.
You will also create a string t' by freely rearranging the characters in t.
Determine whether it is possible to satisfy s' < t' for the lexicographic order.

Notes

For a string a = a_1 a_2 ... a_N of length N and a string b = b_1 b_2 ... b_M of length M, we say a < b for the lexicographic order if either one of the following two conditions holds true:

N < M and a_1 = b_1, a_2 = b_2, ..., a_N = b_N.

There exists i (1 \leq i \leq N, M) such that a_1 = b_1, a_2 = b_2, ..., a_{i - 1} = b_{i - 1} and a_i < b_i. Here, letters are compared using alphabetical order.

For example, xy < xya and atcoder < atlas.

Constraints

The lengths of s and t are between 1 and 100 (inclusive).

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If it is possible to satisfy s' < t', print Yes; if it is not, print No.

Sample Input 1

yx
axy

Sample Output 1

Yes

We can, for example, rearrange yx into xy and axy into yxa. Then, xy < yxa.

Sample Input 2

ratcode
atlas

Sample Output 2

Yes

We can, for example, rearrange ratcode into acdeort and atlas into tslaa. Then, acdeort < tslaa.

Sample Input 3

cd
abc

Sample Output 3

No

No matter how we rearrange cd and abc, we cannot achieve our objective.

Sample Input 4

w
ww

Sample Output 4

Yes

Sample Input 5

zzz
zzz

Sample Output 5

No


"use strict";

const main = arg => {
    const s = arg.split("\n")[0].split("");
    const t = arg.split("\n")[1].split("");

    console.log(s.sort() < t.reverse() ? "Yes" : "No");
}
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 set = new Set(A);
  const uniques = [...set];

  let answer = 0;

  const map = [...Array(1000000000)].fill(0);

  for(let i=0; i<N; i++) {
      map[A[i]]++;
  }

  for(let i in uniques) {
    let cnt = map[uniques[i]];

    if(cnt < uniques[i]) {
        answer += cnt;
    } else {
        answer += cnt - uniques[i];
    }
  }

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

Score : 300 points

Problem Statement

You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N).
Your objective is to remove some of the elements in a so that a will be a good sequence.

Here, an sequence b is a good sequence when the following condition holds true:

For each element x in b, the value x occurs exactly x times in b.

For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.

Find the minimum number of elements that needs to be removed so that a will be a good sequence.

Constraints

1 \leq N \leq 10^5

a_i is an integer.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum number of elements that needs to be removed so that a will be a good sequence.

Sample Input 1

4
3 3 3 3

Sample Output 1

1

We can, for example, remove one occurrence of 3. Then, (3, 3, 3) is a good sequence.

Sample Input 2

5
2 4 1 4 2

Sample Output 2

2

We can, for example, remove two occurrences of 4. Then, (2, 1, 2) is a good sequence.

Sample Input 3

6
1 2 2 3 3 3

Sample Output 3

0

Sample Input 4

1
1000000000

Sample Output 4

1

Remove one occurrence of 10^9. Then, () is a good sequence.

Sample Input 5

8
2 7 1 8 2 8 1 8

Sample Output 5

5


'use strict';
function main(input) {
    var args = input.split('\n')[1].split(' ').map((n) => parseInt(n, 10));
    //let args = input.split(' ');
  	let cnt = 0
    let len = args.length
	while(args.filter(a => a % 2 === 0).length === len) {
      args = args.map(a => a / 2)
      cnt = cnt + 1
      //console.log(args, cnt)
    }
  	console.log(cnt)

}

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

Score : 200 points

Problem Statement

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

Snuke can perform the following operation when all integers on the blackboard are even:

Replace each integer X on the blackboard by X divided by 2.

Find the maximum possible number of operations that Snuke can perform.

Constraints

1 \leq N \leq 200

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible number of operations that Snuke can perform.

Sample Input 1

3
8 12 40

Sample Output 1

2

Initially, [8, 12, 40] are written on the blackboard.
Since all those integers are even, Snuke can perform the operation.

After the operation is performed once, [4, 6, 20] are written on the blackboard.
Since all those integers are again even, he can perform the operation.

After the operation is performed twice, [2, 3, 10] are written on the blackboard.
Now, there is an odd number 3 on the blackboard, so he cannot perform the operation any more.

Thus, Snuke can perform the operation at most twice.

Sample Input 2

4
5 6 8 10

Sample Output 2

0

Since there is an odd number 5 on the blackboard already in the beginning, Snuke cannot perform the operation at all.

Sample Input 3

6
382253568 723152896 37802240 379425024 404894720 471526144

Sample Output 3

8


function main(input){
    var input = input.split('\n')
    var input_list = input[1].split(' ')
    var a = input_list[0]
    var b = input_list[1]
    var c = input_list[2]

    while(a%2==0 &&b%2==0 && c%2 ==0){
        a = a/2
        b = b/2
        c = c/2
    }
    console.log('%d %d %d', a,b,c)
}

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


function Main(s) {
  var s = s.split("\n")[0].split(" ").concat(s.split("\n")[1].split(" ")).map(e => Number(e));
  var arr = new Array(s[0] + 1).fill(0);
  for (var i = 2; i <= s[0] + 1; i++) {
    arr[s[i]]++;
  }
  var ans = 0;
  var v = arr.sort((a, b) => a - b);
  while (v.length > s[1]) {
    ans += v.shift();
  }
  console.log(ans);
}

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

Score : 300 points

Problem Statement

Takahashi has N balls. Initially, an integer A_i is written on the i-th ball.

He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls.

Find the minimum number of balls that Takahashi needs to rewrite the integers on them.

Constraints

1 \leq K \leq N \leq 200000

1 \leq A_i \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of balls that Takahashi needs to rewrite the integers on them.

Sample Input 1

5 2
1 1 2 2 5

Sample Output 1

1

For example, if we rewrite the integer on the fifth ball to 2, there are two different integers written on the balls: 1 and 2.
On the other hand, it is not possible to rewrite the integers on zero balls so that there are at most two different integers written on the balls, so we should print 1.

Sample Input 2

4 4
1 1 2 2

Sample Output 2

0

Already in the beginning, there are two different integers written on the balls, so we do not need to rewrite anything.

Sample Input 3

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

Sample Output 3

3


'use strict'

function main(input) {
  input = input.split('\n');
  const NK = input[0].split(' ').map(n => Number(n));
  const N = NK[0],
        K = NK[1];
  const A = input[1].split(' ').map(n => Number(n));
  const countBucket = [...Array(N+1)].fill(0);

  for (const num of A) {
    countBucket[num] += 1;
  }
  console.log(countBucket.sort((a, b) => b - a).slice(K).reduce((a, b) => a + b));
}

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


function main(input) {
  input=input.trim();
  var n=input.split("")
  var sum  = function(arr) {
    var sum = 0;
    for (var i=0,len=arr.length; i<len; ++i) {
        sum += Number(arr[i]);
    };
    return sum;
  };
  if(Number(input)%sum(n)==0){
    console.log("Yes");
  }else{
    console.log("No");
  }
}

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

Score : 200 points

Problem Statement

An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10.

Given an integer N, determine whether it is a Harshad number.

Constraints

1?N?10^8

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print Yes if N is a Harshad number; print No otherwise.

Sample Input 1

12

Sample Output 1

Yes

f(12)=1+2=3. Since 12 is divisible by 3, 12 is a Harshad number.

Sample Input 2

57

Sample Output 2

No

f(57)=5+7=12. Since 57 is not divisible by 12, 12 is not a Harshad number.

Sample Input 3

148

Sample Output 3

No


//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 one = nextIntArray();
  var N = one[0];
  var C = one[1];
  var len = 100005;
  var list = new Array(len);
  for(var i = 0; i < len; i++){
    list[i] = new Array(C + 1).fill(0);
  }
  for(var i = 0; i < N; i++){
    var tmp = nextIntArray();
    var L = tmp[0] - 1;
    var R = tmp[1];
    var cc = tmp[2];
    for(var j = L; j < R; j++){
      list[j][cc]++;
    }
  }

  var output = 0;
  for(var i = 0; i < len; i++){
    var sum = 0;
    for(var j = 0; j <= C; j++){
      sum += list[i][j];
    }
    output = Math.max(output, sum);
  }
  myout(output);
}

Score : 400 points

Problem Statement

Joisino is planning to record N TV programs with recorders.

The TV can receive C channels numbered 1 through C.

The i-th program that she wants to record will be broadcast from time s_i to time t_i (including time s_i but not t_i) on Channel c_i.

Here, there will never be more than one program that are broadcast on the same channel at the same time.

When the recorder is recording a channel from time S to time T (including time S but not T), it cannot record other channels from time S-0.5 to time T (including time S-0.5 but not T).

Find the minimum number of recorders required to record the channels so that all the N programs are completely recorded.

Constraints

1≤N≤10^5

1≤C≤30

1≤s_i<t_i≤10^5

1≤c_i≤C

If c_i=c_j and i≠j, either t_i≤s_j or s_i≥t_j.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N C
s_1 t_1 c_1
:
s_N t_N c_N

Output

When the minimum required number of recorders is x, print the value of x.

Sample Input 1

3 2
1 7 2
7 8 1
8 12 1

Sample Output 1

2

Two recorders can record all the programs, for example, as follows:

With the first recorder, record Channel 2 from time 1 to time 7. The first program will be recorded. Note that this recorder will be unable to record other channels from time 0.5 to time 7.

With the second recorder, record Channel 1 from time 7 to time 12. The second and third programs will be recorded. Note that this recorder will be unable to record other channels from time 6.5 to time 12.

Sample Input 2

3 4
1 3 2
3 4 4
1 4 3

Sample Output 2

3

There may be a channel where there is no program to record.

Sample Input 3

9 4
56 60 4
33 37 2
89 90 3
32 43 1
67 68 3
49 51 3
31 32 3
70 71 1
11 12 3

Sample Output 3

2


function Main(arg)
{
  var S = arg.split("\n")[0].split("");

  if ((new Set(S)).size === 1 && S.length > 1) {
    console.log("NO");
    return;
  }

  if ((new Set(S)).size === 2 && S.length === 2) {
    console.log("YES");
    return;
  }

  if ((new Set(S)).size === 2 && S.length > 2) {
    console.log("NO");
    return;
  }

  if (S.length % 2 == 0) {
    var a = S.slice(0, S.length / 2 - 1);
    var b = S.slice(0, S.length / 2).reverse();

    if (a.toString() === b.toString()) {
      a = new Set(a);
      b = new Set(b);
      if (a.size == 1 && b.size == 1) {
        console.log("NO");
        return;
      }
    }
  }
  else {
    var a = S.slice(0, ((S.length-1) / 2));
    var b = S.slice(((S.length-1) / 2)+1).reverse();

    if (a.toString() === b.toString()) {
      a = new Set(a);
      b = new Set(b);
      if (a.size == 1 && b.size == 1) {
        console.log("NO");
        return;
      }
    }
  }
  console.log("YES");
  return;
}

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

Score : 400 points

Problem Statement

Snuke has a string S consisting of three kinds of letters: a, b and c.

He has a phobia for palindromes, and wants to permute the characters in S so that S will not contain a palindrome of length 2 or more as a substring. Determine whether this is possible.

Constraints

1 \leq |S| \leq 10^5

S consists of a, b and c.

Input

Input is given from Standard Input in the following format:

S

Output

If the objective is achievable, print YES; if it is unachievable, print NO.

Sample Input 1

abac

Sample Output 1

YES

As it stands now, S contains a palindrome aba, but we can permute the characters to get acba, for example, that does not contain a palindrome of length 2 or more.

Sample Input 2

aba

Sample Output 2

NO

Sample Input 3

babacccabab

Sample Output 3

YES


function Main(input) {
    var isGood = new RegExp('(\\d)\\1{2,}').test(input);
    isGood ? console.log('Yes') : console.log('No');
    }
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

We call a 4-digit integer with three or more consecutive same digits, such as 1118, good.

You are given a 4-digit integer N. Answer the question: Is N good?

Constraints

1000 ≤ N ≤ 9999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is good, print Yes; otherwise, print No.

Sample Input 1

1118

Sample Output 1

Yes

N is good, since it contains three consecutive 1.

Sample Input 2

7777

Sample Output 2

Yes

An integer is also good when all the digits are the same.

Sample Input 3

1234

Sample Output 3

No


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

var words = input.split(' ');

var operand;
if (words[0] === words[1]) {
    operand = '=';
} else if (words[0] < words[1]) {
    operand = '<';
} else {
    operand = '>';
}
console.log(operand);

Score : 100 points

Problem Statement

In programming, hexadecimal notation is often used.

In hexadecimal notation, besides the ten digits 0, 1, ..., 9, the six letters A, B, C, D, E and F are used to represent the values 10, 11, 12, 13, 14 and 15, respectively.

In this problem, you are given two letters X and Y. Each X and Y is A, B, C, D, E or F.

When X and Y are seen as hexadecimal numbers, which is larger?

Constraints

Each X and Y is A, B, C, D, E or F.

Input

Input is given from Standard Input in the following format:

X Y

Output

If X is smaller, print <; if Y is smaller, print >; if they are equal, print =.

Sample Input 1

A B

Sample Output 1

<

10 < 11.

Sample Input 2

E C

Sample Output 2

>

14 > 12.

Sample Input 3

F F

Sample Output 3

=

15 = 15.


function Main(input) {
  const numbers = input.split(' ');
  const x = parseInt(numbers[0], 10);
  const y = parseInt(numbers[1], 10);
  if (x > y) {
    console.log('>');
  } else if (x < y) {
    console.log('<');
  } else {
    console.log('=');
  }
}

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


function Main(input) {
  input = input.split("\n");
  var n = parseInt(input[0].split(" ")[0]);
  var z = parseInt(input[0].split(" ")[1]);
  var w = parseInt(input[0].split(" ")[2]);
  tmp = input[1].split(" ");
  ans = 0;
  a = new Array(n).fill(0);
  for(i=0;i<n;i++){
    a[i]=parseInt(tmp[i]);
  }
  var max=0;
  var min=1000000000;
  for(i=0;i<n;i++){
    max=Math.max(max,a[i]);
    min=Math.min(min,a[i]);
  }
  ans=Math.max(Math.abs(max-w),Math.abs(max-a[n-1]),Math.abs(a[n-1]-min));

  console.log('%s', ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 500 points

Problem Statement

We have a deck consisting of N cards. Each card has an integer written on it. The integer on the i-th card from the top is a_i.

Two people X and Y will play a game using this deck. Initially, X has a card with Z written on it in his hand, and Y has a card with W written on it in his hand. Then, starting from X, they will alternately perform the following action:

Draw some number of cards from the top of the deck. Then, discard the card in his hand and keep the last drawn card instead. Here, at least one card must be drawn.

The game ends when there is no more card in the deck. The score of the game is the absolute difference of the integers written on the cards in the two players' hand.

X will play the game so that the score will be maximized, and Y will play the game so that the score will be minimized. What will be the score of the game?

Constraints

All input values are integers.

1 \leq N \leq 2000

1 \leq Z, W, a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N Z W
a_1 a_2 ... a_N

Output

Print the score.

Sample Input 1

3 100 100
10 1000 100

Sample Output 1

900

If X draws two cards first, Y will draw the last card, and the score will be |1000 - 100| = 900.

Sample Input 2

3 100 1000
10 100 100

Sample Output 2

900

If X draws all the cards first, the score will be |1000 - 100| = 900.

Sample Input 3

5 1 1
1 1 1 1 1

Sample Output 3

0

Sample Input 4

1 1 1
1000000000

Sample Output 4

999999999


"use strict"

//https://img.atcoder.jp/arc084/editorial.pdf

function main(input) {
  //binary search
  const bs = (arr, key) => {
    let left = 0
    let right = arr.length
    let mid = 0
    while (left < right) {
      mid = Math.floor((left + right) / 2)
      //////
      if (arr[mid] == key && mid < arr.length) {
        return arr.length - (mid + 1)
      } else if (mid == 0 && arr[mid] > key) {
        return arr.length - mid
      } else if (mid == 0 && arr[mid + 1] > key) {
        return arr.length - (mid + 1) // 残りの数（keyよりお大きい数の数）を
      } else if (arr[mid] > key && arr[mid - 1] < key) {
        return arr.length - mid // 残りの数（keyよりお大きい数の数）を
        //////////
      } else if (key < arr[mid]) {
        right = mid
      } else {
        left = mid + 1
      }
    }
    return false // not found
  }
  // end of bs

  input = input.split(/\n/).map(v =>
    v
      .split(" ")
      .map(v => ~~v)
      .sort((a, b) => a - b)
  )
  const n = input[0][0]
  const items = input.slice(1, input.length)

  let ans = 0
  let tmp2 = []
  let tmp = []

  for (let i1 = 0; i1 < n; i1++) {
    tmp[i1] = bs(items[1], items[0][i1])
  }
  for (let i2 = 0; i2 < n; i2++) {
    tmp2[i2] = bs(items[2], items[1][i2])
  }

  tmp2.reverse()
  for (let i = 0; i < tmp.length; i++) {
    ans += tmp2.slice(0, tmp[i]).reduce((a, b) => a + b)
  }
  console.log(ans)
}
main(require("fs").readFileSync("/dev/stdin", "utf8"))

Score : 300 points

Problem Statement

The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and lower.

He has N parts for each of the three categories. The size of the i-th upper part is A_i, the size of the i-th middle part is B_i, and the size of the i-th lower part is C_i.

To build an altar, the size of the middle part must be strictly greater than that of the upper part, and the size of the lower part must be strictly greater than that of the middle part. On the other hand, any three parts that satisfy these conditions can be combined to form an altar.

How many different altars can Ringo build? Here, two altars are considered different when at least one of the three parts used is different.

Constraints

1 \leq N \leq 10^5

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

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

1 \leq C_i \leq 10^9(1\leq i\leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N
B_1 ... B_N
C_1 ... C_N

Output

Print the number of different altars that Ringo can build.

Sample Input 1

2
1 5
2 4
3 6

Sample Output 1

3

The following three altars can be built:

Upper: 1-st part, Middle: 1-st part, Lower: 1-st part

Upper: 1-st part, Middle: 1-st part, Lower: 2-nd part

Upper: 1-st part, Middle: 2-nd part, Lower: 2-nd part

Sample Input 2

3
1 1 1
2 2 2
3 3 3

Sample Output 2

27

Sample Input 3

6
3 14 159 2 6 53
58 9 79 323 84 6
2643 383 2 79 50 288

Sample Output 3

87


(function() {
    'use strict';

    var lines = [];
    require('readline').createInterface({
      input: process.stdin,
      output: process.stdout
    }).on('line', function(line) {
      lines.push(line);
    });
    process.stdin.on('end', function() {
      //lines.forEach(function(line) {
        //var tokens = line.split(' ').map(Number);
        //    console.log(tokens[0] + ' ' + tokens[1]);
      //}
      //)
      ;

    // ToDo start
      var N = parseInt(lines[0])
      var A = lines[1].split(" ")
      var B = lines[2].split(" ")
      var C = lines[3].split(" ")
      var ans = 0

      for (var ai=0;ai<N;ai++){
          for (var bi=0;bi<N;bi++){
              if( parseInt(A[ai]) < parseInt(B[bi]) ) {
//                  console.log("A:"+A[ai] + " B:"+B[bi])
                for (var ci=0;ci<N;ci++){
                    if( parseInt(B[bi]) < parseInt(C[ci])  ){
//                        console.log("ai:"+ai + " bi:"+bi + " ci:"+ci)
                        ans++
                    }
                 }
               }
          }
       }

    console.log(ans)

//      console.log( Math.pow(parseInt(lines[0]),2) - parseInt(lines[1])  )
    // ToDo end

    });

})();


function main(input) {
  var a = input[0]-0;
  var b = input[1]-0;
  var ans = 1;
  for(var i=0;i<a;i++){
    ans = Math.min(ans+b,ans*2);
  }
  console.log(ans);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"))

Score : 200 points

Problem Statement

Square1001 has seen an electric bulletin board displaying the integer 1.
He can perform the following operations A and B to change this value:

Operation A: The displayed value is doubled.

Operation B: The displayed value increases by K.

Square1001 needs to perform these operations N times in total.
Find the minimum possible value displayed in the board after N operations.

Constraints

1 \leq N, K \leq 10

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
K

Output

Print the minimum possible value displayed in the board after N operations.

Sample Input 1

4
3

Sample Output 1

10

The value will be minimized when the operations are performed in the following order: A, A, B, B.

In this case, the value will change as follows: 1 → 2 → 4 → 7 → 10.

Sample Input 2

10
10

Sample Output 2

76

The value will be minimized when the operations are performed in the following order: A, A, A, A, B, B, B, B, B, B.

In this case, the value will change as follows: 1 → 2 → 4 → 8 → 16 → 26 → 36 → 46 → 56 → 66 → 76.

By the way, this contest is AtCoder Beginner Contest 076.


Score : 400 points

Problem Statement

In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.

In the plan developed by the president Takahashi, the trains will run as follows:

A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds.

In the first t_1 seconds, a train must run at a speed of at most v_1 m/s (meters per second). Similarly, in the subsequent t_2 seconds, a train must run at a speed of at most v_2 m/s, and so on.

According to the specifications of the trains, the acceleration of a train must be always within ±1m/s^2. Additionally, a train must stop at the beginning and the end of the run.

Find the maximum possible distance that a train can cover in the run.

Constraints

1 \leq N \leq 100

1 \leq t_i \leq 200

1 \leq v_i \leq 100

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
t_1 t_2 t_3 … t_N
v_1 v_2 v_3 … v_N

Output

Print the maximum possible that a train can cover in the run.

Output is considered correct if its absolute difference from the judge's output is at most 10^{-3}.

Sample Input 1

1
100
30

Sample Output 1

2100.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first 30 seconds, it accelerates at a rate of 1m/s^2, covering 450 meters.

In the subsequent 40 seconds, it maintains the velocity of 30m/s, covering 1200 meters.

In the last 30 seconds, it decelerates at the acceleration of -1m/s^2, covering 450 meters.

The total distance covered is 450 + 1200 + 450 = 2100 meters.

Sample Input 2

2
60 50
34 38

Sample Output 2

2632.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first 34 seconds, it accelerates at a rate of 1m/s^2, covering 578 meters.

In the subsequent 26 seconds, it maintains the velocity of 34m/s, covering 884 meters.

In the subsequent 4 seconds, it accelerates at a rate of 1m/s^2, covering 144 meters.

In the subsequent 8 seconds, it maintains the velocity of 38m/s, covering 304 meters.

In the last 38 seconds, it decelerates at the acceleration of -1m/s^2, covering 722 meters.

The total distance covered is 578 + 884 + 144 + 304 + 722 = 2632 meters.

Sample Input 3

3
12 14 2
6 2 7

Sample Output 3

76.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first 6 seconds, it accelerates at a rate of 1m/s^2, covering 18 meters.

In the subsequent 2 seconds, it maintains the velocity of 6m/s, covering 12 meters.

In the subsequent 4 seconds, it decelerates at the acceleration of -1m/s^2, covering 16 meters.

In the subsequent 14 seconds, it maintains the velocity of 2m/s, covering 28 meters.

In the last 2 seconds, it decelerates at the acceleration of -1m/s^2, covering 2 meters.

The total distance covered is 18 + 12 + 16 + 28 + 2 = 76 meters.

Sample Input 4

1
9
10

Sample Output 4

20.250000000000000000

The maximum distance is achieved when a train runs as follows:

In the first 4.5 seconds, it accelerates at a rate of 1m/s^2, covering 10.125 meters.

In the last 4.5 seconds, it decelerates at the acceleration of -1m/s^2, covering 10.125 meters.

The total distance covered is 10.125 + 10.125 = 20.25 meters.

Sample Input 5

10
64 55 27 35 76 119 7 18 49 100
29 19 31 39 27 48 41 87 55 70

Sample Output 5

20291.000000000000


function Main(input) {
	input = input.trim().split(" ").map((a)=>Number(a));
  var a = input[0];
  var b = input[1];
  var c = input[2];
  if(a == b && a != c){
     console.log(c);
  }else if(a != b && a == c){
    console.log(b);
  }else{
    console.log(a);
  }
}

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

Score : 100 points

Problem Statement

You are given three integers, A, B and C.

Among them, two are the same, but the remaining one is different from the rest.

For example, when A=5,B=7,C=5, A and C are the same, but B is different.

Find the one that is different from the rest among the given three integers.

Constraints

-100 \leq A,B,C \leq 100

A, B and C are integers.

The input satisfies the condition in the statement.

Input

Input is given from Standard Input in the following format:

A B C

Output

Among A, B and C, print the integer that is different from the rest.

Sample Input 1

5 7 5

Sample Output 1

7

This is the same case as the one in the statement.

Sample Input 2

1 1 7

Sample Output 2

7

In this case, C is the one we seek.

Sample Input 3

-100 100 100

Sample Output 3

-100


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

var g_input = '';
process.stdin.on('data', function(chunk) {
    g_input += chunk;
});

process.stdin.on('end', function() {
    Main(g_input.split(/\r?\n/));
});

function Main(input) {

    var numbers = input[0].split(' ');

    if (numbers[0] == numbers[1]) {
        console.log(numbers[2]);
    }
    else if (numbers[0] == numbers[2]) {
        console.log(numbers[1]);
    }
    else {
        console.log(numbers[0]);
    }

    return 0;
}


'use strict'

class Main {
  solve() {
    const size = input.nextIntArr();
    console.log(size);
    const nodes = input.nextIntRange(size[1]);
    const edges = [];
    for (const n of nodes) {
      edges[n[0]] = edges[n[0]] ? edges[n[0]] : [];
      edges[n[1]] = edges[n[1]] ? edges[n[1]] : [];
      edges[n[0]].push(n[1]);
      edges[n[1]].push(n[0]);
    }

    let cnt = 0;
    for (let i = 0; i < size[1]; ++i) {
      const n = nodes[i];
      const stack = [n[0]];
      const visited = [];
      while (stack.length > 0) {
        const e = stack.pop();
        visited[e] = true;
        for (let _e of edges[e]) {
          if (e == n[0] && _e == n[1]) { continue; }
          if (visited[_e]) {continue;}
          stack.push(_e);
        }
      }
      if (!visited[n[1]]) { ++cnt; }
    }
    console.log(cnt);
  }
}

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

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

  /* 1行 or 複数行文字列 */
  nextLine(n) {
    if (n) {
      const ret = this.data.slice(this.cursor, this.cursor + n);
      this.cursor += n;
      return ret;
    }
    return this.data[this.cursor++];
  }
  /* 一行文字配列 */
  nextStrArr() { return this.nextLine().split(' '); }
  /* 一行整数配列 */
  nextIntArr() { return this.nextStrArr().map((e) => parseInt(e)); }
  /* 一行浮動小数点配列 */
  nextFloatArr() { return this.nextStrArr().map((e) => parseFloat(e)); }
  /* 複数行整数配列 */
  nextIntLine(n) { return this.nextLine(n).map((e) => parseInt(e)) }
  /* 複数行浮動小数点配列 */
  nextFloatLine(n) { return this.nextLine(n).map((e) => parseFloat(e)) }
  /* 複数行文字列二次元配列 */
  nextStrRange(n) { return this.nextLine(n).map((line) => line.split(' ')); }
  /* 複数行整数二次元配列 */
  nextIntRange(n) { return this.nextLine(n).map((line) => line.split(' ').map((e) => parseInt(e))); }
  /* 複数行浮動小数点数二次元配列 */
  nextFloatRange(n) {
    return this.nextLine(n).map((line) => line.split(' ').map((e) => parseFloat(e)));
  }
}
const input = new Input();
(new Main()).solve();

Score : 300 points

Problem Statement

You are given an undirected connected graph with N vertices and M edges that does not contain self-loops and double edges.

The i-th edge (1 \leq i \leq M) connects Vertex a_i and Vertex b_i.

An edge whose removal disconnects the graph is called a bridge.

Find the number of the edges that are bridges among the M edges.

Notes

A self-loop is an edge i such that a_i=b_i (1 \leq i \leq M).

Double edges are a pair of edges i,j such that a_i=a_j and b_i=b_j (1 \leq i<j \leq M).

An undirected graph is said to be connected when there exists a path between every pair of vertices.

Constraints

2 \leq N \leq 50

N-1 \leq M \leq min(N(N−1)⁄2,50)

1 \leq a_i<b_i \leq N

The given graph does not contain self-loops and double edges.

The given graph is connected.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the number of the edges that are bridges among the M edges.

Sample Input 1

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

Sample Output 1

4

The figure below shows the given graph:

The edges shown in red are bridges. There are four of them.

Sample Input 2

3 3
1 2
1 3
2 3

Sample Output 2

0

It is possible that there is no bridge.

Sample Input 3

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

Sample Output 3

5

It is possible that every edge is a bridge.


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

    var len = input.length;

    var ans = input.substr(0,len-8);
    // 出力
    console.log('%s', ans);
}

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

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

Score : 100 points

Problem Statement

Rng is going to a festival.

The name of the festival is given to you as a string S, which ends with FESTIVAL, from input. Answer the question: "Rng is going to a festival of what?" Output the answer.

Here, assume that the name of "a festival of s" is a string obtained by appending FESTIVAL to the end of s.
For example, CODEFESTIVAL is a festival of CODE.

Constraints

9 \leq |S| \leq 50

S consists of uppercase English letters.

S ends with FESTIVAL.

Input

Input is given from Standard Input in the following format:

S

Output

Print the answer to the question: "Rng is going to a festival of what?"

Sample Input 1

CODEFESTIVAL

Sample Output 1

CODE

This is the same as the example in the statement.

Sample Input 2

CODEFESTIVALFESTIVAL

Sample Output 2

CODEFESTIVAL

This string is obtained by appending FESTIVAL to the end of CODEFESTIVAL, so it is a festival of CODEFESTIVAL.

Sample Input 3

YAKINIKUFESTIVAL

Sample Output 3

YAKINIKU


function getLineByParam( param ){
  var ret;
  for ( var i=0; i<param[0].length; i++ ) {
    if ( "\n" == param[0].charAt( i ) ) {
      ret = param[0].slice( 0, i );
      param[0] = param[0].slice( ret.length+1 );
      return ret;
    }
  }
  ret = param[0];
  param[0]="";
  return ret;
}
function Main(input) {
  input = [input];
  var N = getLineByParam(input);
  N = parseInt( N );

  search2way( 0.0002857959416976279, 3500, 1750 );

  var N=4/N;
  var tmp;
  for ( var h=1; h<=3500; h++ ) {
    if ( N <= 1/h ) continue;
    for ( var n=1; n<=3500; n++ ) {
      tmp = 1/h + 1/n;
      if ( N <= tmp ) continue;

      tmp = search2way( N-tmp, 3500, 1750 );
      if ( -1 == tmp ) continue;
      if ( isCorrect( N, h, n, tmp ) ) return;
    }
  }
  console.log( "NG" );

  function search2way( ans, val, diff ){
    var tmp;
    var fix=0;
    while ( 0 != diff ) {
      tmp = 1/val;
      if ( ans == tmp ) {
        return val;
      }
      else if ( ans < tmp ) {
        val += diff;
        if ( 1 == diff && 0 == fix ) fix = 1;
        if ( -1 == fix ) return -1;
        if ( val > 3500 ) return -1;
      }
      else {
        val -= diff;
        if ( 1 == diff && 0 == fix ) fix = -1;
        if ( 1 == fix ) return -1;
        if ( val < 1 ) return -1;
      }

      diff = Math.floor( diff / 2 );
      if ( 0 == diff ) diff = 1;
    }
    return -1;
  }
  function isCorrect( N, h, n, w ){
    if ( N == ( 1/h + 1/n + 1/w ) ) {
      console.log( [ h, n, w ].join(" ") );
      return true;
    }
    return false;
  }
  function isInclude( ary, idx ){
    for ( var i=0; i<ary.length; i++ ) {
      if ( ary[i] === idx ) return true;
    }
    return false;
  }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

You are given an integer N.

Find a triple of positive integers h, n and w such that 4/N = 1/h + 1/n + 1/w.

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

Constraints

It is guaranteed that, for the given integer N, there exists a solution such that h,n,w \leq 3500.

Inputs

Input is given from Standard Input in the following format:

N

Outputs

Print a triple of positive integers h, n and w that satisfies the condition, in the following format:

h n w

Sample Input 1

2

Sample Output 1

1 2 2

4/2 = 1/1 + 1/2 + 1/2.

Sample Input 2

3485

Sample Output 2

872 1012974 1539173474040

It is allowed to use an integer exceeding 3500 in a solution.

Sample Input 3

4664

Sample Output 3

3498 3498 3498


"use strict";
const main = arg => {
  let Info = arg.split("\n");
  let Num = Info.shift();
  // .map(x => x*1)については型変換の常套句
  let personInfo = Info.map(i => i.split(" ").map(x => x*1));
  let infoMap = new Map();
  let As = [];

  // 情報をそれぞれの値に格納する（別にmapでなくてもよかった）
  personInfo.forEach((x) => {
  	infoMap.set(x[0],x[1]);
    As.push(x[0]);
  })
  // 一番最下位に近い人とその人の下に何人いるかの可能性だけ探ればいい
  let Amax = Math.max(...As);
  let ans = Amax + infoMap.get(Amax);

  console.log(ans);
}

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

Score : 200 points

Problem Statement

A group of people played a game. All players had distinct scores, which are positive integers.

Takahashi knows N facts on the players' scores. The i-th fact is as follows: the A_i-th highest score among the players is B_i.

Find the maximum possible number of players in the game.

Constraints

1 \leq N \leq 10^5

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

0 \leq B_i \leq 10^9(1\leq i\leq N)

If i ≠ j, A_i ≠ A_j.

There exists a possible outcome of the game that are consistent with the facts.

All input values are integers.

Inputs

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Outputs

Print the maximum possible number of players in the game.

Sample Input 1

3
4 7
2 9
6 2

Sample Output 1

8

The maximum possible number of players is achieved when, for example, the players have the following scores: 12,9,8,7,5,2,1,0.

Sample Input 2

5
1 10
3 6
5 2
4 4
2 8

Sample Output 2

7

Sample Input 3

2
1 1000000000
1000000000 1

Sample Output 3

1000000001


function Main(input) {
	if(input.indexOf("YAKI") == 0){
       console.log("Yes");
       }else{
       console.log("No");
       }
}

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

Score : 100 points

Problem Statement

Ringo is giving a present to Snuke.

Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with YAKI in Japanese, and does not like other things.

You are given a string S representing the Japanese name of Ringo's present to Snuke. Determine whether S starts with YAKI.

Constraints

1 \leq |S| \leq 10

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S starts with YAKI, print Yes; otherwise, print No.

Sample Input 1

YAKINIKU

Sample Output 1

Yes

YAKINIKU starts with YAKI.

Sample Input 2

TAKOYAKI

Sample Output 2

No

TAKOYAKI (a Japanese snack. tako: octopus) does not start with YAKI.

Sample Input 3

YAK

Sample Output 3

No


function main(input){
    var tmp = input.split(' ');
    var N = Number(tmp[0]);
    var M = Number(tmp[1]);
    var K = Number(tmp[2]);

    var num;
    for(var i=0; i<N; i++){
        for(var j=0; j<M+1; j++){
            num = N*i + M*j - i*j*2;
            if(num==K){
                console.log("Yes");
                return;
            }
        }
    }
    console.log("No");

}

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

Score : 200 points

Problem Statement

We have a grid with N rows and M columns of squares. Initially, all the squares are white.

There is a button attached to each row and each column.
When a button attached to a row is pressed, the colors of all the squares in that row are inverted; that is, white squares become black and vice versa.
When a button attached to a column is pressed, the colors of all the squares in that column are inverted.

Takahashi can freely press the buttons any number of times. Determine whether he can have exactly K black squares in the grid.

Constraints

1 \leq N,M \leq 1000

0 \leq K \leq NM

Input

Input is given from Standard Input in the following format:

N M K

Output

If Takahashi can have exactly K black squares in the grid, print Yes; otherwise, print No.

Sample Input 1

2 2 2

Sample Output 1

Yes

Press the buttons in the order of the first row, the first column.

Sample Input 2

2 2 1

Sample Output 2

No

Sample Input 3

3 5 8

Sample Output 3

Yes

Press the buttons in the order of the first column, third column, second row, fifth column.

Sample Input 4

7 9 20

Sample Output 4

No


const n = require("fs").readFileSync("/dev/stdin", "utf8")
const a = require("fs").readFileSync("/dev/stdin", "utf8")
console.log(n*n - a)

Score : 100 points

Problem Statement

We have an N \times N square grid.

We will paint each square in the grid either black or white.

If we paint exactly A squares white, how many squares will be painted black?

Constraints

1 \leq N \leq 100

0 \leq A \leq N^2

Inputs

Input is given from Standard Input in the following format:

N
A

Outputs

Print the number of squares that will be painted black.

Sample Input 1

3
4

Sample Output 1

5

There are nine squares in a 3 \times 3 square grid.
Four of them will be painted white, so the remaining five squares will be painted black.

Sample Input 2

19
100

Sample Output 2

261

Sample Input 3

10
0

Sample Output 3

100

As zero squares will be painted white, all the squares will be painted black.


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

				}
			}
		}
	}
	myerr(minus);
	//minus /= 2;
	myout(output - minus);
}

Score : 500 points

Problem Statement

In Takahashi Kingdom, which once existed, there are N cities, and some pairs of cities are connected bidirectionally by roads.
The following are known about the road network:

People traveled between cities only through roads. It was possible to reach any city from any other city, via intermediate cities if necessary.

Different roads may have had different lengths, but all the lengths were positive integers.

Snuke the archeologist found a table with N rows and N columns, A, in the ruin of Takahashi Kingdom.
He thought that it represented the shortest distances between the cities along the roads in the kingdom.

Determine whether there exists a road network such that for each u and v, the integer A_{u, v} at the u-th row and v-th column of A is equal to the length of the shortest path from City u to City v.
If such a network exist, find the shortest possible total length of the roads.

Constraints

1 \leq N \leq 300

If i ≠ j, 1 \leq A_{i, j} = A_{j, i} \leq 10^9.

A_{i, i} = 0

Inputs

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} ... A_{1, N}
A_{2, 1} A_{2, 2} ... A_{2, N}
...
A_{N, 1} A_{N, 2} ... A_{N, N}

Outputs

If there exists no network that satisfies the condition, print -1.
If it exists, print the shortest possible total length of the roads.

Sample Input 1

3
0 1 3
1 0 2
3 2 0

Sample Output 1

3

The network below satisfies the condition:

City 1 and City 2 is connected by a road of length 1.

City 2 and City 3 is connected by a road of length 2.

City 3 and City 1 is not connected by a road.

Sample Input 2

3
0 1 3
1 0 1
3 1 0

Sample Output 2

-1

As there is a path of length 1 from City 1 to City 2 and City 2 to City 3, there is a path of length 2 from City 1 to City 3.
However, according to the table, the shortest distance between City 1 and City 3 must be 3.

Thus, we conclude that there exists no network that satisfies the condition.

Sample Input 3

5
0 21 18 11 28
21 0 13 10 26
18 13 0 23 13
11 10 23 0 17
28 26 13 17 0

Sample Output 3

82

Sample Input 4

3
0 1000000000 1000000000
1000000000 0 1000000000
1000000000 1000000000 0

Sample Output 4

3000000000