function Main(input){
	input = input.split("\n");
  var N = ~~input[0];
  var a = input[1].split(" ").map(b=>~~b);
  var sum = 0;
  for(var i = 0; i < N ; i++){
  	sum += a[i];
  }
  var avr = sum/N;
  for(var i = 0; i < N ; i++){
    a[i] = (a[i] - avr) * (a[i] - avr);
  }
  var smallestIndex = 0;
  var smallestValue = a[0];
  for(var i = 1; i < N ; i++){
   	if(smallestValue > a[i]){
    	smallestIndex = i;
      smallestValue = a[i];
    }
  }
  return smallestIndex;
}

// 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")])(`
3
1 2 3
`);

Score : 200 points

Problem Statement

Niwango-kun is an employee of Dwango Co., Ltd.

One day, he is asked to generate a thumbnail from a video a user submitted.

To generate a thumbnail, he needs to select a frame of the video according to the following procedure:

Get an integer N and N integers a_0, a_1, ..., a_{N-1} as inputs. N denotes the number of the frames of the video, and each a_i denotes the representation of the i-th frame of the video.

Select t-th frame whose representation a_t is nearest to the average of all frame representations.

If there are multiple such frames, select the frame with the smallest index.

Find the index t of the frame he should select to generate a thumbnail.

Constraints

1 \leq N \leq 100

1 \leq a_i \leq 100

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

N
a_{0} a_{1} ... a_{N-1}

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

1

Since the average of frame representations is 2, Niwango-kun needs to select the index 1, whose representation is 2, that is, the nearest value to the average.

Sample Input 2

4
2 5 2 5

Sample Output 2

0

The average of frame representations is 3.5.

In this case, every frame has the same distance from its representation to the average.

Therefore, Niwango-kun should select index 0, the smallest index among them.


n = gets.chomp.to_i
a = gets.split("\s").map{|i| i.to_i }
average = (a.inject(:+).to_f / n)
a.reverse!
min = 100
ans = n
a.each_with_index do |item, idx|
  abs = (item - average).abs
  if min >= abs
    min = abs
    ans = n - idx - 1
  end
end

puts ans

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

Submitted source-code file size, in bytes.

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

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


process.stdin.resume();
process.stdin.setEncoding('utf8');
// 自分の得意な言語で
// Let's チャレンジ！！

let lines = [];

const reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
reader.on('line', (line) => {
   lines.push(line);
});
reader.on('close', () => {
  let n = parseInt(lines.shift());
  let arr = lines.shift().split(/\s/).map(x => parseInt(x));
  let sum = arr.reduce((s, i) => s + i);
  let average = sum / arr.length;

  let min = 101;
  let ans = 0;
  for (let i = arr.length - 1; i >= 0; i--) {
    if (min >= Math.abs(arr[i] - average)) {
      min = Math.abs(arr[i] - average);
      ans = i;
    }
  }
  console.log(ans);
});


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

    var utu=[K];

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

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

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

Score : 400 points

Problem Statement

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

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

Find the maximum possible value for him.

Constraints

2 \leq N \leq 1000

1 \leq a_i \leq 10^9

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

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 ... a_N

Output

Print the answer.

Sample Input 1

4 2
2 5 2 5

Sample Output 1

12

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

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

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

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

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

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

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

Sample Input 2

8 4
9 1 8 2 7 5 6 4

Sample Output 2

32


'use strict';
const main = input => {
  input = input[0].split(' ').map(val => parseInt(val, 10));
  const x = input[0], y = input[1];
  console.log(x+y/2);

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

Score: 100 points

Problem Statement

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

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

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

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

Constraints

1 \leq X,Y \leq 100

Y is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

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

Sample Input 1

81 58

Sample Output 1

110

The train fare is 81 yen.

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

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

Sample Input 2

4 54

Sample Output 2

31


function Main(input) {
  input = input.split("\n");
  var X = parseInt(input[0].split(" ")[0]);
  var Y = parseInt(input[0].split(" ")[1]);
  ans= X + Y/2;
  console.log('%s', ans);
}

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


function Main(input) {
  const args = input.split('\n');
  const n = args[0];
  const t = args[1].split(' ')[0];
  const a = args[1].split(' ')[1];
  const h = args[2].split(' ');

  let diff = 9999999999999;
  let ret;
  for(let i=0; i<n; ++i) {
    let v = t - h[i]*0.006
    if(diff > a - v) {
      diff = a-v;
      ret = i+1;
    }
  }
  console.log(ret);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score: 200 points

Problem Statement

A country decides to build a palace.

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

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

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

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

It is guaranteed that the solution is unique.

Constraints

1 \leq N \leq 1000

0 \leq T \leq 50

-60 \leq A \leq T

0 \leq H_i \leq 10^5

All values in input are integers.

The solution is unique.

Input

Input is given from Standard Input in the following format:

N
T A
H_1 H_2 ... H_N

Output

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

Sample Input 1

2
12 5
1000 2000

Sample Output 1

1

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

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

Thus, the palace should be built at Place 1.

Sample Input 2

3
21 -11
81234 94124 52141

Sample Output 2

3


parcelRequire=function(e,r,t,n){var i,o="function"==typeof parcelRequire&&parcelRequire,u="function"==typeof require&&require;function f(t,n){if(!r[t]){if(!e[t]){var i="function"==typeof parcelRequire&&parcelRequire;if(!n&&i)return i(t,!0);if(o)return o(t,!0);if(u&&"string"==typeof t)return u(t);var c=new Error("Cannot find module '"+t+"'");throw c.code="MODULE_NOT_FOUND",c}p.resolve=function(r){return e[t][1][r]||r},p.cache={};var l=r[t]=new f.Module(t);e[t][0].call(l.exports,p,l,l.exports,this)}return r[t].exports;function p(e){return f(p.resolve(e))}}f.isParcelRequire=!0,f.Module=function(e){this.id=e,this.bundle=f,this.exports={}},f.modules=e,f.cache=r,f.parent=o,f.register=function(r,t){e[r]=[function(e,r){r.exports=t},{}]};for(var c=0;c<t.length;c++)try{f(t[c])}catch(e){i||(i=e)}if(t.length){var l=f(t[t.length-1]);"object"==typeof exports&&"undefined"!=typeof module?module.exports=l:"function"==typeof define&&define.amd?define(function(){return l}):n&&(this[n]=l)}if(parcelRequire=f,i)throw i;return f}({"Focm":[function(require,module,exports) {
var n={};!function(t){"use strict";(n["Control.Apply"]=n["Control.Apply"]||{}).arrayApply=function(n){return function(t){for(var a=n.length,r=t.length,e=new Array(a*r),o=0,i=0;i<a;i++)for(var u=n[i],c=0;c<r;c++)e[o++]=u(t[c]);return e}}}(),function(t){"use strict";(n["Data.Eq"]=n["Data.Eq"]||{}).refEq=function(n){return function(t){return n===t}}}(),function(t){"use strict";(n["Data.Unit"]=n["Data.Unit"]||{}).unit={}}(),function(t){"use strict";(n["Data.Show"]=n["Data.Show"]||{}).showIntImpl=function(n){return n.toString()}}(),function(t){"use strict";var a=n["Data.Show"],r=(n["Data.Symbol"],n["Record.Unsafe"],n["Type.Data.RowList"],function(n){this.show=n}),e=new r(a.showIntImpl);t.Show=r,t.show=function(n){return n.show},t.showInt=e}(n["Data.Show"]=n["Data.Show"]||{}),function(t){"use strict";var a=n["Data.Unit"];n["Data.Show"];t.unit=a.unit}(n["Data.Unit"]=n["Data.Unit"]||{}),function(t){"use strict";var a=n["Data.Eq"],r=(n["Data.HeytingAlgebra"],n["Data.Symbol"],n["Data.Unit"],n["Data.Void"],n["Record.Unsafe"],n["Type.Data.RowList"],function(n){this.eq=n}),e=new r(a.refEq);t.Eq=r,t.eq=function(n){return n.eq},t.eqNumber=e}(n["Data.Eq"]=n["Data.Eq"]||{}),function(t){"use strict";(n["Data.Ord.Unsafe"]=n["Data.Ord.Unsafe"]||{}).unsafeCompareImpl=function(n){return function(t){return function(a){return function(r){return function(e){return r<e?n:r===e?t:a}}}}}}(),function(t){"use strict";n["Data.Semigroup"],n["Data.Symbol"],n["Data.Unit"],n["Data.Void"],n["Record.Unsafe"],n["Type.Data.RowList"];t.append=function(n){return n.append}}(n["Data.Semigroup"]=n["Data.Semigroup"]||{}),function(t){"use strict";var a=n["Data.Eq"],r=(n["Data.Semigroup"],n["Data.Show"],function(){function n(){}return n.value=new n,n}()),e=function(){function n(){}return n.value=new n,n}(),o=function(){function n(){}return n.value=new n,n}(),i=new a.Eq(function(n){return function(t){return n instanceof r&&t instanceof r||(n instanceof e&&t instanceof e||n instanceof o&&t instanceof o)}});t.LT=r,t.GT=e,t.EQ=o,t.eqOrdering=i}(n["Data.Ordering"]=n["Data.Ordering"]||{}),function(t){"use strict";var a=n["Data.Ord.Unsafe"],r=n["Data.Ordering"],e=a.unsafeCompareImpl(r.LT.value)(r.EQ.value)(r.GT.value);t.unsafeCompare=e}(n["Data.Ord.Unsafe"]=n["Data.Ord.Unsafe"]||{}),function(t){"use strict";(n["Data.Ring"]=n["Data.Ring"]||{}).numSub=function(n){return function(t){return n-t}}}(),function(n){"use strict";n.numAdd=function(n){return function(t){return n+t}},n.numMul=function(n){return function(t){return n*t}}}(n["Data.Semiring"]=n["Data.Semiring"]||{}),function(t){"use strict";var a=n["Data.Semiring"],r=(n["Data.Symbol"],n["Data.Unit"],n["Record.Unsafe"],n["Type.Data.Row"],n["Type.Data.RowList"],function(n,t,a,r){this.add=n,this.mul=t,this.one=a,this.zero=r}),e=new r(a.numAdd,a.numMul,1,0);t.Semiring=r,t.add=function(n){return n.add},t.zero=function(n){return n.zero},t.mul=function(n){return n.mul},t.one=function(n){return n.one},t.semiringNumber=e}(n["Data.Semiring"]=n["Data.Semiring"]||{}),function(t){"use strict";var a=n["Data.Ring"],r=n["Data.Semiring"],e=(n["Data.Symbol"],n["Data.Unit"],n["Record.Unsafe"],n["Type.Data.RowList"],function(n,t){this.Semiring0=n,this.sub=t}),o=function(n){return n.sub},i=new e(function(){return r.semiringNumber},a.numSub);t.Ring=e,t.sub=o,t.negate=function(n){return function(t){return o(n)(r.zero(n.Semiring0()))(t)}},t.ringNumber=i}(n["Data.Ring"]=n["Data.Ring"]||{}),function(t){"use strict";n["Data.Ord"];var a=n["Data.Eq"],r=n["Data.Ord.Unsafe"],e=n["Data.Ordering"],o=n["Data.Ring"],i=n["Data.Semiring"],u=(n["Data.Symbol"],n["Data.Unit"],n["Data.Void"],n["Record.Unsafe"],n["Type.Data.RowList"],function(n,t){this.Eq0=n,this.compare=t}),c=new u(function(){return a.eqNumber},r.unsafeCompare),f=function(n){return n.compare},l=function(n){return function(t){return function(a){return!(f(n)(t)(a)instanceof e.LT)}}};t.Ord=u,t.compare=f,t.greaterThanOrEq=l,t.comparing=function(n){return function(t){return function(a){return function(r){return f(n)(t(a))(t(r))}}}},t.abs=function(n){return function(t){return function(a){return l(n)(a)(i.zero(t.Semiring0()))?a:o.negate(t)(a)}}},t.ordNumber=c}(n["Data.Ord"]=n["Data.Ord"]||{}),function(t){"use strict";n["Control.Category"],n["Data.Boolean"],n["Data.Ord"],n["Data.Ring"];t.flip=function(n){return function(t){return function(a){return n(a)(t)}}}}(n["Data.Function"]=n["Data.Function"]||{}),function(t){"use strict";(n["Data.Functor"]=n["Data.Functor"]||{}).arrayMap=function(n){return function(t){for(var a=t.length,r=new Array(a),e=0;e<a;e++)r[e]=n(t[e]);return r}}}(),function(t){"use strict";var a=n["Data.Functor"],r=(n["Control.Semigroupoid"],n["Data.Function"],n["Data.Unit"],function(n){this.map=n}),e=new r(a.arrayMap);t.Functor=r,t.map=function(n){return n.map},t.functorArray=e}(n["Data.Functor"]=n["Data.Functor"]||{}),function(t){"use strict";var a=n["Control.Apply"],r=(n["Control.Category"],n["Data.Function"],n["Data.Functor"]),e=function(n,t){this.Functor0=n,this.apply=t},o=new e(function(){return r.functorArray},a.arrayApply);t.Apply=e,t.apply=function(n){return n.apply},t.applyArray=o}(n["Control.Apply"]=n["Control.Apply"]||{}),function(t){"use strict";n["Control.Apply"],n["Data.Functor"],n["Data.Unit"];t.Applicative=function(n,t){this.Apply0=n,this.pure=t},t.pure=function(n){return n.pure}}(n["Control.Applicative"]=n["Control.Applicative"]||{}),function(t){"use strict";(n["Control.Bind"]=n["Control.Bind"]||{}).arrayBind=function(n){return function(t){for(var a=[],r=0,e=n.length;r<e;r++)Array.prototype.push.apply(a,t(n[r]));return a}}}(),function(t){"use strict";var a=n["Control.Bind"],r=(n["Control.Applicative"],n["Control.Apply"]),e=(n["Control.Category"],n["Data.Function"]),o=(n["Data.Functor"],n["Data.Unit"],function(n,t){this.Apply0=n,this.bind=t}),i=new o(function(){return r.applyArray},a.arrayBind),u=function(n){return n.bind};t.Bind=o,t.bind=u,t.bindFlipped=function(n){return e.flip(u(n))},t.bindArray=i}(n["Control.Bind"]=n["Control.Bind"]||{}),function(n){"use strict";n.range=function(n){return function(t){for(var a=n>t?-1:1,r=new Array(a*(t-n)+1),e=n,o=0;e!==t;)r[o++]=e,e+=a;return r[o]=e,r}},n.length=function(n){return n.length},n.indexImpl=function(n){return function(t){return function(a){return function(r){return r<0||r>=a.length?t:n(a[r])}}}},n.slice=function(n){return function(t){return function(a){return a.slice(n,t)}}},n.take=function(n){return function(t){return n<1?[]:t.slice(0,n)}},n.zipWith=function(n){return function(t){return function(a){for(var r=t.length<a.length?t.length:a.length,e=new Array(r),o=0;o<r;o++)e[o]=n(t[o])(a[o]);return e}}}}(n["Data.Array"]=n["Data.Array"]||{}),function(n){"use strict";n.foldrArray=function(n){return function(t){return function(a){for(var r=t,e=a.length-1;e>=0;e--)r=n(a[e])(r);return r}}},n.foldlArray=function(n){return function(t){return function(a){for(var r=t,e=a.length,o=0;o<e;o++)r=n(r)(a[o]);return r}}}}(n["Data.Foldable"]=n["Data.Foldable"]||{}),function(t){"use strict";n["Data.Boolean"],n["Data.Eq"],n["Data.EuclideanRing"],n["Data.Ord"],n["Data.Ordering"],n["Data.Semigroup"],n["Data.Symbol"],n["Data.Unit"],n["Record.Unsafe"],n["Type.Data.RowList"];t.mempty=function(n){return n.mempty}}(n["Data.Monoid"]=n["Data.Monoid"]||{}),function(t){"use strict";n["Control.Alt"],n["Control.Alternative"];var a=n["Control.Applicative"],r=n["Control.Apply"],e=n["Control.Bind"],o=(n["Control.Category"],n["Control.Extend"],n["Control.Monad"],n["Control.MonadZero"],n["Control.Plus"],n["Data.Bounded"],n["Data.Eq"],n["Data.Function"],n["Data.Functor"]),i=(n["Data.Functor.Invariant"],n["Data.Monoid"],n["Data.Ord"],n["Data.Ordering"],n["Data.Semigroup"],n["Data.Show"],n["Data.Unit"]),u=(n.Prelude,function(){function n(){}return n.value=new n,n}()),c=function(){function n(n){this.value0=n}return n.create=function(t){return new n(t)},n}(),f=new o.Functor(function(n){return function(t){return t instanceof c?new c(n(t.value0)):u.value}}),l=new r.Apply(function(){return f},function(n){return function(t){if(n instanceof c)return o.map(f)(n.value0)(t);if(n instanceof u)return u.value;throw new Error("Failed pattern match at Data.Maybe (line 67, column 1 - line 67, column 35): "+[n.constructor.name,t.constructor.name])}}),s=new e.Bind(function(){return l},function(n){return function(t){if(n instanceof c)return t(n.value0);if(n instanceof u)return u.value;throw new Error("Failed pattern match at Data.Maybe (line 125, column 1 - line 125, column 33): "+[n.constructor.name,t.constructor.name])}}),D=new a.Applicative(function(){return l},c.create);t.Nothing=u,t.Just=c,t.maybe=function(n){return function(t){return function(a){if(a instanceof u)return n;if(a instanceof c)return t(a.value0);throw new Error("Failed pattern match at Data.Maybe (line 217, column 1 - line 217, column 51): "+[n.constructor.name,t.constructor.name,a.constructor.name])}}},t["maybe'"]=function(n){return function(t){return function(a){if(a instanceof u)return n(i.unit);if(a instanceof c)return t(a.value0);throw new Error("Failed pattern match at Data.Maybe (line 230, column 1 - line 230, column 62): "+[n.constructor.name,t.constructor.name,a.constructor.name])}}},t.functorMaybe=f,t.applyMaybe=l,t.applicativeMaybe=D,t.bindMaybe=s}(n["Data.Maybe"]=n["Data.Maybe"]||{}),function(t){"use strict";var a=n["Data.Foldable"],r=(n["Control.Alt"],n["Control.Applicative"],n["Control.Apply"],n["Control.Bind"],n["Control.Category"],n["Control.Plus"],n["Control.Semigroupoid"],n["Data.Eq"]),e=(n["Data.Function"],n["Data.Functor"],n["Data.HeytingAlgebra"],n["Data.Maybe"]),o=(n["Data.Maybe.First"],n["Data.Maybe.Last"],n["Data.Monoid"]),i=(n["Data.Monoid.Additive"],n["Data.Monoid.Conj"],n["Data.Monoid.Disj"],n["Data.Monoid.Dual"],n["Data.Monoid.Endo"],n["Data.Monoid.Multiplicative"],n["Data.Newtype"],n["Data.Ord"],n["Data.Ordering"]),u=n["Data.Semigroup"],c=(n["Data.Semiring"],n["Data.Unit"],n.Prelude,function(n,t,a){this.foldMap=n,this.foldl=t,this.foldr=a}),f=function(n){return n.foldr},l=function(n){return n.foldl},s=function(n){return function(t){return function(a){return f(n)(function(n){return function(r){return u.append(t.Semigroup0())(a(n))(r)}})(o.mempty(t))}}},D=new c(function(n){return s(D)(n)},a.foldlArray,a.foldrArray);t.Foldable=c,t.foldr=f,t.foldl=l,t.foldMap=function(n){return n.foldMap},t.foldMapDefaultR=s,t.minimumBy=function(n){return function(t){return l(n)(function(n){return function(a){if(n instanceof e.Nothing)return new e.Just(a);if(n instanceof e.Just)return new e.Just(r.eq(i.eqOrdering)(t(n.value0)(a))(i.LT.value)?n.value0:a);throw new Error("Failed pattern match at Data.Foldable (line 402, column 3 - line 402, column 27): "+[n.constructor.name,a.constructor.name])}})(e.Nothing.value)}},t.foldableArray=D}(n["Data.Foldable"]=n["Data.Foldable"]||{}),function(t){"use strict";n["Control.Applicative"],n["Control.Apply"],n["Control.Biapplicative"],n["Control.Biapply"],n["Control.Bind"],n["Control.Comonad"],n["Control.Extend"],n["Control.Lazy"],n["Control.Monad"],n["Control.Semigroupoid"],n["Data.Bifoldable"],n["Data.Bifunctor"],n["Data.Bitraversable"],n["Data.BooleanAlgebra"],n["Data.Bounded"],n["Data.CommutativeRing"],n["Data.Distributive"],n["Data.Eq"],n["Data.Foldable"],n["Data.FoldableWithIndex"],n["Data.Function"],n["Data.Functor"],n["Data.Functor.Invariant"],n["Data.FunctorWithIndex"],n["Data.HeytingAlgebra"],n["Data.Maybe"],n["Data.Maybe.First"],n["Data.Monoid"],n["Data.Newtype"],n["Data.Ord"],n["Data.Ordering"],n["Data.Ring"],n["Data.Semigroup"],n["Data.Semigroup.Foldable"],n["Data.Semigroup.Traversable"],n["Data.Semiring"],n["Data.Show"],n["Data.Traversable"],n["Data.TraversableWithIndex"],n["Data.Unit"],n.Prelude,n["Type.Equality"];var a=function(){function n(n,t){this.value0=n,this.value1=t}return n.create=function(t){return function(a){return new n(t,a)}},n}();t.Tuple=a,t.fst=function(n){return n.value0},t.snd=function(n){return n.value1}}(n["Data.Tuple"]=n["Data.Tuple"]||{}),function(t){"use strict";(n["Partial.Unsafe"]=n["Partial.Unsafe"]||{}).unsafePartial=function(n){return n()}}(),function(t){"use strict";(n["Partial"]=n["Partial"]||{}).crashWith=function(){return function(n){throw new Error(n)}}}(),function(t){"use strict";var a=n.Partial;t.crashWith=a.crashWith}(n.Partial=n.Partial||{}),function(t){"use strict";var a=n["Partial.Unsafe"],r=n.Partial;t.unsafeCrashWith=function(n){return a.unsafePartial(function(t){return r.crashWith(t)(n)})}}(n["Partial.Unsafe"]=n["Partial.Unsafe"]||{}),function(t){"use strict";(n["Unsafe.Coerce"]=n["Unsafe.Coerce"]||{}).unsafeCoerce=function(n){return n}}(),function(t){"use strict";var a=n["Unsafe.Coerce"];t.unsafeCoerce=a.unsafeCoerce}(n["Unsafe.Coerce"]=n["Unsafe.Coerce"]||{}),function(t){"use strict";var a=n["Data.Array"],r=(n["Control.Alt"],n["Control.Alternative"],n["Control.Applicative"],n["Control.Apply"],n["Control.Bind"]),e=(n["Control.Category"],n["Control.Lazy"],n["Control.Monad.Rec.Class"],n["Control.Monad.ST"],n["Control.Monad.ST.Internal"],n["Control.Semigroupoid"],n["Data.Array.NonEmpty.Internal"],n["Data.Array.ST"],n["Data.Array.ST.Iterator"],n["Data.Boolean"],n["Data.Eq"],n["Data.Foldable"],n["Data.Function"]),o=(n["Data.Functor"],n["Data.HeytingAlgebra"],n["Data.Maybe"]),i=(n["Data.Ord"],n["Data.Ordering"],n["Data.Ring"],n["Data.Semigroup"],n["Data.Semiring"],n["Data.Traversable"],n["Data.Tuple"],n["Data.Unfoldable"],n["Partial.Unsafe"],n.Prelude,n["Unsafe.Coerce"],function(n){return[n]}),u=a.indexImpl(o.Just.create)(o.Nothing.value),c=e.flip(r.bind(r.bindArray));t.singleton=i,t.head=function(n){return u(n)(0)},t.last=function(n){return u(n)(a.length(n)-1|0)},t.index=u,t.concatMap=c,t.mapMaybe=function(n){return c(function(t){return o.maybe([])(i)(n(t))})},t.mapWithIndex=function(n){return function(t){return a.zipWith(n)(a.range(0)(a.length(t)-1|0))(t)}},t.take=a.take}(n["Data.Array"]=n["Data.Array"]||{}),function(t){"use strict";n["Control.Alt"];var a=n["Control.Applicative"],r=n["Control.Apply"],e=n["Control.Bind"],o=(n["Control.Extend"],n["Control.Monad"],n["Control.Semigroupoid"],n["Data.Bifoldable"],n["Data.Bifunctor"],n["Data.Bitraversable"],n["Data.Bounded"],n["Data.Eq"],n["Data.Foldable"],n["Data.FoldableWithIndex"],n["Data.Function"],n["Data.Functor"]),i=(n["Data.Functor.Invariant"],n["Data.FunctorWithIndex"],n["Data.Maybe"]),u=(n["Data.Monoid"],n["Data.Ord"],n["Data.Ordering"],n["Data.Semigroup"],n["Data.Show"],n["Data.Traversable"],n["Data.TraversableWithIndex"],n["Data.Unit"],n.Prelude,function(){function n(n){this.value0=n}return n.create=function(t){return new n(t)},n}()),c=function(){function n(n){this.value0=n}return n.create=function(t){return new n(t)},n}(),f=new o.Functor(function(n){return function(t){if(t instanceof u)return new u(t.value0);if(t instanceof c)return new c(n(t.value0));throw new Error("Failed pattern match at Data.Either (line 38, column 8 - line 38, column 52): "+[t.constructor.name])}}),l=function(n){return function(t){return function(a){if(a instanceof u)return n(a.value0);if(a instanceof c)return t(a.value0);throw new Error("Failed pattern match at Data.Either (line 238, column 1 - line 238, column 64): "+[n.constructor.name,t.constructor.name,a.constructor.name])}}},s=new r.Apply(function(){return f},function(n){return function(t){if(n instanceof u)return new u(n.value0);if(n instanceof c)return o.map(f)(n.value0)(t);throw new Error("Failed pattern match at Data.Either (line 82, column 1 - line 82, column 41): "+[n.constructor.name,t.constructor.name])}}),D=new e.Bind(function(){return s},l(function(n){return function(t){return new u(n)}})(function(n){return function(t){return t(n)}})),d=new a.Applicative(function(){return s},c.create);t.Left=u,t.Right=c,t.either=l,t.note=function(n){return i.maybe(new u(n))(c.create)},t.functorEither=f,t.applyEither=s,t.applicativeEither=d,t.bindEither=D}(n["Data.Either"]=n["Data.Either"]||{}),function(n){"use strict";n.toNumber=function(n){return n},n.fromStringAsImpl=function(n){return function(t){return function(a){var r;r=a<11?"[0-"+(a-1).toString()+"]":11===a?"[0-9a]":"[0-9a-"+String.fromCharCode(86+a)+"]";var e=new RegExp("^[\\+\\-]?"+r+"+$","i");return function(r){if(e.test(r)){var o=parseInt(r,a);return(0|o)===o?n(o):t}return t}}}}}(n["Data.Int"]=n["Data.Int"]||{}),function(t){"use strict";var a=n["Data.Int"],r=(n["Control.Category"],n["Control.Semigroupoid"],n["Data.Boolean"],n["Data.Bounded"],n["Data.CommutativeRing"],n["Data.DivisionRing"],n["Data.Eq"],n["Data.EuclideanRing"],n["Data.HeytingAlgebra"],n["Data.Int.Bits"],n["Data.Maybe"]),e=(n["Data.Ord"],n["Data.Ordering"],n["Data.Ring"],n["Data.Semiring"],n["Data.Show"],n.Global,n.Math,n.Prelude,a.fromStringAsImpl(r.Just.create)(r.Nothing.value)),o=e(10);t.fromString=o,t.fromStringAs=e,t.toNumber=a.toNumber}(n["Data.Int"]=n["Data.Int"]||{}),function(n){"use strict";n.split=function(n){return function(t){return t.split(n)}},n.trim=function(n){return n.trim()}}(n["Data.String.Common"]=n["Data.String.Common"]||{}),function(t){"use strict";var a=n["Data.String.Common"];n["Data.Eq"],n["Data.Ordering"],n["Data.String.Pattern"],n.Prelude;t.split=a.split,t.trim=a.trim}(n["Data.String.Common"]=n["Data.String.Common"]||{}),function(t){"use strict";var a=n["Control.Applicative"],r=n["Control.Bind"],e=n["Data.Array"],o=n["Data.Either"],i=n["Data.Foldable"],u=n["Data.Functor"],c=n["Data.Int"],f=n["Data.Maybe"],l=n["Data.Ord"],s=n["Data.Ring"],D=(n["Data.Semiring"],n["Data.Show"]),d=(n["Data.String"],n["Data.String.Common"]),p=(n["Data.String.Pattern"],n["Data.Tuple"]),m=(n["Debug.Trace"],n["Partial.Unsafe"]),g=(n.Prelude,function(n){var t=d.split("\n")(d.trim(n));return r.bind(o.bindEither)(o.note("n")(r.bindFlipped(f.bindMaybe)(c.fromString)(e.head(t))))(function(n){return r.bind(o.bindEither)(o.note("t a")(r.bind(f.bindMaybe)(e.last(e.take(2)(t)))(function(n){var t=e.mapMaybe(c.fromString)(d.split(" ")(n));return 2===t.length?new f.Just(new p.Tuple(t[0],t[1])):f.Nothing.value})))(function(n){return r.bind(o.bindEither)(o.note("hs")(r.bind(f.bindMaybe)(e.last(t))(function(n){return a.pure(f.applicativeMaybe)(e.mapMaybe(c.fromString)(d.split(" ")(n)))})))(function(t){return a.pure(o.applicativeEither)(D.show(D.showInt)((r=n.value0,function(n){return function(t){var a=c.toNumber(r),o=c.toNumber(n);return f["maybe'"](function(n){return m.unsafeCrashWith("hs is empty")})(p.fst)(i.minimumBy(i.foldableArray)(l.comparing(l.ordNumber)(p.snd))(e.mapWithIndex(function(n){return function(t){return new p.Tuple(n+1|0,l.abs(l.ordNumber)(s.ringNumber)(o-(a-.006*t)))}})(u.map(u.functorArray)(c.toNumber)(t))))}})(n.value1)(t)));var r})})})});t.solve=function(n){var t=g(n);if(t instanceof o.Left)return m.unsafeCrashWith(t.value0);if(t instanceof o.Right)return t.value0;throw new Error("Failed pattern match at AtCoder.ABC113.B (line 21, column 3 - line 23, column 24): "+[t.constructor.name])}}(n["AtCoder.ABC113.B"]=n["AtCoder.ABC113.B"]||{}),function(t){"use strict";(n["Effect.Console"]=n["Effect.Console"]||{}).log=function(n){return function(){return console.log(n),{}}}}(),function(t){"use strict";var a=n["Effect.Console"];n["Data.Show"],n["Data.Unit"],n.Effect;t.log=a.log}(n["Effect.Console"]=n["Effect.Console"]||{}),function(t){"use strict";n["Node.Encoding"];var a=n["Data.Show"],r=(n.Prelude,function(){function n(){}return n.value=new n,n}()),e=function(){function n(){}return n.value=new n,n}(),o=function(){function n(){}return n.value=new n,n}(),i=function(){function n(){}return n.value=new n,n}(),u=function(){function n(){}return n.value=new n,n}(),c=function(){function n(){}return n.value=new n,n}(),f=function(){function n(){}return n.value=new n,n}(),l=function(){function n(){}return n.value=new n,n}(),s=new a.Show(function(n){if(n instanceof r)return"ASCII";if(n instanceof e)return"UTF8";if(n instanceof o)return"UTF16LE";if(n instanceof i)return"UCS2";if(n instanceof u)return"Base64";if(n instanceof c)return"Latin1";if(n instanceof f)return"Binary";if(n instanceof l)return"Hex";throw new Error("Failed pattern match at Node.Encoding (line 19, column 1 - line 19, column 39): "+[n.constructor.name])});t.ASCII=r,t.UTF8=e,t.UTF16LE=o,t.UCS2=i,t.Base64=u,t.Latin1=c,t.Binary=f,t.Hex=l,t.showEncoding=s}(n["Node.Encoding"]=n["Node.Encoding"]||{}),function(t){"use strict";(n["Node.FS.Internal"]=n["Node.FS.Internal"]||{}).unsafeRequireFS=require("fs")}(),function(t){"use strict";var a=n["Node.FS.Internal"],r=(n.Effect,n.Prelude,n["Unsafe.Coerce"].unsafeCoerce);t.mkEffect=r,t.unsafeRequireFS=a.unsafeRequireFS}(n["Node.FS.Internal"]=n["Node.FS.Internal"]||{}),function(t){"use strict";n["Control.Bind"],n["Control.Semigroupoid"],n["Data.DateTime"],n["Data.DateTime.Instant"],n["Data.EuclideanRing"],n["Data.Function"],n["Data.Function.Uncurried"],n["Data.Functor"],n["Data.Int"],n["Data.Maybe"],n["Data.Nullable"];var a=n["Data.Show"],r=(n["Data.Time.Duration"],n.Effect,n["Node.Buffer"],n["Node.Encoding"]),e=(n["Node.FS"],n["Node.FS.Internal"]),o=(n["Node.FS.Perms"],n["Node.FS.Stats"],n["Node.Path"],n.Prelude,e.unsafeRequireFS);t.readTextFile=function(n){return function(t){return e.mkEffect(function(e){return o.readFileSync(t,{encoding:a.show(r.showEncoding)(n)})})}}}(n["Node.FS.Sync"]=n["Node.FS.Sync"]||{}),function(t){"use strict";var a=n["AtCoder.ABC113.B"],r=(n["Control.Applicative"],n["Control.Bind"],n.Effect,n["Effect.Console"]),e=n["Node.Encoding"],o=n["Node.FS.Sync"];n.Prelude;t.main=function(){var n=o.readTextFile(e.UTF8.value)("/dev/stdin")(),t=a.solve(n);return r.log(t)()}}(n.Main=n.Main||{}),n.Main.main();
},{}]},{},["Focm"], null)


function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
    tmp2 = input[1].split(" ");
    tmp3 = input[2].split(" ");
    T = parseInt(tmp2[0]);
    A = parseInt(tmp2[1]);
    var ans;
    var ansAmari=10000000;
	//文字列から10進数に変換するときはparseIntを使います
    for(i = 1;i <= parseInt(input[0]);i++){
        kion = T - parseInt(tmp3[i]) * 0.006;
        amari = A - kion;
        if(ansAmari > amari){
            ans = i;
            ansAmari = amari;
        }
    }
	console.log('%d',ans);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


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 tmp = lines.shift();
    var n = Number(tmp.split(" ")[0]);
    var m = Number(tmp.split(" ")[1]);

    var city = Array(m);
    var result = "";

    for (var i = 0; i < m; i++) {
        tmp = lines[i].split(" ");
        city[i] = {
            "i": i,
            "P": Number(tmp[0]),
            "Y": Number(tmp[1]),
            "KenNum": "",
            "ShiNum": "",
        }
    }

    city.sort(function (a, b) {
        if (a.P < b.P) return -1;
        if (a.P > b.P) return 1;
        if (a.Y < b.Y) return -1;
        if (a.Y > b.Y) return 1;
        return 0;
    });

    var ken  = 1;
    var shi  = 1;
    var loop = 0;

    for (var i=0;i<m;i++) {
        if(ken === city[i].P) {
            city[i].KenNum = ken.toString();
            loop = 6 - ken.toString().length;

            for (var k = 0; k < loop; k++) { city[i].KenNum = "0" + city[i].KenNum; }

            city[i].ShiNum = shi.toString();
            loop = 6 - shi.toString().length;

            for (var k = 0; k < loop; k++) { city[i].ShiNum = "0" + city[i].ShiNum; }
            shi++;
        }
        else{ken++; shi=1; i--;}
    }
    city.sort(function(a,b){return(a.i-b.i)});
    for (var i=0;i<m;i++) {
        console.log(city[i].KenNum+city[i].ShiNum);
    }
});

Score: 300 points

Problem Statement

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

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

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

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

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

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

Find the ID numbers for all the cities.

Note that there can be a prefecture with no cities.

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq P_i \leq N

1 \leq Y_i \leq 10^9

Y_i are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
P_1 Y_1
:
P_M Y_M

Output

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

Sample Input 1

2 3
1 32
2 63
1 12

Sample Output 1

000001000002
000002000001
000001000001

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

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

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

Sample Input 2

2 3
2 55
2 77
2 99

Sample Output 2

000002000001
000002000002
000002000003


function main(input) {
    const args = input.split('\n')
    const args0 = args[0].split(' ')
    const sumPrefecture = +args0[0]
    const sumCity = +args0[1]
    args.shift()

    const cityList = args.map(item => {
        const tmpArry = item.split(' ')
        const belongPrefecture = tmpArry[0]
        const barthYear = tmpArry[1]
        return {pre: +belongPrefecture, year: +barthYear}
    })

    const preList = {}
    for (let i = 1; i <= sumPrefecture; i++) {
        preList[i.toString().padStart(6, '0')] = cityList.filter(item => {
            return item.pre == i
        }).map(item => {
            return item.year
        }).sort(function (a, b) {
            return a - b
        })
    }

    Object.keys(preList).forEach((key, index) => {
        for (let [item, index2] of preList[key].entries()) {
            console.log(key+(+item + 1).toString().padStart(6,'0'))
        }

    })

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


// inputに入力データ全体が入る
function Main(input) {
  inputs = input.split(/\n/);
  // N 個の県, M個の市
  var firstLine = inputs[0]
  var firstLines = firstLine.split(/\s/)
  var n = Number(firstLines[0])
  var m = Number(firstLines[1])

  var prefs = {}
  var prefLineLength = inputs.length - 1 - 1
  for (var i = 0; i < prefLineLength; i++) {
    var prefLine = inputs[i+1]
    var prefLines = prefLine.split(/\s/)
    var p = Number(prefLines[0])
    var y = Number(prefLines[1])
    if (!prefs[p]) {
      prefs[p] = []
    }
    prefs[p].push({i: i, pref: p, year: y})
  }

  var cities = []
  for (var i = 0; i <= n; i++) {
    var pref = prefs[i]
    if (!pref) continue;
    pref.sort(function(a,b) {
      return a.year - b.year;
    })
    for (var j = 0; j < pref.length; j++) {
      pref[j].ID = ("00000"+pref[j].pref).slice(-6)+("00000"+(j+1)).slice(-6)
      cities.push(pref[j])
    }
  }

  cities.sort(function(a, b) {
    return a.i - b.i
  })

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


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

function Main(input){
	var input = input.split('\n');
	var n = toInt(input[0]);
	var as = [];
	for(var i = 0; i < n; i++){
		as[i] = toInt(input[i+1]);
	}

	as.sort((a,b)=>a-b);

	var x = 0;
	var y = 0;
	if(n%2===0){
		for(var i = 0; i < n; i++){
			x += i>=n/2? 2*as[i]: -2*as[i];
		}
		x += as[n/2 -1] - as[n/2];
	}else{
		for(var i = 0; i < n; i++){
			x += i>=(n-1)/2? 2*as[i]: -2*as[i];
			y += i>(n-1)/2? 2*as[i]: -2*as[i];
		}
		x -= as[(n-1)/2] + as[(n+1)/2];
		y += as[(n-1)/2] + as[(n-3)/2];
	}
	var ans = max(x,y);

	//console.log(as,bs)
	console.log(ans);

	return 0;
}

Score : 400 points

Problem Statement

You are given N integers; the i-th of them is A_i.
Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like.

Constraints

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the maximum possible sum of the absolute differences between the adjacent elements after arranging the given integers in a row in any order you like.

Sample Input 1

5
6
8
1
2
3

Sample Output 1

21

When the integers are arranged as 3,8,1,6,2, the sum of the absolute differences between the adjacent elements is |3 - 8| + |8 - 1| + |1 - 6| + |6 - 2| = 21. This is the maximum possible sum.

Sample Input 2

6
3
1
4
1
5
9

Sample Output 2

25

Sample Input 3

3
5
5
1

Sample Output 3

8


function Main(input) {
  input = input.split("\n");
  var n = input[0];
  var ans;
  if(n==1){
    ans="Hello World";
  }else{
    var a= parseInt(input[1]);
    var b= parseInt(input[2]);
    ans=a+b;
  }
  console.log('%s', ans);
}

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

Score: 100 points

Problem Statement

In 2020, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education.

One day, there was an exam where a one-year-old child must write a program that prints Hello World, and a two-year-old child must write a program that receives integers A, B and prints A+B.

Takahashi, who is taking this exam, suddenly forgets his age.

He decides to write a program that first receives his age N (1 or 2) as input, then prints Hello World if N=1, and additionally receives integers A, B and prints A+B if N=2.

Write this program for him.

Constraints

N is 1 or 2.

A is an integer between 1 and 9 (inclusive).

B is an integer between 1 and 9 (inclusive).

Input

Input is given from Standard Input in one of the following formats:

1

2
A
B

Output

If N=1, print Hello World; if N=2, print A+B.

Sample Input 1

1

Sample Output 1

Hello World

As N=1, Takahashi is one year old. Thus, we should print Hello World.

Sample Input 2

2
3
5

Sample Output 2

8

As N=2, Takahashi is two years old. Thus, we should print A+B, which is 8 since A=3 and B=5.


/*
-------関数一覧--------
arr1dto2d(Array) 一次元配列を二次元配列にします
pf(N)因数分解した結果をオブジェクトで返します
gcd(a,b)最大公約数を返します
lcm(a,b)最小公倍数を返します
num(a,b)a-bを返します。ソート用です
isPrime(n)素数かどうか真偽値で返します
isNumber(n)数かどうか真偽値で返します
arrsum(arr)配列の合計値を返します
*/
var inf = Number.MAX_SAFE_INTEGER;
function Main(input){
	input = input.split("\n");
	input = arr1dto2d(input);
	var t = input[0][1];
	var cost = inf;
	for(var i=1;i<input.length;i++){
	   // console.log(input[i],cost)
		if(input[i][0]<cost&&input[i][1]<=t){
			cost = input[i][0];
		}
	}
	console.log(cost==inf?"TLE":cost)
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
function isPrime(n){
    if(false===Number.isInteger(n)){
        return false;
    }
    if(n<=1){
        return false;
    }
    if(2===n){
        return true;
    }
    if(0===n%2){
        return false;
    }
    var square_root = Math.floor(Math.sqrt(n));
    for(var i=3; i<=square_root; i+=2){
        if(0===n%i){
            return false;
        }
    }
    return true;
}
function isNumber(val){
	const pat = /^([1-9]\d*|0)$/;
	return pat.test(val);
}
function arr1dto2d (arr){
	for(var i=0;i<arr.length;i++){
		arr[i]=arr[i].split("");
		}
	return arr;
}
function factorialize(num) {
  if (num === 0) { return 1; }
  return num * factorialize(num-1);
}
function arr1dto2d (arr){
	for(var i=0;i<arr.length;i++){
    arr[i]=arr[i].split(" ").map(Number);
    }
  return arr;
}
function rotate(array) {
  const ROW = array.length;
  const COL = array[0].length;
  const row = ROW-1;
  var a = new Array(COL);
  for (var c=0; c<COL; c++) {
    a[c] = new Array(ROW);
    for (var r=0; r<ROW; r++) {
      a[c][r] = array[row-r][c];
    }
  }
  return a;
}
function part_in(base,push,st){
	for(var i=st,p=0;p<push.length;i++,p++){
		base[i] = push[p];
	}
	return base;
}
function part_reverse(arr,s,g){
	var push = arr.slice(s-1,g);
  push.reverse();
	arr = part_in(arr,push,s-1);
	return arr;
}
function zeroPadding(num,length){
    return (num + '000000000000000000000000000000000').slice(0,length);
}
function arrsum(arr){
    var sum = 0;
    for (var i=0,len=arr.length; i<len; ++i) {
        sum += arr[i]-0;
    };
    return sum;
}
function pf(n) {
    var result = {};

    if (n === 1) {
        return {"1":1}
    }

    var init = 2;

    while (n !== 1) {
        var i = init;
        while (i < Number.MAX_SAFE_INTEGER) {
            if (n % i === 0) {
                n /= i;
                if (!(result[i] > 0)) {
                    result[i] = 0;
                }
                result[i]++;
                break;
            }
            i++;
        }
        init = i;
    }
    return result;
}
function gcd(a, b) {
    if (b === 0){
        return a
    }
    return gcd(b, a % b)
}
function lcm(a,b) {
    var g = (n, m) => m ? g(m, n % m) : n
    return a * b / g(a, b)
}
function num(a, b) {
  return a - b;
}
function nibu(a,searchValue){
	var index = -1;

//調べる左端を表す添字(index)
var left = 0;

//調べる右端を表す添字(index)
var right = a.length-1;

//左端と右端にデータがある間は処理を繰り返す
while(left <= right){

    //左右の真ん中を表す添字(index)
    middle =Math.floor((left +right)/2);

    //真ん中の値と探す値を比較する
    if(a[middle]==searchValue){
        //一致した場合、変数に入れて処理終了
        index = middle;
        break;
    }else if(a[middle]<searchValue){
        //探す値より小さい場合、左側にはもっと小さい値しかないので左端の値を真ん中の値の右に移動する
        left = middle +1;
    }else{
        //探す値より大きい場合、右側にはもっと大きい値しかないので右端の値を真ん中の値の左に移動する
        right = middle -1;
    }
}
if(index!=-1) return true;
else return false;
}

Score : 200 points

Problem Statement

When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.

You, the smartwatch, has found N routes to his home.

If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.

Find the smallest cost of a route that takes not longer than time T.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq T \leq 1000

1 \leq c_i \leq 1000

1 \leq t_i \leq 1000

The pairs (c_i, t_i) are distinct.

Input

Input is given from Standard Input in the following format:

N T
c_1 t_1
c_2 t_2
:
c_N t_N

Output

Print the smallest cost of a route that takes not longer than time T.

If there is no route that takes not longer than time T, print TLE instead.

Sample Input 1

3 70
7 60
1 80
4 50

Sample Output 1

4

The first route gets him home at cost 7.

The second route takes longer than time T = 70.

The third route gets him home at cost 4.

Thus, the cost 4 of the third route is the minimum.

Sample Input 2

4 3
1 1000
2 4
3 1000
4 500

Sample Output 2

TLE

There is no route that takes not longer than time T = 3.

Sample Input 3

5 9
25 8
5 9
4 10
1000 1000
6 1

Sample Output 3

5


function getLines(input){
	return input.split("\n").map((s)=>s.trim())
}
function parseLine(line){
	return line.split(" ").map((s)=>s.trim());
}
function parseLineToInt(line){
	return line.split(" ").map((s)=>parseInt(s.trim()));
}
// parameter "input" gets all data
function Main(input) {
	// the first line is assigned to input[0], the second line is assigned to input[1] similarly.
	input = getLines(input).map(parseLineToInt);
	var n = input[0][0];
	var t=input[0][1];
	input.shift()
	input=input.filter((ct)=>ct[1]<=t)

	if(input.length==0){
		console.log('TLE')
	}else{
		input.sort((a,b)=>a[0]-b[0])
		console.log(input[0][0]);
	}

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


'use strict'

class Main {
  solve() {
    const nm = input.nextIntArr();
    return _.max(Prime.getDivisors(nm[1]).filter(e => e <= nm[1]/nm[0]));
  }
}

class Prime {
  /* 初期化と素数テーブル生成 */
  constructor(n) {
    if (n == null) { n = 100000; }
    const primeTable = [...((new Array(n)).keys())];
    primeTable[0] = false;
    primeTable[1] = false;
    let max = Math.sqrt(n);
    for(let i = 2;i <= max;++i) {
      if (primeTable[i] !== i) continue;
      for (let j = i * i; j < n; j += i) {
        if (primeTable[j] !== j) continue;
        primeTable[j] = i;
      }
    }
    this.size = n;
    this.primeTable = primeTable;
    this.primeList = primeTable.filter((e,i) => e === i);
  }

  /* テーブルに生成した素数の2乗までの素数判定 */
  isPrime(n) {
    if (n < this.size) return this.primeTable[n] === n;
    let max = Math.sqrt(n);
    for (let i = 0; this.primeList[i] <= max; ++i) {
      if (n % this.primeList[i] === 0) return false;
    }
    return true;
  }

  /* 最小の素因数 */
  getMinimumFactor(n) {
    if (n < this.size) return this.primeTable[n];
    let max = Math.sqrt(n);
    for (let i = 0; this.primeList[i] <= max; ++i) {
      if (n % this.primeList[i] === 0) return this.primeList[i];
    }
    return n;
  }

  /* 素因数の取得
   * 上限: テーブルサイズの二乗*/
  getFactor(n) {
    const ret = [];
    let k = n;
    while(!this.isPrime(k)) {
      const p = this.getMinimumFactor(k)
      ret.push(p);
      k /= p;
    }
    ret.push(k);
    return ret;
  }

  /* 素因数テーブル
   * 上限: テーブルサイズ*/
  getFactorTable(n) {
    const factor = this.getFactor(n);
    const maxFactor = factor[factor.length - 1];
    const ret = [];
    for (let i = 0;this.primeList[i] <= maxFactor; ++i) {
      ret[this.primeList[i]] = 0;
    }
    for (const e of factor) { ++ret[e]; }
    return ret;
  }

  /* 約数の個数 */
  getDivisorCount(n) {
    const factor = this.getFactor(n);
    let count = 1;
    let prev = factor[0];
    let factorCount = [];
    for (let i = 1; i < factor.length; ++i) {
      if (factor[i] != prev) {
        factorCount.push(count);
        count = 1;
      }
      else {
        ++count;
      }
      prev = factor[i];
    }
    factorCount.push(count);
    return factorCount.reduce((a,b)=>a * (b+1),1);
  }

  /* 約数の一覧の取得(未ソート) O(√n)*/
  static getDivisors(n) {
    let max = Math.sqrt(n);
    let ret = [];
    if (n % max === 0) {ret.push(max);}
    for(let i = 0; i < max; ++i) {
      if (n % i == 0) {
        ret.push(i);
        ret.push(n / i);
      }
    }
    return ret;
  }
}

const prime = new Prime(1000);
class Underscore {
  sum(arr) { return arr.reduce((a,b)=>a+b); }
  min(arr, func) { if (func == null) {func = (a,b) => a - b} return arr.reduce((a,b) => func(a,b) < 0 ? a : b); }
  max(arr, func) { if (func == null) {func = (a,b) => a - b} return arr.reduce((a,b) => func(a,b) > 0 ? a : b); }
  sort(arr, func) { if (func == null) {func = (a,b) => a - b} return arr.sort(func) }
  range(start, stop, step) {
	if (stop == null) {
	  stop = start || 0;
	  start = 0;
	}
	if (!step) {
	  step = stop < start ? -1 : 1;
	}
	const length = Math.max(Math.ceil((stop - start) / step), 0);
	const range = Array(length);

	for (var idx = 0; idx < length; idx++, start += step) {
	  range[idx] = start;
	}
	return range;
  }

  first (array, n) {
    if (array == null || array.length < 1) return n == null ? void 0 : [];
    if (n == null) return array[0];
    return this.initial(array, array.length - n);
  };

  initial (array, n) { return array.slice.call(array, 0, Math.max(0, array.length - (n == null ? 1 : n))); }

  tail(array, n) { return array.slice.call(array, n == null ? 1 : n); }

  last (array, n) {
    if (n == null) return array[array.length - 1];
    return this.tail(array, Math.max(0, array.length - n));
  }

  /* 累積和 */
  sumArray (arr) { return this.tail(arr.reduce(((a,b,i) => {a.push(b + a[i]); return a}), [0])); }

  binarySearch (array, key, iteratee) {
	const itr = (obj) => (typeof obj === 'object') ? obj[iteratee] : obj;
	const value = itr(obj);
	let low = 0, high = array.length;
	while (low < high) {
	  let mid = Math.floor((low + high) / 2);
	  if (itr(array[mid]) < value) low = mid + 1; else high = mid;
	}
	return low;
  };
}
const _ = new Underscore();

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++];
  }
  /* 1整数 */
  nextInt() { return parseInt(this.nextLine()); }
  /* 一行文字配列 */
  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();

const Out = (output) => {
  let ret;
  if (output == null) return;
  if (output === true) { ret = 'Yes'; }
  else if (output === false) { ret = 'No'; }
  else { ret = output; }
  console.log(ret);
}

Out(new Main().solve());

Score : 400 points

Problem Statement

You are given integers N and M.

Consider a sequence a of length N consisting of positive integers such that a_1 + a_2 + ... + a_N = M. Find the maximum possible value of the greatest common divisor of a_1, a_2, ..., a_N.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

N \leq M \leq 10^9

Input

Input is given from Standard Input in the following format:

N M

Output

Print the maximum possible value of the greatest common divisor of a sequence a_1, a_2, ..., a_N that satisfies the condition.

Sample Input 1

3 14

Sample Output 1

2

Consider the sequence (a_1, a_2, a_3) = (2, 4, 8). Their greatest common divisor is 2, and this is the maximum value.

Sample Input 2

10 123

Sample Output 2

3

Sample Input 3

100000 1000000000

Sample Output 3

10000


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

const list = input.split('');

var newNum = '';

list.forEach((n) => {
  if (n === '1') {
    newNum += '9';
  } else {
    newNum += '1';
  }
});

console.log(Number(newNum));

Score : 100 points

Problem Statement

Cat Snuke is learning to write characters.
Today, he practiced writing digits 1 and 9, but he did it the other way around.

You are given a three-digit integer n written by Snuke.
Print the integer obtained by replacing each digit 1 with 9 and each digit 9 with 1 in n.

Constraints

111 \leq n \leq 999

n is an integer consisting of digits 1 and 9.

Input

Input is given from Standard Input in the following format:

n

Output

Print the integer obtained by replacing each occurrence of 1 with 9 and each occurrence of 9 with 1 in n.

Sample Input 1

119

Sample Output 1

991

Replace the 9 in the ones place with 1, the 1 in the tens place with 9 and the 1 in the hundreds place with 9. The answer is 991.

Sample Input 2

999

Sample Output 2

111


'use strict';

function Main(INPUT) {
    let input = INPUT.split("");
    for (let i = 0; i < input.length; i++) {
        input[i] = input[i] == "9" ? "1" : "9";
    }
    console.log(input.join(""));
}

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


function main(input) {
  var tmp = toString(input);
  for(i=0;i<input.length;i++){
    if(tmp[i] == 9){
      tmp[i] = 1;
    }else{
      tmp[i] = 9;
    }
  }
  console.log(tmp);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const input = require("fs").readFileSync("/dev/stdin", "utf8")
const n = Number(input)
function main(n){
  if(Number.isInteger(n / 111)){
  	return n
  }else{
 	return (Math.floor(n / 111) + 1) * 111
  }
}

console.log(main(n));

Score : 200 points

Problem Statement

Kurohashi has never participated in AtCoder Beginner Contest (ABC).

The next ABC to be held is ABC N (the N-th ABC ever held).
Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.

What is the earliest ABC where Kurohashi can make his debut?

Constraints

100 \leq N \leq 999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If the earliest ABC where Kurohashi can make his debut is ABC n, print n.

Sample Input 1

111

Sample Output 1

111

The next ABC to be held is ABC 111, where Kurohashi can make his debut.

Sample Input 2

112

Sample Output 2

222

The next ABC to be held is ABC 112, which means Kurohashi can no longer participate in ABC 111.
Among the ABCs where Kurohashi can make his debut, the earliest one is ABC 222.

Sample Input 3

750

Sample Output 3

777


function Main(input){
  const n = Number(input[0])
  if(Number.isInteger(n / 111)){
  	return n
  }else{
 	return (Math.floor(n / 111) + 1) * 111
  }
}

console.log('%d %s',main(n));


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 N = lines.shift(); N = Number(N);
    var v = Array(N);
    var counter_g = Array(N).fill(0); var max_g = -1;
    var counter_k = Array(N).fill(0); var max_k = -1;
    var result = 0;

    var tmp = lines[0].split(" ");
    for (var i = 0; i < N; i++) {
        v[i] = Number(tmp[i]);
        i % 2 === 0 ? counter_g[i]++ : counter_k[i]++;
    }

    var g = -1; var k = -1;
    for (var i = 0; i < N; i++) { if (counter_g[i] > max_g) { max_g = counter_g[i]; g = i; } }
    for (var i = 0; i < N; i++) { if (counter_k[i] > max_k && v[i] !== v[g]) { max_k = counter_k[i]; k = i; } }

    if (k === -1) { v[k] = -1; }

    console.log(v[g],v[k])
    for (var i = 0; i < N; i++) {
        if (i % 2 === 0 && v[i] !== v[g]) { result++; }
        if (i % 2 !== 0 && v[i] !== v[k]) { result++; }
    }
    console.log(result);
});

Score : 300 points

Problem Statement

A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied:

For each i = 1,2,..., n-2, a_i = a_{i+2}.

Exactly two different numbers appear in the sequence.

You are given a sequence v_1,v_2,...,v_n whose length is even.
We would like to make this sequence /\/\/\/ by replacing some of its elements.
Find the minimum number of elements that needs to be replaced.

Constraints

2 \leq n \leq 10^5

n is even.

1 \leq v_i \leq 10^5

v_i is an integer.

Input

Input is given from Standard Input in the following format:

n
v_1 v_2 ... v_n

Output

Print the minimum number of elements that needs to be replaced.

Sample Input 1

4
3 1 3 2

Sample Output 1

1

The sequence 3,1,3,2 is not /\/\/\/, but we can make it /\/\/\/ by replacing one of its elements: for example, replace the fourth element to make it 3,1,3,1.

Sample Input 2

6
105 119 105 119 105 119

Sample Output 2

0

The sequence 105,119,105,119,105,119 is /\/\/\/.

Sample Input 3

4
1 1 1 1

Sample Output 3

2

The elements of the sequence 1,1,1,1 are all the same, so it is not /\/\/\/.


// inputに入力データ全体が入る
function Main(input) {
  inp = input.split('\n');
  var N = Number(inp[0]);
  var an = inp[1].split(' ');
  an.map(e => Number(e));

  function chkArray(lt){
    var buf = '';
    var cnt = 0;
    for (var i = 0; i < lt.length; i++) {
      if (i === 0) buf = lt[0];
      if (buf === lt[i]) {
        cnt++;
      }
    }
    return cnt;
  }
  // 配列チェック
  var chkcnt = chkArray(an);
  if (chkcnt === an.length){
    console.log("%d", parseInt(an.length / 2, 10));
    return;
  }

  if (chkcnt === 1 && an.length >= 4){
    console.log("%d", parseInt(an.length / 2, 10));
    return;
  }

  num1 = new Map(); // 配列要素偶数
  num2 = new Map(); // 配列要素奇数
  for (var i = 0; i < an.length; i++) {
    if (i % 2 === 0) {
      var val = num1.get(an[i]);
      if (!val) {
        val = 0;
        num1.set(an[i], val);
      }
      val++;
      num1.set(an[i], val);
    } else {
      var val = num2.get(an[i]);
      if (!val) {
        val = 0;
        num2.set(an[i], val);
      }
      val++;
      num2.set(an[i], val);
    }
  }

  // console.log(num1);
  // console.log(num2);
  function getCnt(numarray) {
    var array = [];
    var cnt = 0;
    for (var tmp of numarray) {
      array.push(tmp[1]); // 連想配列の値を取る
    }
    if (array.length >= 2) {
      array.sort((a, b) => b - a); // 降順ソート
      for (var i = 1; i < array.length; i++) {
        cnt += array[i];
      }
    } else if (array.length <= 1) {
      cnt = 0;
    }
    return cnt;
  }

  var ans = getCnt(num1);
  ans += getCnt(num2);

  console.log("%d", ans);

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


// inputに入力データ全体が入る
function Main(input) {
  inp = input.split('\n');
  var N = Number(inp[0]);
  var an = inp[1].split(' ');
  an.map(e => Number(e));

  function chkArray(lt){
    var buf = '';
    for (var i = 0; i < lt.length; i++) {
      if (i === 0) buf = an[0];
      if (buf !== lt[i]) {
        return true;
      }
    }
    return false;
  }
  // 配列チェック
  if (chkArray(an) === false){
    console.log("%d", parseInt(an.length / 2, 10));
    return;
  }

  num1 = new Map(); // 配列要素偶数
  num2 = new Map(); // 配列要素奇数
  for (var i = 0; i < an.length; i++) {
    if (i % 2 === 0) {
      var val = num1.get(an[i]);
      if (!val) {
        val = 0;
        num1.set(an[i], val);
      }
      val++;
      num1.set(an[i], val);
    } else {
      var val = num2.get(an[i]);
      if (!val) {
        val = 0;
        num2.set(an[i], val);
      }
      val++;
      num2.set(an[i], val);
    }
  }

  // console.log(num1);
  // console.log(num2);
  function getCnt(numarray) {
    var array = [];
    var cnt = 0;
    for (var tmp of numarray) {
      array.push(tmp[1]); // 連想配列の値を取る
    }
    if (array.length >= 2) {
      array.sort((a, b) => b - a); // 降順ソート
      for (var i = 1; i < array.length; i++) {
        cnt += array[i];
      }
    } else if (array.length <= 1) {
      cnt = 0;
    }
    return cnt;
  }

  var ans = getCnt(num1);
  ans += getCnt(num2);

  console.log("%d", ans);

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


"use strict";
function Main(input) {
    let lines = input.split("\n");
    let N = lines.shift() - 0;
    let Vc = lines[0].split(/\s/).map((v) => v - 0);
    let a = {};
    for (let v of Vc) {
        let b = a[v] || 0;
        a[v] = b + 1;
    }
    let c = [];
    for (let v in a) {
        c.push({value:v, count:a[v]});
    }
    c.sort((a, b) => b.count - a.count);

    let ans = 0;
    let n = N / 2;
    for (let v of c) {
        ans += Math.abs(n - v.count);
    }

    console.log(ans);
}

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


function Main(input) {
  input = input.split("\n");
  var S = input[0];
  var T = input[1];
  var ans="Yes";
  while(T.length!=0){
    for(i=1;i<T.length;i++){
      if(T.substr(0,1)==T.substr(i,1)){
        if(S.substr(0,1)!=S.substr(i,1)){
          ans="No";
          break;
        }
      }
      if(S.substr(0,1)==S.substr(i,1)){
        if(T.substr(0,1)!=T.substr(i,1)){
          ans="No";
          break;
        }
      }
    }
    if(ans=="No"){
      break;
    }
    S=S.substr(1);
    T=T.substr(1);
  }

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

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

Score : 300 points

Problem Statement

You are given strings S and T consisting of lowercase English letters.

You can perform the following operation on S any number of times:

Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1.

Determine if S and T can be made equal by performing the operation zero or more times.

Constraints

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

|S| = |T|

S and T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S and T can be made equal, print Yes; otherwise, print No.

Sample Input 1

azzel
apple

Sample Output 1

Yes

azzel can be changed to apple, as follows:

Choose e as c_1 and l as c_2. azzel becomes azzle.

Choose z as c_1 and p as c_2. azzle becomes apple.

Sample Input 2

chokudai
redcoder

Sample Output 2

No

No sequences of operation can change chokudai to redcoder.

Sample Input 3

abcdefghijklmnopqrstuvwxyz
ibyhqfrekavclxjstdwgpzmonu

Sample Output 3

Yes


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

   a.sort();

   var cnt = 0;

   for (i=0;i<n;i++){if (x  >=　a[i] ){ x =x-a[i];
                                   // console.log(x);
                                    cnt = cnt +1;}
                                    else{break;}

                                   }
   // console.log(x,i,n);
    if (x>0　&&　i==n) {cnt=cnt-1;}

    console.log(cnt);

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

Score : 200 points

Problem Statement

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

Snuke has decided to distribute x sweets among them.
He needs to give out all the x sweets, but some of the children may get zero sweets.

For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets.
Snuke is trying to maximize the number of happy children by optimally distributing the sweets.
Find the maximum possible number of happy children.

Constraints

All values in input are integers.

2 \leq N \leq 100

1 \leq x \leq 10^9

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Print the maximum possible number of happy children.

Sample Input 1

3 70
20 30 10

Sample Output 1

2

One optimal way to distribute sweets is (20, 30, 20).

Sample Input 2

3 10
20 30 10

Sample Output 2

1

The optimal way to distribute sweets is (0, 0, 10).

Sample Input 3

4 1111
1 10 100 1000

Sample Output 3

4

The optimal way to distribute sweets is (1, 10, 100, 1000).

Sample Input 4

2 10
20 20

Sample Output 4

0

No children will be happy, no matter how the sweets are distributed.


"use strict";
const s = require("fs").readFileSync("/dev/stdin", "utf8");
const n = parseInt(s.split("\n")[0].split(" ")[0], 10);
let x = parseInt(s.split("\n")[0].split(" ")[1], 10);
let a = s.split("\n")[1].split(" ").map(e => parseInt(e, 10)).sort((a, b) => a - b);
let cnt = 0;
for (let i = 0; i < n; i++) {
  if (x >= a[i]) {
    x -= a[i];
    cnt++;
  } else {
    break;
  }
}
if (x > 0 && cnt >= n) {
  cnt--;
}
console.log(cnt);


function main(arg) {
    arg = arg.split("\n")
    var x = parseInt(arg[0].split(" ")[1], 10)
    var ai = arg[1].split(" ").map((e) => parseInt(e, 10))

    ai.sort((a,b) => {
        if (a > b) {return 1}
        return -1
    })

    var count = ai.slice()
    count.fill(0)
    var max = x

    var min = Math.min.apply(null, ai)

    for(;;) {
        if (max < min) {
            break;
        }

        for (var i = 0; i < ai.length; i++) {
            if((max - ai[i]) >= 0) {
                max -= ai[i]
                count[i] ++
            }
        }

        if(max <= 0) {
            break;
        }
    }

    var count2 = 0
    count.forEach((e) => {
        if(1 === e) {
            count2++
        }
    })

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


function Main(input){
var K = input.trim();
K =parseInt(K,10);
var a,b;
if(K%2==1){
  a = Math.floor(K/2);
  b = K - a;
  console.log(a*b);
}else{
  console.log((K*K)/4);
}
}
  Main(require('fs').readFileSync('/dev/stdin','utf8'));

Score : 100 points

Problem Statement

Find the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). The order does not matter.

Constraints

2\leq K\leq 100

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive).

Sample Input 1

3

Sample Output 1

2

Two pairs can be chosen: (2,1) and (2,3).

Sample Input 2

6

Sample Output 2

9

Sample Input 3

11

Sample Output 3

30

Sample Input 4

50

Sample Output 4

625


console.log((args=>{
  const [[N,k],x] = args.trim().split`\n`.map(r=>r.split` `.map(v=>v|0));
  const K = k-1;
  let min = Infinity;
  for ( let i = 0; i+K < N; i++ ) {
    if ( x[i] < 0 && 0 < x[i+K] ) {
      min = Math.min( min, x[i+K] - x[i] + Math.min(x[i+K],-x[i]) );
    } else if ( x[i] >= 0 ) min = Math.min( min, x[i+K] );
    else if ( x[i+K] <= 0 ) min = Math.min( min, -x[i] );
  }
  return `${min}`;
})(require('fs').readFileSync('/dev/stdin', 'utf8')));

Score : 300 points

Problem Statement

There are N candles placed on a number line.
The i-th candle from the left is placed on coordinate x_i.
Here, x_1 < x_2 < ... < x_N holds.

Initially, no candles are burning.
Snuke decides to light K of the N candles.

Now, he is at coordinate 0.
He can move left and right along the line with speed 1.
He can also light a candle when he is at the same position as the candle, in negligible time.

Find the minimum time required to light K candles.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

x_i is an integer.

|x_i| \leq 10^8

x_1 < x_2 < ... < x_N

Input

Input is given from Standard Input in the following format:

N K
x_1 x_2 ... x_N

Output

Print the minimum time required to light K candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate 0 to -10.

Light the second candle from the left.

Move from coordinate -10 to 10.

Light the third candle from the left.

Move from coordinate 10 to 20.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate 0.

Sample Input 4

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

Sample Output 4

10


// 与えられたXの部分配列を用意、距離の値を算出
//それだと
// 最大でN^2になるナ10^2^5=10^10で確実に死ぬ
//k*(n-k)でkはn以下という制約があるので死ぬとは限らんな

function get_run_length(xs){
  const max = xs[xs.length-1];
  const min=xs[0]
  var result = 0;

  if(max > min*-1){
    result = min*-2 + max;
  }else{
    result = min*-1 + max*2;
  }

  if(min>=0){result = max;}
  if(max<=0){result = min*-1;}

  return result;
}

function main(input){
  const lines = input.split('\n');
  const N = parseInt(lines[0].split(' ')[0]);
  const K = parseInt(lines[0].split(' ')[1]);
  const Xs = lines[1].split(' ').map(x => parseInt(x))

  var result = 1000000;
  for(var i=0;i<N-K+1;i++){
    var part_xs = Xs.slice(i,i+K)
   var tmp = get_run_length(part_xs);
    result = Math.min(tmp, result);
//    console.log([i,result]);
  }

  if(result==0){result=0;}
  console.log(result);
}

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


function gets(str){
  this._s = str.split("\n");
  this._y = 0;
};
gets.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;
  },
  l: function(f){
    var s = this._s[this._y++].split(" ");
    return f?s:s.map(a=>+a);
  },
  m: function(n,f){
    var s = this._s, y = this._y, r = [], i = 0;
    if(f)for(;i < n; i++)r[i] = s[y+i].split(" ");
    else for(;i < n; i++)r[i] = s[y+i].split(" ").map(a=>+a);
    this._y += n;
    return r;
  },
};
var o=new gets(require("fs").readFileSync("/dev/stdin","utf8"));

console.log(main());
function main(){
  var n = o.a();
  var a = o.l();
  var b = [];
  if(n <= 2)return Math.max(...a);
  for(var i = 0; i < n-1; i++)b[i] = Math.max(a[i],a[i+1]);
  a = a.concat(b);
  return middle(a);

  function middle(a){
    a.sort((a,b)=>a-b);
    return a[a.length>>1];
  }
}

Score : 700 points

Problem Statement

We will define the median of a sequence b of length M, as follows:

Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.

For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.

Snuke comes up with the following problem.

You are given a sequence a of length N.
For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a.
We will list m_{l, r} for all pairs (l, r) to create a new sequence m.
Find the median of m.

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 median of m.

Sample Input 1

3
10 30 20

Sample Output 1

30

The median of each contiguous subsequence of a is as follows:

The median of (10) is 10.

The median of (30) is 30.

The median of (20) is 20.

The median of (10, 30) is 30.

The median of (30, 20) is 30.

The median of (10, 30, 20) is 20.

Thus, m = (10, 30, 20, 30, 30, 20) and the median of m is 30.

Sample Input 2

1
10

Sample Output 2

10

Sample Input 3

10
5 9 5 9 8 9 3 5 4 3

Sample Output 3

8


function Main(input){
var inputs =input.split(" ");
var A = parseInt(inputs[0],10);
var B = parseInt(inputs[1],10);
var answer = (A-1)*(B-1);
console.log(answer);

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

Score: 100 points

Problem Statement

There is a farm whose length and width are A yard and B yard, respectively. A farmer, John, made a vertical road and a horizontal road inside the farm from one border to another, as shown below: (The gray part represents the roads.)

What is the area of this yard excluding the roads? Find it.

Note

It can be proved that the positions of the roads do not affect the area.

Constraints

A is an integer between 2 and 100 (inclusive).

B is an integer between 2 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

A B

Output

Print the area of this yard excluding the roads (in square yards).

Sample Input 1

2 2

Sample Output 1

1

In this case, the area is 1 square yard.

Sample Input 2

5 7

Sample Output 2

24

In this case, the area is 24 square yards.


function main(lines) {
    const input = lines.split('\n').map(Number)[0]
    var count = 0
    for(var i=1; i<=input; i++){
        if(input%i === 0 && i%2 === 1){
            var tmpCount = 0;
            for(var k=1; k<=i; k++){
                if(i%k === 0){
                    tmpCount++
                }
            }
            if(tmpCount === 8){
                count++
            }
        }
    }
    console.log(count)
}

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

Score: 200 points

Problem Statement

The number 105 is quite special - it is odd but still it has eight divisors.
Now, your task is this: how many odd numbers with exactly eight positive divisors are there between 1 and N (inclusive)?

Constraints

N is an integer between 1 and 200 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print the count.

Sample Input 1

105

Sample Output 1

1

Among the numbers between 1 and 105, the only number that is odd and has exactly eight divisors is 105.

Sample Input 2

7

Sample Output 2

0

1 has one divisor. 3, 5 and 7 are all prime and have two divisors. Thus, there is no number that satisfies the condition.


_dividers = function(n) {
  var arr = []
  for (var i = 1; i*i <= n; i++) {
     if (n % i === 0) {
       arr.push(i)
       if ( i != n / i) {
         arr.push(n / i)
       }
     }
  }
  return arr.sort((a, b) => a - b)
}

inp = require('fs').readFileSync('/dev/stdin', 'utf8').split('\n')
N = inp.shift() * 1
cnt = 0
for (i=1; i<=N; i+=2) {
    if (_dividers(i).length == 8) {
        cnt++
    }
}
console.log(cnt)


'use strict'

const main = (input) => {
    const s = input.split('\n')[0]
    const k = parseInt(input.split('\n')[1])

    for(let i = 0; i < k; i++){
        if(s[i] !== '1'){
            console.log(s[i])
            return
        }
    }
    console.log('1')
}

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

Score: 300 points

Problem Statement

Mr. Infinity has a string S consisting of digits from 1 to 9. Each time the date changes, this string changes as follows:

Each occurrence of 2 in S is replaced with 22. Similarly, each 3 becomes 333, 4 becomes 4444, 5 becomes 55555, 6 becomes 666666, 7 becomes 7777777, 8 becomes 88888888 and 9 becomes 999999999. 1 remains as 1.

For example, if S is 1324, it becomes 1333224444 the next day, and it becomes 133333333322224444444444444444 the day after next.
You are interested in what the string looks like after 5 \times 10^{15} days. What is the K-th character from the left in the string after 5 \times 10^{15} days?

Constraints

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

K is an integer between 1 and 10^{18} (inclusive).

The length of the string after 5 \times 10^{15} days is at least K.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the K-th character from the left in Mr. Infinity's string after 5 \times 10^{15} days.

Sample Input 1

1214
4

Sample Output 1

2

The string S changes as follows:

Now: 1214

After one day: 12214444

After two days: 1222214444444444444444

After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444

The first five characters in the string after 5 \times 10^{15} days is 12222. As K=4, we should print the fourth character, 2.

Sample Input 2

3
157

Sample Output 2

3

The initial string is 3. The string after 5 \times 10^{15} days consists only of 3.

Sample Input 3

299792458
9460730472580800

Sample Output 3

2


'use strict'

const main = (input) => {
    const s = input.split('\n')[0]
    const k = parseInt(input.split('\n')[1])

    for(let i = 0; i <= k; i++){
        if(s[i] !== '1'){
            console.log(s[i])
            return
        }
    }
    console.log('1')
}

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


'use strict'
const lines = require('fs').readFileSync(0, 'utf8').split('\n')
const nmq = lines[0].split(' ')
const N = parseInt(nmq[0], 10)
const M = parseInt(nmq[1], 10)
const Q = parseInt(nmq[2], 10)
const LRs = []
for (let i=1;i <= M;i++) {
  const LR = lines[i].split(' ')
  LRs.push({L: parseInt(LR[0], 10), R: parseInt(LR[1], 10)})
}
for (let i=M+1;i <= M+Q;i++) {
  const pq = lines[i].split(' ')
  const p = parseInt(pq[0], 10)
  const q = parseInt(pq[1], 10)
  let count = 0
  for (const LR of LRs) {
    if (p <= LR.L && LR.R <= q) count++
  }
  console.log(count)
}

Score: 400 points

Problem Statement

In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east.
A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i).
Takahashi the king is interested in the following Q matters:

The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.

Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.

Constraints

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

M is an integer between 1 and 200 \ 000 (inclusive).

Q is an integer between 1 and 100 \ 000 (inclusive).

1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)

1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q

Output

Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.

Sample Input 1

2 3 1
1 1
1 2
2 2
1 2

Sample Output 1

3

As all the trains runs within the section from City 1 to City 2, the answer to the only query is 3.

Sample Input 2

10 3 2
1 5
2 8
7 10
1 7
3 10

Sample Output 2

1
1

The first query is on the section from City 1 to 7. There is only one train that runs strictly within that section: Train 1.
The second query is on the section from City 3 to 10. There is only one train that runs strictly within that section: Train 3.

Sample Input 3

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

Sample Output 3

7
9
10
6
8
9
6
7
8
10


'use strict'

const Main = (input) => {
    const lines = input.split('\r\n')
    const N = Number(lines[0].split(' ')[0])
    const M = Number(lines[0].split(' ')[1])
    const Q = Number(lines[0].split(' ')[2])

    const L = []
    const R = []
    for(let i = 1; i <= M; i++) {
        L.push(Number(lines[i].split(' ')[0]));
        R.push(Number(lines[i].split(' ')[1]));
    }
    for(let i = M + 1; i <= M+Q; i++) {
        const p = Number(lines[i].split(' ')[0])
        const q = Number(lines[i].split(' ')[1])
        const start = L.map((v, index) => {
            if(v >= p){
                return index
            }
            return -1
        }).filter(v => v >= 0)

        const ans = start.filter(v => R[v] <= q)
        console.log(ans.length);
    }
}

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


const main = function(input){
  var nums = input.trim().split(" ").map(i=>parseInt(i));
  var n = nums[0];
  var k = nums[1];
  var ans = 1;

  if(k<=n && n%k ===0){
  	ans = 0;
  }

  console.log(ans);

}

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

Score : 100 points

Problem Statement

Takahashi has decided to distribute N AtCoder Crackers to K users of as evenly as possible.
When all the crackers are distributed, find the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Constraints

1 \leq N,K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Sample Input 1

7 3

Sample Output 1

1

When the users receive two, two and three crackers, respectively, the (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user, is 1.

Sample Input 2

100 10

Sample Output 2

0

The crackers can be distributed evenly.

Sample Input 3

1 1

Sample Output 3

0


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

	var n = parseInt(tmp[0], 10);
	var k = parseInt(tmp[1], 10);
	var ans;

        ans = 1;
if(n%k==0){ans=0}

	console.log('%d',ans);
}

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


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

  var a = parseInt(splitInput[0], 10);
  var b = parseInt(splitInput[1], 10);

  console.log(Math.floor(a / b));
}

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


// C: Base -2
"use strict";

const DEBUG_MODE = false;
const rawInput = DEBUG_MODE
  ? "-9"
  : require("fs")
    .readFileSync("/dev/stdin", "utf8")
    .trim();

const process = inputRaw => {
  let input = parseInt(inputRaw);
  let result = "";

  while (input !== 0) {
    let remainder = input % -2;
    input = parseInt(input / -2);

    if (remainder < 0) {
      remainder *= -1;
      input += 1;
    }

    result = Number(remainder).toString() + result;
  }

  console.log(result);
};

process(rawInput);

Score : 300 points

Problem Statement

Given an integer N, find the base -2 representation of N.

Here, S is the base -2 representation of N when the following are all satisfied:

S is a string consisting of 0 and 1.

Unless S = 0, the initial character of S is 1.

Let S = S_k S_{k-1} ... S_0, then S_0 \times (-2)^0 + S_1 \times (-2)^1 + ... + S_k \times (-2)^k = N.

It can be proved that, for any integer M, the base -2 representation of M is uniquely determined.

Constraints

Every value in input is integer.

-10^9 \leq N \leq 10^9

Input

Input is given from Standard Input in the following format:

N

Output

Print the base -2 representation of N.

Sample Input 1

-9

Sample Output 1

1011

As (-2)^0 + (-2)^1 + (-2)^3 = 1 + (-2) + (-8) = -9, 1011 is the base -2 representation of -9.

Sample Input 2

123456789

Sample Output 2

11000101011001101110100010101

Sample Input 3

0

Sample Output 3

0


function Main(s){
  var n = +s;
  if(n === 0){console.log(0);return;}
  var ans = [], i = 1, j = 1;
  while(n && Math.abs(n) < 9e9){
    if(Math.abs(n) & i){
      ans.push(1);
      n -= j;
    }
    else ans.push(0);
    i *= 2;
    j *= -2;
  }
  console.log(ans.reverse().join(""));
}

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


var lines = []; var result = 0;
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 N = n(lines[0], 0)
    var M = n(lines[0], 1)

    var A = lines[1].split(" ").map(value => Number(value));

    var sum = []; sum[0] = 0;
    for (var i = 0; i < N; i++) { sum[i + 1] = (sum[i] + A[i]) % M; }

    var ans = 0; counter = {}
    for (var i = 0; i < sum.length; i++) {
        if (counter[sum[i]] === undefined) { counter[sum[i]] = 0 ;}

        ans += counter[sum[i]];
        counter[sum[i]]++;
    }

    console.log(ans);
});

function n(s, n) {
    return (Number(s.split(" ")[n]));
}

Score : 400 points

Problem Statement

There are N boxes arranged in a row from left to right. The i-th box from the left contains A_i candies.

You will take out the candies from some consecutive boxes and distribute them evenly to M children.

Such being the case, find the number of the pairs (l, r) that satisfy the following:

l and r are both integers and satisfy 1 \leq l \leq r \leq N.

A_l + A_{l+1} + ... + A_r is a multiple of M.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

2 \leq M \leq 10^9

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the number of the pairs (l, r) that satisfy the conditions.

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

Sample Input 1

3 2
4 1 5

Sample Output 1

3

The sum A_l + A_{l+1} + ... + A_r for each pair (l, r) is as follows:

Sum for (1, 1): 4

Sum for (1, 2): 5

Sum for (1, 3): 10

Sum for (2, 2): 1

Sum for (2, 3): 6

Sum for (3, 3): 5

Among these, three are multiples of 2.

Sample Input 2

13 17
29 7 5 7 9 51 7 13 8 55 42 9 81

Sample Output 2

6

Sample Input 3

10 400000000
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

25


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

function Main(input){
	var input = input.split('\n');
	var nm = toIntArr(input[0].split(' '));
	var n = nm[0];
	var m = nm[1];
	var as = toIntArr(input[1].split(' '));
	var sums = [];
	sums[-1] = 0;
	for(var i = 0; i < n; i++){
		sums[i] = (sums[i-1] + as[i])%m;
	}
	var ans = 0;
	for(var l = 0; l < n; l++){
		for(var r = l; r < n; r++){
			if((sums[r]-sums[l-1])%m===0)ans++;
		}
	}
	console.log(ans);

}


if(R<1200){
	console.log("ABC");
}
if else(R<2800){
	console.log("ARC");
}
else{
console.log("AGC")}

Score : 100 points

Problem Statement

A programming competition site AtCode regularly holds programming contests.

The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200.

The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800.

The contest after the ARC is called AGC, which is rated for all contestants.

Takahashi's rating on AtCode is R. What is the next contest rated for him?

Constraints

0 ≤ R ≤ 4208

R is an integer.

Input

Input is given from Standard Input in the following format:

R

Output

Print the name of the next contest rated for Takahashi (ABC, ARC or AGC).

Sample Input 1

1199

Sample Output 1

ABC

1199 is less than 1200, so ABC will be rated.

Sample Input 2

1200

Sample Output 2

ARC

1200 is not less than 1200 and ABC will be unrated, but it is less than 2800 and ARC will be rated.

Sample Input 3

4208

Sample Output 3

AGC


// parameter "input" gets all data
function Main(input) {
  var result = 'AC';

  if (input.charAt(0) != 'A') {
    result = 'WA';
  }

  var cFound = false;
  for (var i = 1; i < input.length; i++) {
    if (input.charAt(i) === 'C') {
      if (i === 1 || i === input.length - 1 || cFound) {
        result = 'WA';
      } else {
        cFound = true;
      }
    } else if (input.charAt(i).match(/[A-Z]/)) {
        result = 'WA';
    }
  }

  if (cFound === false) {
    result = 'WA';
  }

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

Score : 200 points

Problem Statement

You are given a string S. Each character of S is uppercase or lowercase English letter.
Determine if S satisfies all of the following conditions:

The initial character of S is an uppercase A.

There is exactly one occurrence of C between the third character from the beginning and the second to last character (inclusive).

All letters except the A and C mentioned above are lowercase.

Constraints

4 ≤ |S| ≤ 10 (|S| is the length of the string S.)

Each character of S is uppercase or lowercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

If S satisfies all of the conditions in the problem statement, print AC; otherwise, print WA.

Sample Input 1

AtCoder

Sample Output 1

AC

The first letter is A, the third letter is C and the remaining letters are all lowercase, so all the conditions are satisfied.

Sample Input 2

ACoder

Sample Output 2

WA

The second letter should not be C.

Sample Input 3

AcycliC

Sample Output 3

WA

The last letter should not be C, either.

Sample Input 4

AtCoCo

Sample Output 4

WA

There should not be two or more occurrences of C.

Sample Input 5

Atcoder

Sample Output 5

WA

The number of C should not be zero, either.


'use strict';
function main(arg) {
    // 処理
    arg = arg[0]
  	if (arg[0] != "A") {
        console.log('WA')
        return
    }

    var numC = 0
    for(var i = 1; i < arg.length; i++){
        if(i >= 2 && i <= arg.length - 2 && arg[i] == "C"){
            numC++;
            if(numC > 1){
                console.log("WA");
                return 0;
            }
        }else if(arg[i].search(/[a-z]/) == -1){
            console.log("WA");
            return 0;
        }
    }
  	if(numC != 1){
        console.log("WA")
    } else {
        console.log('AC')
    }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(arg) {
    // 処理

    if (arg[0] === 'A') {
        arg[0] = 'a'
        var top = arg.slice(0,2)
        var tmp = arg.slice(2, -2)
        var bot = arg.slice(-2)
        if (tmp.split("C").length === 2) {
            var text = top + tmp.split("C").join("c") + bot
            if (!text.match(/^[A-Z]+$/) || arg.length === 4){
                console.log('AC')
                return
            }
        }
    }
    console.log('WA')
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (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 D = one[0];
  var G = one[1] / 100;
  var plist = new Array(D);
  var blist = new Array(D);
  for(var i = 0; i < D; i++){
    var tmp = nextIntArray();
    plist[i] = tmp[0];
    blist[i] = tmp[1] / 100;
  }

  var min = 10000;
  var dp = new Array(G + 1).fill(min);
  //dp[i] = i点の時の最小正答数
  dp[0] = 0;
  for(var i = 0; i < D; i++){
    var count = plist[i];
    var bonus = blist[i];
    for(var j = G - 1; j >= 0; j--){
      for(var k = 1; k <= count; k++){
        var check = j + k * (i + 1);
        if(k == count){
          check += bonus;
        }
        var t = Math.min(G, check);
        dp[t] = Math.min(dp[t], dp[j] + k);
      }
    }
  }

  myout(dp[G]);
}

Score : 300 points

Problem Statement

A programming competition site AtCode provides algorithmic problems.
Each problem is allocated a score based on its difficulty.
Currently, for each integer i between 1 and D (inclusive), there are p_i problems with a score of 100i points.
These p_1 + … + p_D problems are all of the problems available on AtCode.

A user of AtCode has a value called total score.
The total score of a user is the sum of the following two elements:

Base score: the sum of the scores of all problems solved by the user.

Perfect bonuses: when a user solves all problems with a score of 100i points, he/she earns the perfect bonus of c_i points, aside from the base score (1 ≤ i ≤ D).

Takahashi, who is the new user of AtCode, has not solved any problem.
His objective is to have a total score of G or more points.
At least how many problems does he need to solve for this objective?

Constraints

1 ≤ D ≤ 10

1 ≤ p_i ≤ 100

100 ≤ c_i ≤ 10^6

100 ≤ G

All values in input are integers.

c_i and G are all multiples of 100.

It is possible to have a total score of G or more points.

Input

Input is given from Standard Input in the following format:

D G
p_1 c_1
:
p_D c_D

Output

Print the minimum number of problems that needs to be solved in order to have a total score of G or more points. Note that this objective is always achievable (see Constraints).

Sample Input 1

2 700
3 500
5 800

Sample Output 1

3

In this case, there are three problems each with 100 points and five problems each with 200 points. The perfect bonus for solving all the 100-point problems is 500 points, and the perfect bonus for solving all the 200-point problems is 800 points. Takahashi's objective is to have a total score of 700 points or more.

One way to achieve this objective is to solve four 200-point problems and earn a base score of 800 points. However, if we solve three 100-point problems, we can earn the perfect bonus of 500 points in addition to the base score of 300 points, for a total score of 800 points, and we can achieve the objective with fewer problems.

Sample Input 2

2 2000
3 500
5 800

Sample Output 2

7

This case is similar to Sample Input 1, but the Takahashi's objective this time is 2000 points or more. In this case, we inevitably need to solve all five 200-point problems, and by solving two 100-point problems additionally we have the total score of 2000 points.

Sample Input 3

2 400
3 500
5 800

Sample Output 3

2

This case is again similar to Sample Input 1, but the Takahashi's objective this time is 400 points or more. In this case, we only need to solve two 200-point problems to achieve the objective.

Sample Input 4

5 25000
20 1000
40 1000
50 1000
30 1000
1 1000

Sample Output 4

66

There is only one 500-point problem, but the perfect bonus can be earned even in such a case.