function Main(input) {
    var C = 1e+9 + 7;
    var C2 = 1e+5;
    input = input.trim().split("\n").map(function(x) { return x.split(" ")});
    var N = parseInt(input[0][0], 10);
    var K = parseInt(input[0][1], 10);
    var vec_A = input[1].map(e => parseInt(e, 10));
    vec_A.sort((a, b) => Math.abs(b) - Math.abs(a));

    var ans = calc(vec_A, N, K, C, C2);
    console.log(mod(ans, C));

}

function calc(vec_A, N, K, C, C2){
    var ans = 1;
    var minusCount = 0;
    var minPlus;
    var minMinus;
    for (var i = 0; i < K; i++){
        ans = kakeruR(ans, vec_A[i], C, C2);
        if (ans === 0) return 0
        if (vec_A[i] > 0) minPlus = i;
        if (vec_A[i] < 0) {
            minMinus = i;
            minusCount ++;
        }
    }
    if (K === N) return ans;
    if (minusCount % 2 === 0) return ans;

    if (minusCount < K) {
        // console.log("here", minMinus, minPlus);
        var tmp01 = [0, -1];
        var tmp02 = [0, -1];
        for (var i = K; i < N; i++){
            if (vec_A[i] < 0){
                tmp01 = [vec_A[i], vec_A[minPlus], i];
                break;
            }
        }
        for (var i = K; i < N; i++){
            if (vec_A[i] > 0){
                tmp02 = [vec_A[i], vec_A[minMinus], i];
                break;
            }
        }
        if (tmp01[0] * tmp02[1] >= tmp02[0] * tmp01[1]){

            vec_A.splice(K, tmp01[2] - K);
            vec_A.splice(minPlus, 1);
        } else {
            vec_A.splice(K, tmp02[2] - K);
            vec_A.splice(minMinus, 1);
        }
        // console.log(vec_A);

        ans = 1;
        for (var i = 0; i < K; i++){
            ans = kakeruR(ans, vec_A[i], C, C2);
            if (ans === 0) return 0
        }
        return ans;
    } else {
        // console.log("there");
        for (var i = K; i < N; i++){
            if (vec_A[i] >= 0){
                vec_A.splice(K, i - K);
                vec_A.splice(minMinus, 1);
                ans = 1;
                for (var i = 0; i < K; i++){
                    ans = kakeruR(ans, vec_A[i], C, C2);
                    if (ans === 0) return 0
                }
                return ans;
            }
        }
        // console.log("reached?");
        ans = 1;
        for (var i = N - 1; i >= (N - K); i--){
            ans = kakeruR(ans, vec_A[i], C, C2);
        }
        return ans;
    }
}

function kakeruR(a, b, C, C2){
	var tmpQ, tmpR, ans;
  	tmpQ =  (b / C2 | 0);
    tmpR =  b - (tmpQ * C2);
    ans = (a * tmpQ % C) * C2 % C + (a * tmpR);
  	ans %= C;
  return ans;
}

function mod(i, j) {
    return (i % j) < 0 ? (i % j) + 0 + (j < 0 ? -j : j) : (i % j + 0);
}

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

Score : 500 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

We will choose exactly K of these elements. Find the maximum possible product of the chosen elements.

Then, print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Constraints

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

|A_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 \ldots A_N

Output

Print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Sample Input 1

4 2
1 2 -3 -4

Sample Output 1

12

The possible products of the two chosen elements are 2, -3, -4, -6, -8, and 12, so the maximum product is 12.

Sample Input 2

4 3
-1 -2 -3 -4

Sample Output 2

1000000001

The possible products of the three chosen elements are -24, -12, -8, and -6, so the maximum product is -6.

We print this value modulo (10^9+7), that is, 1000000001.

Sample Input 3

2 1
-1 1000000000

Sample Output 3

1000000000

The possible products of the one chosen element are -1 and 1000000000, so the maximum product is 1000000000.

Sample Input 4

10 10
1000000000 100000000 10000000 1000000 100000 10000 1000 100 10 1

Sample Output 4

999983200

Be sure to print the product modulo (10^9+7).


console.log((args=>{
  const [[N,K],A] = args.trim().split('\n').map( r=>r.split(' ').map(v=>v|0) );
  let Am = [], Ap = [];
  for ( let i = 0; i < N; i++ ) {
    if ( A[i] > 0 ) Ap.push(A[i]);
    if ( A[i] < 0 ) Am.push(A[i]);
  }
  const MOD = BigInt(1e9+7), mul = (a,b) => (BigInt(a)*BigInt(b)%MOD+MOD)%MOD;
  Am.sort((a,b)=>a-b);
  Ap.sort((a,b)=>b-a);
  if ( Ap.length === 0 && K&1 ) return `${ Am.slice(-K).reduce(mul,1) }`;
  let om = 0, op = 0, ap = [], am = [];
  for ( let i = 0; i < K; i++ ) {
    if ( (Ap[op]|0) > -(Am[om]|0) ) {
      ap.push(Ap[op]); op++;
    } else {
      am.push(Am[om]); om++;
    }
  }
  if ( am.length&1 ) {
    if ( (Ap[op]|0) > -(Am[om]|0) ) {
      ap.push(Ap[op]); am.pop();
    } else {
      am.push(Am[om]); ap.pop();
    }
  }
  return `${mul(ap.reduce(mul,1),am.reduce(mul,1))}`;
})(require('fs').readFileSync('/dev/stdin', 'utf8')));

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.


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

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

function main(){
  var n = next();
  var ans = n * (n+1) * (n+2) / 6;
  for(var i = 1; i < n; i++){
    var u = next(), v = next();
    if(u > v){var temp = u; u = v; v = temp;}
    ans -= u * (n-v+1);
  }
  return ans;
}

Score : 600 points

Problem Statement

We have a tree with N vertices and N-1 edges, respectively numbered 1, 2,\cdots, N and 1, 2, \cdots, N-1. Edge i connects Vertex u_i and v_i.

For integers L, R (1 \leq L \leq R \leq N), let us define a function f(L, R) as follows:

Let S be the set of the vertices numbered L through R. f(L, R) represents the number of connected components in the subgraph formed only from the vertex set S and the edges whose endpoints both belong to S.

Compute \sum_{L=1}^{N} \sum_{R=L}^{N} f(L, R).

Constraints

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

1 \leq u_i, v_i \leq N

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

Output

Print \sum_{L=1}^{N} \sum_{R=L}^{N} f(L, R).

Sample Input 1

3
1 3
2 3

Sample Output 1

7

We have six possible pairs (L, R) as follows:

For L = 1, R = 1, S = \{1\} and we have 1 connected component.

For L = 1, R = 2, S = \{1, 2\} and we have 2 connected components.

For L = 1, R = 3, S = \{1, 2, 3\} and we have 1 connected component, since S contains both endpoints of each of the edges 1, 2.

For L = 2, R = 2, S = \{2\} and we have 1 connected component.

For L = 2, R = 3, S = \{2, 3\} and we have 1 connected component, since S contains both endpoints of Edge 2.

For L = 3, R = 3, S = \{3\} and we have 1 connected component.

The sum of these is 7.

Sample Input 2

2
1 2

Sample Output 2

3

Sample Input 3

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

Sample Output 3

113


function Main(input) {
	input = input.split("\n");
	input2 = input[1].split(" ");

  	var a = input[0].split("");
	var b = input2[0].split("");
  	var count = 0;

  	a.forEach((item, i) => {
      if(a[i] !== b[i]) {
        count++;
      }
    });

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

Score : 200 points

Problem Statement

Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so.

Operation: Choose one character of S and replace it with a different character.

Constraints

S and T have lengths between 1 and 2\times 10^5 (inclusive).

S and T consists of lowercase English letters.

S and T have equal lengths.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the answer.

Sample Input 1

cupofcoffee
cupofhottea

Sample Output 1

4

We can achieve the objective in four operations, such as the following:

First, replace the sixth character c with h.

Second, replace the eighth character f with t.

Third, replace the ninth character f with t.

Fourth, replace the eleventh character e with a.

Sample Input 2

abcde
bcdea

Sample Output 2

5

Sample Input 3

apple
apple

Sample Output 3

0

No operations may be needed to achieve the objective.


process.stdin.setEncoding('utf-8')
process.stdin.on('data', (data) => {
    const array = data.trim().split(/[\n]/)
    array[0].trim()
    array[1].trim()
    let res = 0
    for (let i = 0; i < array[0].length; i++) {
        if (array[0][i] !== array[1][i]){
            res ++
        }
    }
    console.log(res)
})


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

    let count = 0;
    for(let i = 0; i < s.length; i++) {
        if(!(s.charAt(i) === t.charAt(i))) {
            count++;
        }
    }

    console.log(count);
}

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


function Main(input) {
    const a = input;

    if(isUpperCase(a)){
        console.log('A');
    }else{
        console.log('a');
    }

}

const isUpperCase = c => {
    return /^[A-Z]+$/g.test(c)
}

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

Score : 100 points

Problem Statement

An uppercase or lowercase English letter \alpha will be given as input.
If \alpha is uppercase, print A; if it is lowercase, print a.

Constraints

\alpha is an uppercase (A - Z) or lowercase (a - z) English letter.

Input

Input is given from Standard Input in the following format:

α

Output

If \alpha is uppercase, print A; if it is lowercase, print a.

Sample Input 1

B

Sample Output 1

A

B is uppercase, so we should print A.

Sample Input 2

a

Sample Output 2

a

a is lowercase, so we should print a.


// 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 = input.split("\n");
	let n = input[0].split(" ")[0];
	let k = input[0].split(" ")[1];
	let arr = input[1].split(" ").map(el => parseInt(el));
	arr.sort();
  	let ans = 0;
	for(let i=0;i<arr.length;i++)
      ans+=arr[0];

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

Score : 200 points

Problem Statement

A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)

Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.

Constraints

1 \leq K \leq N \leq 1000

1 \leq p_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 p_2 \ldots p_N

Output

Print an integer representing the minimum possible total price of fruits.

Sample Input 1

5 3
50 100 80 120 80

Sample Output 1

210

This shop sells Fruit 1, 2, 3, 4, and 5 for 50 yen, 100 yen, 80 yen, 120 yen, and 80 yen, respectively.

The minimum total price for three kinds of fruits is 50 + 80 + 80 = 210 yen when choosing Fruit 1, 3, and 5.

Sample Input 2

1 1
1000

Sample Output 2

1000


process.stdin.resume();
process.stdin.setEncoding("utf8");
process.stdin.on("data", (input) => {
    const analyzed = analyzeInput(input);
    const result = getResult(analyzed.K, analyzed.Pk);

    console.log(result);
});

const analyzeInput = (input) => {
  const lines = input.split("\n");
  const line1 = lines[0].split(" ");
  const line2 = lines[1].split(" ");

  const N = line1[0];
  const K = line1[1];

  const pk = line2.map(num => Number(num));

  return {
    N: N,
    K: K,
    Pk: pk,
  };
};

const getResult = (k, pk) => {
  pk.sort((p1, p2) => {
    if (p1 > p2) return 1;
    if (p1 < p2) return -1;
    return 0;
  });

  const sum = pk.slice(0, k).reduce((total, curr) => {
    return total + curr;
  }, 0);

  return sum;
};


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


const fs = require('fs')
const chars = 'abcdefghijklmnopqrstuvwxyz'

function changeBase(value) {
	const base = chars.length
    let result = ''
    while (value > 0) {
    	const c = chars[value % base]
        result = c + result
        value = Math.floor(value / base)
    }
	return result
}

const inputValue = parseInt(fs.readFileSync('/dev/stdin', 'utf8'))
console.log(changeBase(inputValue))

Score : 300 points

Problem Statement

1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows:

the dogs numbered 1,2,\cdots,26 were respectively given the names a, b, ..., z;

the dogs numbered 27,28,29,\cdots,701,702 were respectively given the names aa, ab, ac, ..., zy, zz;

the dogs numbered 703,704,705,\cdots,18277,18278 were respectively given the names aaa, aab, aac, ..., zzy, zzz;

the dogs numbered 18279,18280,18281,\cdots,475253,475254 were respectively given the names aaaa, aaab, aaac, ..., zzzy, zzzz;

the dogs numbered 475255,475256,\cdots were respectively given the names aaaaa, aaaab, ...;

and so on.

To sum it up, the dogs numbered 1, 2, \cdots were respectively given the following names:

a, b, ..., z, aa, ab, ..., az, ba, bb, ..., bz, ..., za, zb, ..., zz, aaa, aab, ..., aaz, aba, abb, ..., abz, ..., zzz, aaaa, ...

Now, Roger asks you:

"What is the name for the dog numbered N?"

Constraints

N is an integer.

1 \leq N \leq 1000000000000001

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer to Roger's question as a string consisting of lowercase English letters.

Sample Input 1

2

Sample Output 1

b

Sample Input 2

27

Sample Output 2

aa

Sample Input 3

123456789

Sample Output 3

jjddja


function main(input) {
  let N = parseInt(input.split("\n"), 10);
  let alphabet = "abcdefghijklmnopqrstuvwhyz";
  let result = "";

  while (0 < N) {
    let M = N % 26;
    if (M === 26) {
      M = 26;
    }
    result = alphabet.substr(M - 1, 1) + result;
    N = (N - M) / 26;
  }

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


const main = (input) => {
  const a = '0abcdefghijklmnopqrstuvwxyz'
  let N = BigInt(input.trim())

  const ans = []
  while (N > 26n) {
    const r = Number(N % 26n)
    ans.unshift(a[r])
    N = (N - BigInt(r)) / 26n
  }
  if (N > 0n) ans.unshift(a[Number(N)])
  return console.log(ans.join(''))
}

process.env.MYTEST ? test() : main(require('fs').readFileSync('/dev/stdin', 'utf8'))


"use strict";

function main(input) {
  const alphabet = "abcdefghijklmnopqrstuvwxyz";
  const alphabet_arr = alphabet.split("");
  input = input.trim();
  const az = 26;
  let num = parseInt(input);
  let n = 1; //桁数
  let m = 0;
  let ans = [];

  while (num > 26) {
    n++;
    const a = num % az;
    ans.push(a);
    num = Math.floor(num / az);
  }
  ans.push(num % az);
  for (let i in ans) {
    ans[i] = alphabet_arr[ans[i] - 1];
  }
  console.log(ans.reverse().join(""));
}
var f = function (a, b) {
  return a - b;
};

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


"use strict";

function main(input) {
  const alphabet = "abcdefghijklmnopqrstuvwxyz";
  const alphabet_arr = alphabet.split("");
  console.log(alphabet_arr[0]);
  input = input.trim();
  const az = 26;
  let num = parseInt(input);
  let n = 1; //桁数
  let m = 0;
  let ans = [];

  while (num > 26) {
    n++;
    const a = num % az;
    ans.push(a);
    num = Math.floor(num / az);
  }
  ans.push(num % az);
  for (let i in ans) {
    ans[i] = alphabet_arr[ans[i] - 1];
  }
  console.log(ans);
}
var f = function (a, b) {
  return a - b;
};

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


"use strict"

function main(arg) {
    lines = arg.split("\n")
    const N = Number(lines[0])
    let A = lines[1].split(" ").map(x=>Number(x))
    const Q = Number(lines[2])
    lines.shift()
    lines.shift()
    lines.shift()
    const B = lines.map(x=>Number(x.split(" ")[0]))
    const C = lines.map(x=>Number(x.split(" ")[1]))

    let sum = []
    sum[0] = A.reduce((a,b)=>a+b)//initial summation
    A.sort()

    for(let i=0; i<Q; i++) {
        let dif = 0
        for(let j=0; j<N; j++) {
            if(A[j]===B[i]) {
                A[j] = C[i]
                dif = dif + (C[i] - B[i])
            }
        }
        sum[i+1] = sum[i] + dif
    }
    sum.shift()
    console.log(sum.join("\n"))
}

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

Score : 400 points

Problem Statement

You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.

You will now successively do the following Q operations:

In the i-th operation, you replace every element whose value is B_{i} with C_{i}.

For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th operation.

Constraints

All values in input are integers.

1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5}

B_{i} \neq C_{i}

Input

Input is given from Standard Input in the following format:

N
A_{1} A_{2} \cdots A_{N}
Q
B_{1} C_{1}
B_{2} C_{2}
\vdots
B_{Q} C_{Q}

Output

Print Q integers S_{i} to Standard Output in the following format:

S_{1}
S_{2}
\vdots
S_{Q}

Note that S_{i} may not fit into a 32-bit integer.

Sample Input 1

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

Sample Output 1

11
12
16

Initially, the sequence A is 1,2,3,4.

After each operation, it becomes the following:

2, 2, 3, 4

2, 2, 4, 4

4, 4, 4, 4

Sample Input 2

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

Sample Output 2

8
4
4

Note that the sequence A may not contain an element whose value is B_{i}.

Sample Input 3

2
1 2
3
1 100
2 100
100 1000

Sample Output 3

102
200
2000


function Main(input) {
    input = input.trim().split("\n").map(function(x) { return x.split(" ")});
    var N = parseInt(input[0],10);
    var vec_A = input[1].map(e => parseInt(e, 10));
    var Q = parseInt(input[2], 10);
    ary_bc = [];
    for (var i = 0; i < Q; i++){
        ary_bc.push(input[i+3].map(e => parseInt(e, 10)));
    }
    var　ATable = vec_A.reduce(function(m, a, i) {
        m[a] = (m[a] || []).concat(i);
        return m;
        }, {});
    var b, c, l;
    var vec_S = [];
    var S = sum(vec_A);

    for (i = 0; i < Q; i++){
        l = 0;
        if (ary_bc[i][0] in ATable){
          	l = 0;
          	var tmp = ATable[String(ary_bc[i][0])]
            if (tmp !== undefined)  l = tmp.length;
            if (ary_bc[i][1] in ATable){
                ATable[String(ary_bc[i][1])] = ATable[String(ary_bc[i][0])].concat(ATable[String(ary_bc[i][1])]);
            } else {
                ATable[String(ary_bc[i][1])] = ATable[String(ary_bc[i][0])];
            }
            delete(ATable[String(ary_bc[i][0])]);
        }
        S = S + (ary_bc[i][1] - ary_bc[i][0]) * l
        vec_S.push(S);
    }
	console.log(vec_S.join('\n');
}

var sum  = function(arr) {
    var sum = 0;
    arr.forEach(function(elm) {
        sum += elm;
    });
    return sum;
};

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


function Main(input){
    input=input.split("\n");  //ここまで必須
    var line=input[0].split(" ");
    var result="";
    for (i=0;i<5;i++){
        if (line[i]==0){result=i}
    }
    console.log(parseInt(result)+1)
}
Main(require("fs").readFileSync("/dev/stdin","utf8"));

Score : 100 points

Problem Statement

We have five variables x_1, x_2, x_3, x_4, and x_5.

The variable x_i was initially assigned a value of i.

Snuke chose one of these variables and assigned it 0.

You are given the values of the five variables after this assignment.

Find out which variable Snuke assigned 0.

Constraints

The values of x_1, x_2, x_3, x_4, and x_5 given as input are a possible outcome of the assignment by Snuke.

Input

Input is given from Standard Input in the following format:

x_1 x_2 x_3 x_4 x_5

Output

If the variable Snuke assigned 0 was x_i, print the integer i.

Sample Input 1

0 2 3 4 5

Sample Output 1

1

In this case, Snuke assigned 0 to x_1, so we should print 1.

Sample Input 2

1 2 0 4 5

Sample Output 2

3


// JavaScript source code
"use strict";

function main(input) {
    input = input.split(" ");
    for (let i = 0; i < 5; i++) {
        if (input[i] == 0) {
            console.log(i + 1);
            break;
        }
    }
};

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


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

function Main(inputText){
	let input = inputText.split('\n');
	input = input.map(e => toIntArr(e.split(' ')));
	let xs = input[0];
	for(let i = 0; i < 5; i++)if(i+1!==xs[i]){
		console.log(i+1);
		return 0;
	};
}


r=require("fs").readFileSync("/dev/stdin","utf8").split(" ");
for(i in r)if(i=="0")console.log(i-0+1);


"use strict";

const main = (input) => {
    const spi = input.split('\n');
    const [x, y] = spi[0].split(' ').map(e => parseInt(e));

    for (let i = 0; i < x + 1; i++) {
        const turu = i * 2;
        const kame = (x - i) * 4;

        if (turu + kame === y) {
            console.log("Yes");
            return;
        }
    }

    console.log("No");
};

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

Score : 200 points

Problem Statement

There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.

Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.

Constraints

1 \leq X \leq 100

1 \leq Y \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If there is a combination of numbers of cranes and turtles in which the statement is correct, print Yes; otherwise, print No.

Sample Input 1

3 8

Sample Output 1

Yes

The statement "there are 3 animals in total in the garden, and they have 8 legs in total" is correct if there are two cranes and one turtle. Thus, there is a combination of numbers of cranes and turtles in which the statement is correct.

Sample Input 2

2 100

Sample Output 2

No

There is no combination of numbers of cranes and turtles in which this statement is correct.

Sample Input 3

1 2

Sample Output 3

Yes

We also consider the case in which there are only cranes or only turtles.


function Main(input) {

    input = input.split("\n");
    const numArray = input[0].split(" ");

    const sum = Number(numArray[0]);
    const legSum = Number(numArray[1]);

    const min = sum * 2;
    const max = sum * 4;

    if (legSum >= min && legSum <= max && legSum % 2 === 0) {
        console.log('Yes');
    } else {
        console.log('No');
    }
}

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


// ABC170 - B
function main(input) {
  var inputs = input.trim().split('\n');
  var X = inputs[0].split(' ')[0] - 0;
  var Y = inputs[0].split(' ')[1] - 0;

  for (var cr = 0; cr < X; cr++) {
    for (var tu = X - cr; tu >= 0; tu--) {
      if (cr * 2 + tu * 4 === Y) {
        console.log('Yes');
        return;
      }
    }
  }

  console.log('No');
}

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


const main = (input) => {
  const args = input.trim().split(" ");
  const x = parseInt(args[0], 10);
  const y = parseInt(args[1], 10);

  if (y % 2 !== 0 || y / 2 - x < 0 || 2 * x - y / 2 < 0) {
    console.log("No");
  } else {
    console.log("Yes");
  }
};

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


function main(input) {
  input = input.trim()
  const args = input.split("\n")

  args[0] = args[0].split(" ")
  const x = Number(args[0][0])
  const n = Number(args[0][1])

  if (n === 0) return console.log(x)

  const pArray = args[1]
                  .split(" ")
                  .map(v => Number(v))
                  .sort((a, b) => a - b)

  const min = Math.min(x, pArray[0])
  const max = Math.max(x, pArray[n - 1])
  let last = null
  for (let i = min; i <= max + 1; i++) {
    if (pArray.includes(i) || i === x) continue

    const diff = Math.abs(x - i)
    if (!last) {
      last = { value: i, diff }
      continue
    }

    if (diff < last.diff) {
      last = { value: i, diff }
      continue
    }
    console.log(last.value)
    break
  }
}

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

Score : 300 points

Problem Statement

Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N.

Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, report the smallest such integer.

Constraints

1 \leq X \leq 100

0 \leq N \leq 100

1 \leq p_i \leq 100

p_1, \ldots, p_N are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X N
p_1 ... p_N

Output

Print the answer.

Sample Input 1

6 5
4 7 10 6 5

Sample Output 1

8

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the one nearest to 6 is 8.

Sample Input 2

10 5
4 7 10 6 5

Sample Output 2

9

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the ones nearest to 10 are 9 and 11. We should print the smaller one, 9.

Sample Input 3

100 0

Sample Output 3

100

When N = 0, the second line in the input will be empty. Also, as seen here, X itself can be the answer.


const main = (input) => {
  const args = input.trim().split("\n");
  const [x, n] = args[0]
    .trim()
    .split(" ")
    .map((n) => parseInt(n, 10));

  const excluded = (() => {
    if (n === 0) {
      return [];
    } else {
      return args[1]
        .trim()
        .split(" ")
        .map((n) => parseInt(n, 10));
    }
  })();

  const selection = [...Array(101 + 1).keys()].filter(
    (s) => !excluded.includes(s)
  );

  const abs = (n) => {
    if (n < 0) return -n;
    else {
      return n;
    }
  };
  const byAsc = (a, b) => a[1] - b[1];

  const answer = selection
    .map((s) => [s, abs(x - s)])
    .sort(byAsc)[0][0];

  console.log(answer);
};

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


function main(input) {
    let [X, N, ...ps] = input.trim().split(/[\s\n]/).map(Number)

    let down = X
    let up = X

    let changed = false
    do {
        changed = false
        for(const p of ps) {
            if(down === p) {
                down--
                changed = true
            }

            if(up === p) {
                up++
                changed = true
            }
        }
    } while(changed)

    const d = Math.abs(down - X)
    const u = Math.abs(up - X)

    if(d === u || d < u) {
        console.log(down)
    } else {
        console.log(up)
    }
}

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


'use strict';
function Main(stdin){
  const input = stdin.trim().split(/\r?\n/g);
  const A_V= input[0].split(' ').map(str => BigInt(str));
  const A = A_V[0], V = A_V[1];
  const B_W= input[1].split(' ').map(str => BigInt(str));
  const B = B_W[0], W = B_W[1];
  const T = BigInt(input[2]);
  let result = 'NO';
  let kyori;
  const tidimu = V - W;

  if(tidimu > 0){
    if(A > 0 && B < 0){
        kyori = A + BigInt(String(B).slice(1));
      } else if(A < 0 && B > 0){
        kyori = B + BigInt(String(A).slice(1));
      } else {
        kyori = A - B;
        if(kyori < 0) kyori = BigInt(String(kyori).slice(1));
      }
      if(tidimu * T > kyori) result = 'YES';
  }
  console.log(result);
}

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

Score : 200 points

Problem Statement

Two children are playing tag on a number line. (In the game of tag, the child called "it" tries to catch the other child.) The child who is "it" is now at coordinate A, and he can travel the distance of V per second.
The other child is now at coordinate B, and she can travel the distance of W per second.

He can catch her when his coordinate is the same as hers.
Determine whether he can catch her within T seconds (including exactly T seconds later).
We assume that both children move optimally.

Constraints

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

1 \leq V,W \leq 10^9

1 \leq T \leq 10^9

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A V
B W
T

Output

If "it" can catch the other child, print YES; otherwise, print NO.

Sample Input 1

1 2
3 1
3

Sample Output 1

YES

Sample Input 2

1 2
3 2
3

Sample Output 2

NO

Sample Input 3

1 2
3 3
3

Sample Output 3

NO


function Main(input) {
    input = input.split("\n");
    var mem = input[0].split("");
    var arr = input[1].split(" ").map(Number);
    while (1) {
        var tmp = new Array(arr.length).fill(0);
        for (var i = 0; i < arr.length; i++) {
            var n = arr[i];
          //  console.log(i,n)
            var min = i - n;
            var max = i + n;
            if (min < 0) min = 0;
            if (max > arr.length-1) max = arr.length-1;
            for (var j = min; j <= max; j++) {
                tmp[j]++;
            }
          //  console.log(max,min,tmp)
        }
      //  console.log(arr)
        var flag = true;
        for (var i = 0; i < arr.length; i++) {
            if(arr[i]!=tmp[i]) flag = false;
            arr[i] = tmp[i];
        }
        if(flag) break;
    }
    console.log(arr.join(" "));
} Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());

Score : 500 points

Problem Statement

We have N bulbs arranged on a number line, numbered 1 to N from left to right.
Bulb i is at coordinate i.

Each bulb has a non-negative integer parameter called intensity.
When there is a bulb of intensity d at coordinate x, the bulb illuminates the segment from coordinate x-d-0.5 to x+d+0.5.
Initially, the intensity of Bulb i is A_i. We will now do the following operation K times in a row:

For each integer i between 1 and N (inclusive), let B_i be the number of bulbs illuminating coordinate i. Then, change the intensity of each bulb i to B_i.

Find the intensity of each bulb after the K operations.

Constraints

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

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

0 \leq A_i \leq N

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \ldots A_N

Output

Print the intensity A{'}_i of each bulb i after the K operations to Standard Output in the following format:

A{'}_1 A{'}_2 \ldots A{'}_N

Sample Input 1

5 1
1 0 0 1 0

Sample Output 1

1 2 2 1 2

Initially, only Bulb 1 illuminates coordinate 1, so the intensity of Bulb 1 becomes 1 after the operation.
Similarly, the bulbs initially illuminating coordinate 2 are Bulb 1 and 2, so the intensity of Bulb 2 becomes 2.

Sample Input 2

5 2
1 0 0 1 0

Sample Output 2

3 3 4 4 3


Score : 100 points

Problem Statement

Compute A \times B.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the value A \times B as an integer.

Sample Input 1

2 5

Sample Output 1

10

We have 2 \times 5 = 10.

Sample Input 2

100 100

Sample Output 2

10000


const rl = require("readline").createInterface(process.stdin,process.stdout);

let count = 1
let inputA, inputB
rl.on("line", (input) => {
  if (count === 1) {
    inputA = input
  } else {
    inputB = input
    console.log(inputA * inputB)
    process.exit()
  }
  count++
});


function main(input){
    var inp=input.trim();
    var inpArray=inp.split(' ');
    out=parseInt(inpArray[0])*parseInt(inpArray[1]);
    console.log(out);

}

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


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  var ans = 0;
  var set = new Set();
  var N2=N;
  for(var i=2;i<Math.sqrt(N);i++){
    var x =i;
    for(var j=1;x<N;j++){
      if(N2%Math.pow(i,j)==0){
        ans++;
        N2=N2/Math.pow(i,j);
      }else{
        break;
      }
      x=Math.pow(i,j+1);
    }
  }
  if(ans==0&&N!=1){
    ans=1;
  }

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

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

Score : 400 points

Problem Statement

Given is a positive integer N. Consider repeatedly applying the operation below on N:

First, choose a positive integer z satisfying all of the conditions below:

z can be represented as z=p^e, where p is a prime number and e is a positive integer;

z divides N;

z is different from all integers chosen in previous operations.

Then, replace N with N/z.

Find the maximum number of times the operation can be applied.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum number of times the operation can be applied.

Sample Input 1

24

Sample Output 1

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=12.)

Choose z=3 (=3^1). (Now we have N=4.)

Choose z=4 (=2^2). (Now we have N=1.)

Sample Input 2

1

Sample Output 2

0

We cannot apply the operation at all.

Sample Input 3

64

Sample Output 3

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=32.)

Choose z=4 (=2^2). (Now we have N=8.)

Choose z=8 (=2^3). (Now we have N=1.)

Sample Input 4

1000000007

Sample Output 4

1

We can apply the operation once by, for example, making the following choice:

z=1000000007 (=1000000007^1). (Now we have N=1.)

Sample Input 5

997764507000

Sample Output 5

7


function Main(input) {
  input = input.trim().split("\n");
  var N = parseInt(input[0], 10);
  var PArr = input[1].split(" ").map((n) => parseInt(n, 10));
  var zaseki = new Array(N);
  var nolike = 0;
  for (var x = 0; x < N; x++) {
    zaseki[x] = new Array(N);
  }
  var data = {};

  for (var i = 1; i <= N; i++) {
    for (var j = 1; j <= N; j++) {
      var num = (i - 1) * N + 1 + (j - 1);
      zaseki[i - 1][j - 1] = num;
      data[num] = [i, j];
    }
  }
  for (var i = 1; i <= N; i++) {
    for (var j = 1; j <= N; j++) {
      var idx = (i - 1) * N + 1 + (j - 1) - 1; //0基準
      var p = PArr[idx]; //座席の番号取得
      var id = data[p][0];
      var jd = data[p][1];
      zaseki[id - 1][jd - 1] = 0;

      if (id == 1 || jd == 1 || id == N || jd == N) {
        continue;
      } else {
        var left = 0;
        var right = 0;
        var up = 0;
        var down = 0;
        for (var a = id; a > 0; a--) {
          if (zaseki[a - 1][jd - 1] != 0) left++;
        }
        for (var b = id; b <= N; b++) {
          if (zaseki[b - 1][jd - 1] != 0) right++;
        }
        for (var c = id; c > 0; c--) {
          if (zaseki[id - 1][c - 1] != 0) up++;
        }
        for (var d = id; d <= N; d++) {
          if (zaseki[id - 1][d - 1] != 0) down++;
        }
      }
      nolike += Math.min(left, right, up, down);
    }
  }

  console.log(nolike);
}

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

Score : 700 points

Problem Statement

Tonight, in your favourite cinema they are giving the movie Joker and all seats are occupied. In the cinema there are N rows with N seats each, forming an N\times N square. We denote with 1, 2,\dots, N the viewers in the first row (from left to right); with N+1, \dots, 2N the viewers in the second row (from left to right); and so on until the last row, whose viewers are denoted by N^2-N+1,\dots, N^2.

At the end of the movie, the viewers go out of the cinema in a certain order: the i-th viewer leaving her seat is the one denoted by the number P_i. The viewer P_{i+1} waits until viewer P_i has left the cinema before leaving her seat.
To exit from the cinema, a viewer must move from seat to seat until she exits the square of seats (any side of the square is a valid exit). A viewer can move from a seat to one of its 4 adjacent seats (same row or same column).
While leaving the cinema, it might be that a certain viewer x goes through a seat currently occupied by viewer y; in that case viewer y will hate viewer x forever. Each viewer chooses the way that minimizes the number of viewers that will hate her forever.

Compute the number of pairs of viewers (x, y) such that y will hate x forever.

Constraints

2 \le N \le 500

The sequence P_1, P_2, \dots, P_{N^2} is a permutation of \{1, 2, \dots, N^2\}.

Input

The input is given from Standard Input in the format

N
P_1 P_2 \cdots P_{N^2}

Output

If ans is the number of pairs of viewers described in the statement, you should print on Standard Output

ans

Sample Input 1

3
1 3 7 9 5 4 8 6 2

Sample Output 1

1

Before the end of the movie, the viewers are arranged in the cinema as follows:

1 2 3
4 5 6
7 8 9

The first four viewers leaving the cinema (1, 3, 7, 9) can leave the cinema without going through any seat, so they will not be hated by anybody.

Then, viewer 5 must go through one of the seats where viewers 2, 4, 6, 8 are currently seated while leaving the cinema; hence he will be hated by at least one of those viewers.

Finally the remaining viewers can leave the cinema (in the order 4, 8, 6, 2) without going through any occupied seat (actually, they can leave the cinema without going through any seat at all).

Sample Input 2

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

Sample Output 2

3

Sample Input 3

6
11 21 35 22 7 36 27 34 8 20 15 13 16 1 24 3 2 17 26 9 18 32 31 23 19 14 4 25 10 29 28 33 12 6 5 30

Sample Output 3

11


function Main(input) {
  input = input.trim().split("\n");
  var N = parseInt(input[0], 10);
  var PArr = input[1].split(" ").map((n) => parseInt(n, 10));
  var zaseki = new Array(N);
  var nolike = 0;
  for (var x = 0; x < N; x++) {
    zaseki[x] = new Array(N);
  }
  var data = {};

  for (var i = 1; i <= N; i++) {
    for (var j = 1; j <= N; j++) {
      var num = (i - 1) * N + 1 + (j - 1);
      zaseki[i - 1][j - 1] = num;
      data[num] = [i, j];
    }
  }
  for (var i = 1; i <= N; i++) {
    for (var j = 1; j <= N; j++) {
      var idx = (i - 1) * N + 1 + (j - 1) - 1; //0基準
      var p = PArr[idx]; //座席の番号取得
      var id = data[p][0];
      var jd = data[p][1];
      zaseki[id - 1][jd - 1] = 0;

      if (id == 1 || jd == 1 || id == N || jd == N) {
        continue;
      } else {
        var left = 0;
        var right = 0;
        var up = 0;
        var down = 0;
        for (var a = id; a > 0; a--) {
          if (zaseki[a - 1][jd - 1] != 0) left++;
        }
        for (var b = id; b <= N; b++) {
          if (zaseki[b - 1][jd - 1] != 0) right++;
        }
        for (var c = id; c > 0; c--) {
          if (zaseki[id - 1][c - 1] != 0) up++;
        }
        for (var d = id; d <= N; d++) {
          if (zaseki[id - 1][d - 1] != 0) down++;
        }
        nolike += Math.min(left, right, up, down);
      }
    }
  }

  console.log(nolike);
}

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


"use strict";

const main = (arg) => {
  const array = arg.trim().split("");
  const lastNumber = array[array.length - 1];
  if (lastNumber == 3) {
    console.log("bon");
  } else if (
    lastNumber == 0 ||
    lastNumber == 1 ||
    lastNumber == 6 ||
    lastNumber == 8
  ) {
    console.log("pon");
  } else {
    console.log("hon");
  }
};
main(require("fs").readFileSync("/dev/stdin", "utf8"));
// main("183");
// https://atcoder.jp/contests/abc168/tasks/abc168_a

Score: 100 points

Problem Statement

The cat Snuke wants to play a popular Japanese game called ÅtCoder, so Iroha has decided to teach him Japanese.

When counting pencils in Japanese, the counter word "本" follows the number. The pronunciation of this word varies depending on the number. Specifically, the pronunciation of "本" in the phrase "N 本" for a positive integer N not exceeding 999 is as follows:

hon when the digit in the one's place of N is 2, 4, 5, 7, or 9;

pon when the digit in the one's place of N is 0, 1, 6 or 8;

bon when the digit in the one's place of N is 3.

Given N, print the pronunciation of "本" in the phrase "N 本".

Constraints

N is a positive integer not exceeding 999.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

16

Sample Output 1

pon

The digit in the one's place of 16 is 6, so the "本" in "16 本" is pronounced pon.

Sample Input 2

2

Sample Output 2

hon

Sample Input 3

183

Sample Output 3

bon


function main(input) {
  const inputs = input.trim().split('\n');
  var N = inputs[0];
  var N1 = N.slice(-1);

  if ('24579'.includes(N1)) {
    console.log('hon');
  } else if ('0168'.includes(N1)) {
    console.log('pon');
  } else {
    console.log('bon');
  }
}

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


function main(input) {
	input = input.split("\n");
  	input = input[0].split(" ");
  	let a = parseInt(input[0], 10);
  	let b = parseInt(input[1], 10);
  	let h = parseInt(input[2], 10);
  	let m = parseInt(input[3], 10);

	console.log(
    	Math.sqrt(
        	Math.pow(a, 2) + Math.pow(b, 2) - 2*a*b*Math.cos(
              Math.PI*Math.abs((5*h - m))/30
            )
        ).toFixed(20)
    );
}

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

Score: 300 points

Problem Statement

Consider an analog clock whose hour and minute hands are A and B centimeters long, respectively.

An endpoint of the hour hand and an endpoint of the minute hand are fixed at the same point, around which each hand rotates clockwise at constant angular velocity. It takes the hour and minute hands 12 hours and 1 hour to make one full rotation, respectively.

At 0 o'clock, the two hands overlap each other. H hours and M minutes later, what is the distance in centimeters between the unfixed endpoints of the hands?

Constraints

All values in input are integers.

1 \leq A, B \leq 1000

0 \leq H \leq 11

0 \leq M \leq 59

Input

Input is given from Standard Input in the following format:

A B H M

Output

Print the answer without units. Your output will be accepted when its absolute or relative error from the correct value is at most 10^{-9}.

Sample Input 1

3 4 9 0

Sample Output 1

5.00000000000000000000

The two hands will be in the positions shown in the figure below, so the answer is 5 centimeters.

Sample Input 2

3 4 10 40

Sample Output 2

4.56425719433005567605

The two hands will be in the positions shown in the figure below. Note that each hand always rotates at constant angular velocity.


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const A = parseInt(arg[0].split(" ")[0]);
    const B = parseInt(arg[0].split(" ")[1]);
    const H = parseInt(arg[0].split(" ")[2]);
    const M = parseInt(arg[0].split(" ")[3]);

    let angleA = (360 / 12) * (H % 12);
    const angleB = (360 / 60) * M;
    angleA += 30 * (M / 60);

    const absAB = Math.abs(angleA - angleB);
    const angle = Math.min(absAB, 360 - absAB);

    let answer;

    answer = (Math.pow(A, 2) + Math.pow(B, 2)) - (2 * A * B) * (Math.cos(angle * (Math.PI / 180)));

    //console.log(angle);
    console.log(Math.sqrt(answer));
    // console.log(Math.cos(90))
    //console.log(Math.sqrt(20));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input) {
  const args = input.split("\n");
  const [A, B, H, M] = args[0].split(" ").map((n) => parseInt(n, 10));

  const min = H * 60 + M;
  console.log(Math.sqrt(A * A + B * B - (2 * A * B * Math.cos(11 * Math.PI * min / 360))));
}

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


let input = require('fs').readFileSync('/dev/stdin', 'utf8').split(' ');
// let input = '3 4 10 40'.split(' ');

const a = parseInt(input[0],10);
const b = parseInt(input[1],10);
const h = parseInt(input[2],10);
const m = parseInt(input[3],10);
const pi = Math.PI;

const arga = (h + m/60)*pi/6;
const argb = pi * m / 30;

const c = (a**2 + b**2 - 2*a*b*Math.cos(arga-argb))**0.5;

console.log(c);


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

function main() {
    let a = +cin.shift();//jisin
    let b = +cin.shift();//hunsin
    let h = +cin.shift();
    let m = +cin.shift();
    let theta =  Math.PI * ((h / 6 +m/360) - m / 30);
    let xx = a * a + b * b - 2 * a * b * Math.cos(theta);
    let x = Math.sqrt(xx);
    console.log(x);
}
main();


const main = arg => {
  const input = arg.trim().split('\n');
  const abList = input.slice(1).map(l => l.split(' ').map(x => Number(x)));

  console.log(abList.reduce(
    (accumulator, [a, b], index) =>
      1 + accumulator + abList.slice(index + 1)
        .filter(([aa, bb]) => a !== aa && b !== bb)
        .filter(([aa, bb]) => a * aa + b * bb !== 0).length,
    0,
  ));
};

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

Score: 500 points

Problem Statement

We have caught N sardines. The deliciousness and fragrantness of the i-th sardine is A_i and B_i, respectively.

We will choose one or more of these sardines and put them into a cooler. However, two sardines on bad terms cannot be chosen at the same time.

The i-th and j-th sardines (i \neq j) are on bad terms if and only if A_i \cdot A_j + B_i \cdot B_j = 0.

In how many ways can we choose the set of sardines to put into the cooler? Since the count can be enormous, print it modulo 1000000007.

Constraints

All values in input are integers.

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

-10^{18} \leq A_i, B_i \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the count modulo 1000000007.

Sample Input 1

3
1 2
-1 1
2 -1

Sample Output 1

5

There are five ways to choose the set of sardines, as follows:

The 1-st

The 1-st and 2-nd

The 2-nd

The 2-nd and 3-rd

The 3-rd

Sample Input 2

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

Sample Output 2

479


const main = arg => {
  const input = arg.trim().split('\n');
  const abList = input.slice(1).map(l => l.split(' ').map(x => Number(x)));

  console.log(abList.reduce(
    (accumulator, [a, b], index) =>
      accumulator + abList.slice(index + 1).filter(([aa, bb]) => a * aa + b * bb !== 0).length + 1,
    0,
  ));
};

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


"use strict";

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

    T.pop();

    console.log(S.join("") === T.join("") ? "Yes" : "No");
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

Takahashi wants to be a member of some web service.

He tried to register himself with the ID S, which turned out to be already used by another user.

Thus, he decides to register using a string obtained by appending one character at the end of S as his ID.

He is now trying to register with the ID T. Determine whether this string satisfies the property above.

Constraints

S and T are strings consisting of lowercase English letters.

1 \leq |S| \leq 10

|T| = |S| + 1

Input

Input is given from Standard Input in the following format:

S
T

Output

If T satisfies the property in Problem Statement, print Yes; otherwise, print No.

Sample Input 1

chokudai
chokudaiz

Sample Output 1

Yes

chokudaiz can be obtained by appending z at the end of chokudai.

Sample Input 2

snuke
snekee

Sample Output 2

No

snekee cannot be obtained by appending one character at the end of snuke.

Sample Input 3

a
aa

Sample Output 3

Yes


function main(input) {
	input =  input.split(" ");
	const A = input[0];
	const B = input[1];
	const C = input[1];
	const K = input[3];

	if (A+B>=K){
	    console.log(A);
	} else {
	    console.log(2*A+B-K);
	}

}

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

Score : 200 points

Problem Statement

We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.

We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?

Constraints

All values in input are integers.

0 \leq A, B, C

1 \leq K \leq A + B + C \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the maximum possible sum of the numbers written on the cards chosen.

Sample Input 1

2 1 1 3

Sample Output 1

2

Consider picking up two cards with 1s and one card with a 0.
In this case, the sum of the numbers written on the cards is 2, which is the maximum possible value.

Sample Input 2

1 2 3 4

Sample Output 2

0

Sample Input 3

2000000000 0 0 2000000000

Sample Output 3

2000000000


function Main(input) {
	var str = input;
	var ans = 0;
	str = str.split("\n")[0];
	str = str.split(" ");
	var a = Number(str[0]);
	var b = Number(str[1]);
	var c = Number(str[2]);
	var k = Number(str[3]);
	ans = Number(ans);
	if (a <= k){
	ans = ans + a;
	k = k - a;
	k = k - b;
		if(k > 0){
			ans = ans - k;
		}
   	}else{
   		ans = a;
   	}
	   console.log(ans);
}
 //*おまじない
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


let input = require("fs").readFileSync("/dev/stdin", "utf8").split("\n")[0].split(' ').map(i => parseInt(i))

const A = input[0]
const B = input[1]
const C = input[2]

// const ABC = [
//     [1, input[0]],
//     [0, input[1]],
//     [-1, input[2]]
// ]
const K = input[3]

count = 0
result = 0

if (K - count - A >= 0) {
    count += A
    result += A * 1
} else {
    console.log(K)
    return
}

if (K - count - B >= 0) {
    count += B
    result += B * 0
} else {
    console.log(result)
    return
}

result += (K - count) * (-1)

console.log(result)


// ABC167 - B
function main(input) {
  var inputs = input.split('\n');
  var line1 = inputs[0].split(' ');
  var n = parseInt(line1[0], 10);
  var m = parseInt(line1[1], 10);
  var x = parseInt(line1[2], 10);

  var c = [];
  var a = [];
  for (var i = 0; i < n; i++) {
    var lineN = inputs[i + 1].split(' ');
    c.push(parseInt(lineN[0], 10));
    a[i] = [];
    for (var j = 1; j < m + 1; j++) {
      a[i].push(parseInt(lineN[j], 10));
    }
  }

  var iniAs = [];
  for (var i = 0; i < m; i++) {
    iniAs.push(0);
  }

  var maxCost = c.reduce((a, b) => a + b);
  var minCost = maxCost * 1;

  var bits = bitComb(n);
  bits.forEach((bit) => {
    var tempCost = 0;
    var tempAs = iniAs.concat();
    bit.forEach((bitItem) => {
      tempCost += c[bitItem];
      tempAs = sumItems(tempAs.concat(), a[bitItem]);
    });
    if (tempAs.every((foo) => foo >= x)) minCost = Math.min(minCost, tempCost);
  });

  console.log(minCost != maxCost ? minCost : -1);
}

function bitComb(n) {
  var ret = [];
  for (let bit = 0; bit < (1 << n); bit++) {
    let row = [];
    for (let i = 0; i < n; i++) {
      if (bit & (1 << i)) {
        row.push(i);
      }
    }
    ret.push(row);
  }
  return ret;
}

function sumItems(arr1, arr2) {
  var ret = [];
  for (var i = 0; i < arr1.length; i++) {
    ret.push(arr1[i] + arr2[i]);
  }
  return ret;
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 300 points

Problem

Takahashi, who is a novice in competitive programming, wants to learn M algorithms.
Initially, his understanding level of each of the M algorithms is 0.

Takahashi is visiting a bookstore, where he finds N books on algorithms.
The i-th book (1\leq i\leq N) is sold for C_i yen (the currency of Japan). If he buys and reads it, his understanding level of the j-th algorithm will increase by A_{i,j} for each j (1\leq j\leq M).
There is no other way to increase the understanding levels of the algorithms.

Takahashi's objective is to make his understanding levels of all the M algorithms X or higher. Determine whether this objective is achievable. If it is achievable, find the minimum amount of money needed to achieve it.

Constraints

All values in input are integers.

1\leq N, M\leq 12

1\leq X\leq 10^5

1\leq C_i \leq 10^5

0\leq A_{i, j} \leq 10^5

Input

Input is given from Standard Input in the following format:

N M X
C_1 A_{1,1} A_{1,2} \cdots A_{1,M}
C_2 A_{2,1} A_{2,2} \cdots A_{2,M}
\vdots
C_N A_{N,1} A_{N,2} \cdots A_{N,M}

Output

If the objective is not achievable, print -1; otherwise, print the minimum amount of money needed to achieve it.

Sample Input 1

3 3 10
60 2 2 4
70 8 7 9
50 2 3 9

Sample Output 1

120

Buying the second and third books makes his understanding levels of all the algorithms 10 or higher, at the minimum cost possible.

Sample Input 2

3 3 10
100 3 1 4
100 1 5 9
100 2 6 5

Sample Output 2

-1

Buying all the books is still not enough to make his understanding levels of all the algorithms 10 or higher.

Sample Input 3

8 5 22
100 3 7 5 3 1
164 4 5 2 7 8
334 7 2 7 2 9
234 4 7 2 8 2
541 5 4 3 3 6
235 4 8 6 9 7
394 3 6 1 6 2
872 8 4 3 7 2

Sample Output 3

1067


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

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

function main(){
  var NN = "No", YY = "Yes";
  var n = next();
  var up = [], ud = [], sum = 0, rest = 0;
  for(var i = 0; i < n; i++){
    var mn = 0, last = 0;
    var s = next(1);
    for(var j = 0; j < s.length; j++){
      if(s[j] === "(")last++;
      else{
        last--;
        if(last < mn)mn = last;
      }
    }
    sum += last;
    if(mn >= 0)rest += last;
    else if(last <= 0)up.push([-mn+last,last]);
    else ud.push([-mn,last]);
  }
  if(sum)return NN;
  ud.sort((a,b)=>a[0]-b[0]);
  for(var i = 0; i < ud.length; i++){
    if(ud[i][0] > rest)return NN;
    rest += ud[i][1];
  }
  up.sort((a,b)=>b[0]-a[0]);
  for(var i = 0; i < up.length; i++){
    var [mn,last] = up[i];
    if(mn > rest)return NN;
    rest += last;
  }
  return YY;
}

Score : 600 points

Problem Statement

A bracket sequence is a string that is one of the following:

An empty string;

The concatenation of (, A, and ) in this order, for some bracket sequence A ;

The concatenation of A and B in this order, for some non-empty bracket sequences A and B /

Given are N strings S_i. Can a bracket sequence be formed by concatenating all the N strings in some order?

Constraints

1 \leq N \leq 10^6

The total length of the strings S_i is at most 10^6.

S_i is a non-empty string consisting of ( and ).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

If a bracket sequence can be formed by concatenating all the N strings in some order, print Yes; otherwise, print No.

Sample Input 1

2
)
(()

Sample Output 1

Yes

Concatenating (() and ) in this order forms a bracket sequence.

Sample Input 2

2
)(
()

Sample Output 2

No

Sample Input 3

4
((()))
((((((
))))))
()()()

Sample Output 3

Yes

Sample Input 4

3
(((
)
)

Sample Output 4

No


const main = input => /^ABC/.test(input) ? "ARC" : "ABC"; // Implement this function

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

Score : 100 points

Problem Statement

AtCoder Inc. holds a contest every Saturday.

There are two types of contests called ABC and ARC, and just one of them is held at a time.

The company holds these two types of contests alternately: an ARC follows an ABC and vice versa.

Given a string S representing the type of the contest held last week, print the string representing the type of the contest held this week.

Constraints

S is ABC or ARC.

Input

Input is given from Standard Input in the following format:

S

Output

Print the string representing the type of the contest held this week.

Sample Input 1

ABC

Sample Output 1

ARC

They held an ABC last week, so they will hold an ARC this week.


function Main(input) {
  input = input.split("\n");
  var a = input[0];
  if (a === "ABC") {
	console.log("ARC")
  } else {
	console.log("ABC")
  }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));//おまじない


const Main = (arg) => {
  const elem = arg.split('_')[0];
  if(elem === 'ABC') {
    console.log('ARC')
  } else if (elem === 'ARC') {
    console.log('ABC')
  }
}

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


// inputに入力データ全体が入る
function Main(input) {
  　if (input == 'ABC') {
     console.log('ARC');
   } else {
     console.log('ABC');
   }

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


const main = input => parseInt(input.split(" ")[0]) - new Set(input.split("\n").slice(1).filter((e, i) => i % 2).map(e => e.slice(" ")).flat()).size; // Implement this function

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

Score : 200 points

Problem Statement

N Snukes called Snuke 1, Snuke 2, ..., Snuke N live in a town.

There are K kinds of snacks sold in this town, called Snack 1, Snack 2, ..., Snack K. The following d_i Snukes have Snack i: Snuke A_{i, 1}, A_{i, 2}, \cdots, A_{i, {d_i}}.

Takahashi will walk around this town and make mischief on the Snukes who have no snacks. How many Snukes will fall victim to Takahashi's mischief?

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq K \leq 100

1 \leq d_i \leq N

1 \leq A_{i, 1} < \cdots < A_{i, d_i} \leq N

Input

Input is given from Standard Input in the following format:

N K
d_1
A_{1, 1} \cdots A_{1, d_1}
\vdots
d_K
A_{K, 1} \cdots A_{K, d_K}

Output

Print the answer.

Sample Input 1

3 2
2
1 3
1
3

Sample Output 1

1

Snuke 1 has Snack 1.

Snuke 2 has no snacks.

Snuke 3 has Snack 1 and 2.

Thus, there will be one victim: Snuke 2.

Sample Input 2

3 3
1
3
1
3
1
3

Sample Output 2

2


const Main = (input) => {
    ans=''
    const lines = input.split('\r')
    line0=lines[0].trim().split(" ")
    N=line0[0]
    K=lines[1]
    a=new Array(N)
    for (i=2;i<lines.length;i=i+2){
        line=lines[i].trim().split(" ")
        for(j=0;j<line.length;j++){
            a[line[j]]=true
        }
    }
    ans=0
    for( i=0 ;i<a.length;i++){
        if(!a[i]){
            ans++
        }
    }
    return ans
}

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


'use strict'

function main(input) {
  const inputList = input.split('\n');
  const n = Number(inputList[0].split(' ')[0])
  const m = Number(inputList[0].split(' ')[1])
  const heightList = inputList[1].split(' ').map(height => Number(height))
  const routeList = inputList.slice(2)

  let list = new Array(n)
  for (let i=0; i<n; i++) {
    list[i] = new Array()
  }
  for (let i=0; i<m; i++) {
    const tmp = routeList[i].split(' ')
    const a = Number(tmp[0]) - 1
    const b = Number(tmp[1]) - 1
    list[a].push(b)
    list[b].push(a)
  }

  let count = 0
  for (let i=0; i<list.length; i++) {
    let tmp = 1
    for (let j=0; j<list[i].length; j++) {
      if (heightList[i] <= heightList[list[i][j]]) {
        tmp = 0
        break
      }
    }
    count += tmp
  }

  console.log(count)
}

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

Score : 300 points

Problem Statement

There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i.
There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j.

Obs. i is said to be good when its elevation is higher than those of all observatories that can be reached from Obs. i using just one road.
Note that Obs. i is also good when no observatory can be reached from Obs. i using just one road.

How many good observatories are there?

Constraints

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq H_i \leq 10^9

1 \leq A_i,B_i \leq N

A_i \neq B_i

Multiple roads may connect the same pair of observatories.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
H_1 H_2 ... H_N
A_1 B_1
A_2 B_2
:
A_M B_M

Output

Print the number of good observatories.

Sample Input 1

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

Sample Output 1

2

From Obs. 1, you can reach Obs. 3 using just one road. The elevation of Obs. 1 is not higher than that of Obs. 3, so Obs. 1 is not good.

From Obs. 2, you can reach Obs. 3 and 4 using just one road. The elevation of Obs. 2 is not higher than that of Obs. 3, so Obs. 2 is not good.

From Obs. 3, you can reach Obs. 1 and 2 using just one road. The elevation of Obs. 3 is higher than those of Obs. 1 and 2, so Obs. 3 is good.

From Obs. 4, you can reach Obs. 2 using just one road. The elevation of Obs. 4 is higher than that of Obs. 2, so Obs. 4 is good.

Thus, the good observatories are Obs. 3 and 4, so there are two good observatories.

Sample Input 2

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

Sample Output 2

3


"use strict";

const main = arg => {
    const inputList = arg.trim().split("\n");
  // 回答を記述
  const N = parseInt(inputList[0].split(' ')[0]);
  // [高さ, 隣より高いbool]
  const peaks = inputList[1].split(' ').map(ele => parseInt(ele)).map(ele => [ele, true]);
  // 道のリスト（idx >= 2）から隣以下の高さであればboolをfalseにする
  for (let i = 2; i < inputList.length; i++) {
    // idxにするために -1
    const AB = inputList[i].split(' ').map(ele => parseInt(ele) - 1);
    if (peaks[AB[0]][0] <= peaks[AB[1]][0] ) peaks[AB[0]][1] = false;
    if (peaks[AB[0]][0] >= peaks[AB[1]][0] ) peaks[AB[1]][1] = false;
  }
  // 高いbool == true　の要素数を出力する
  console.log(peaks.filter(ele => ele[1] == true).length)

}

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


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

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

function main(){
  var [n,m] = nexts(2);
  var h = nexts(n);
  var q = xArray(1,n);
  for(var i = 0; i < m; i++){
    var [a,b] = nexts(2);
    a--,b--;
    if(h[a] >= h[b])q[b] = 0;
    if(h[b] >= h[a])q[a] = 0;
  }
  return q.reduce((a,b)=>a+b);
}


"use strict";

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

const firstLine = input[0].split(" ").map((val) => parseInt(val, 10));

const N = firstLine[0];
const M = firstLine[1];

const heightList = input[1].split(" ").map((val) => parseInt(val, 10));
const goodPlaceList = Array(N).fill(true);

for (let i = 2; i < M + 2; i++) {
  const path = input[i].split(" ").map((val) => parseInt(val, 10));

  if (heightList[path[0] - 1] <= heightList[path[1] - 1]) {
    goodPlaceList[path[0] - 1] = false;
  }

  if (heightList[path[1] - 1] <= heightList[path[0] - 1]) {
    goodPlaceList[path[1] - 1] = false;
  }
}

console.log(goodPlaceList.filter((isGood) => isGood === true).length);


"use strict";

const main = arg => {
    const input = arg.trim().split("\n");

    const x = parseInt(input[0]);
    for(let a = -120; a<= 120; a++){
        for(let b = -120; b<= 120; b++){
            let tmp = a*a*a*a*a - b*b*b*b*b
            if(x === tmp){
                console.log(`${a} ${b}`)
                return
            }
        }
    }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 400 points

Problem Statement

Give a pair of integers (A, B) such that A^5-B^5 = X.
It is guaranteed that there exists such a pair for the given integer X.

Constraints

1 \leq X \leq 10^9

X is an integer.

There exists a pair of integers (A, B) satisfying the condition in Problem Statement.

Input

Input is given from Standard Input in the following format:

X

Output

Print A and B, with space in between.
If there are multiple pairs of integers (A, B) satisfying the condition, you may print any of them.

A B

Sample Input 1

33

Sample Output 1

2 -1

For A=2 and B=-1, A^5-B^5 = 33.

Sample Input 2

1

Sample Output 2

0 -1


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

function main() {
    let X = +cin.shift();
    let s = 0;
    while (s <= 200) {
        for (let a = 0; a <= s; a++) {
            let b = s - a;
            let ma = -a;
            let mb = -b;
            if (a ** 5 - b ** 5 == X) {
                console.log(a, b);
                return;
            }
            if (a ** 5 - mb ** 5 == X) {
                console.log(a, mb);
                return;
            }
            if (ma ** 5 - b ** 5 == X) {
                console.log(ma, b);
                return;
            }
            if (ma ** 5 - mb ** 5 == X) {
                console.log(ma, mb);
                return;
            }
        }
        s++;
    }
}
main();


"use strict";

function main(input) {
  input = input.split("\n");
  let tmp = input[1].split(" ");
  let a = tmp[0];
  let b = tmp[1];
  for (a; a <= b; a++) {
    const res = a % input[0];
    if (res === 0) {
      console.log("OK");
      return;
    }
  }
  console.log("NG");
}

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

Score: 100 points

Problem Statement

Takahashi the Jumbo will practice golf.

His objective is to get a carry distance that is a multiple of K, while he can only make a carry distance of between A and B (inclusive).

If he can achieve the objective, print OK; if he cannot, print NG.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 1000

1 \leq K \leq 1000

Input

Input is given from Standard Input in the following format:

K
A B

Output

If he can achieve the objective, print OK; if he cannot, print NG.

Sample Input 1

7
500 600

Sample Output 1

OK

Among the multiples of 7, for example, 567 lies between 500 and 600.

Sample Input 2

4
5 7

Sample Output 2

NG

No multiple of 4 lies between 5 and 7.

Sample Input 3

1
11 11

Sample Output 3

OK


const Main = input => {
    const inp = input.split("\n");//["K", "A B"]
    const ab = inp[1].split(" ");//["A", "B"]
    const k = parseInt(inp[0], 10);
    const a = parseInt(ab[0], 10);
    const b = parseInt(ab[1], 10);

    let result = "NG";
    const min = Math.ceil(a / k);
    if(a <= k*min && k*min <= b) result = "OK";
    console.log(result);
}

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


"use strict";

const main = arg => {
    const input = arg.trim().split("\n");

    const [N, M, Q] = input[0].split(" ").map(el => parseInt(el));
    let list = []
    for(let i = 1; i<=Q; i++){
        list.push(input[i].split(" ").map(el => parseInt(el)))
    }
    let ans = 0
    const dfs = function(parent, sub){
        if(sub.length == N){
            let tmp = 0
            for(let i = 0; i<Q; i++){
                if(sub[list[i][1]-1] - sub[list[i][0]-1] == list[i][2]){
                    tmp += list[i][3]
                }
            }
            ans = Math.max(ans, tmp)
            return
        }
        for(let i = parent; i<=M; i++){
            sub.push(i)
            dfs(i, sub)
            sub.pop()
        }
    }
    dfs(1, [])
    console.log(ans)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 300 points

Problem Statement

Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ).

Consider a sequence A satisfying the following conditions:

A is a sequence of N positive integers.

1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M.

Let us define a score of this sequence as follows:

The score is the sum of d_i over all indices i such that A_{b_i} - A_{a_i} = c_i. (If there is no such i, the score is 0.)

Find the maximum possible score of A.

Constraints

All values in input are integers.

2 ≤ N ≤ 10

1 \leq M \leq 10

1 \leq Q \leq 50

1 \leq a_i < b_i \leq N ( i = 1, 2, ..., Q )

0 \leq c_i \leq M - 1 ( i = 1, 2, ..., Q )

(a_i, b_i, c_i) \neq (a_j, b_j, c_j) (where i \neq j)

1 \leq d_i \leq 10^5 ( i = 1, 2, ..., Q )

Input

Input is given from Standard Input in the following format:

N M Q
a_1 b_1 c_1 d_1
:
a_Q b_Q c_Q d_Q

Output

Print the maximum possible score of A.

Sample Input 1

3 4 3
1 3 3 100
1 2 2 10
2 3 2 10

Sample Output 1

110

When A = \{1, 3, 4\}, its score is 110. Under these conditions, no sequence has a score greater than 110, so the answer is 110.

Sample Input 2

4 6 10
2 4 1 86568
1 4 0 90629
2 3 0 90310
3 4 1 29211
3 4 3 78537
3 4 2 8580
1 2 1 96263
1 4 2 2156
1 2 0 94325
1 4 3 94328

Sample Output 2

357500

Sample Input 3

10 10 1
1 10 9 1

Sample Output 3

1


function getCombArr(len = 2, comb = 1) {
  //10進数まで　重複を許す組み合わせ
  const num = Math.pow(len, comb),
    makeArr = (v, i) => {
      const n = i.toString(len),
        padStr = "0".repeat(comb - n.length);
      return (padStr + n).split("");
    };
  return [...Array(num).keys()].map(makeArr);
  //console.log(getCombArr(3, 2)); // [['0','0'],['0','1'],['0','2'],['1','0'],['1','1'],['1','2'],['2','0'],['2','1'],['2','2']]
}
function getCombArrNoSame(len = 2, comb = 1) {
  //重複を許さない組み合わせ
  const num = Math.pow(len, comb),
    makeArr = (v, i) => {
      const n = i.toString(len),
        padStr = "0".repeat(comb - n.length);
      return (padStr + n).split("");
    };
  const fil = (v, i) => {
    const n = v.toString(len),
      padStr = "0".repeat(comb - n.length);
    const arr = (padStr + n).split("").map((n) => parseInt(n, 10));
    var frag = true;
    for (var i = 1; i < arr.length; i++) {
      if (arr[i - 1] > arr[i]) {
        frag = false;
        break;
      }
    }
    return frag;
  };
  return [...Array(num).keys()].filter(fil).map(makeArr);
  //console.log(getCombArrNoSame(3, 2)); // [['0','0'],['0','1'],['0','2'],['1','1'],['1','2'],['2','2']]
}

// 上記関数を利用しつつ、組み合わせを作成
function getComb(arr = [], comb = 1) {
  const base = getCombArr(arr.length, comb),
    convert = (v) => arr[v],
    makeArr = (comb) => comb.map(convert);
  return base.map(makeArr);
  //console.log(getComb(['a', 'b', 'c'], 2));
  //     [ 'a', 'a' ],
  //     [ 'a', 'b' ],
  //     [ 'a', 'c' ],
  //     [ 'b', 'a' ],
  //     [ 'b', 'b' ],
  //     [ 'b', 'c' ],
  //     [ 'c', 'a' ],
  //     [ 'c', 'b' ],
  //     [ 'c', 'c' ]
  //   ]
}
// 上記関数を利用しつつ、組み合わせを作成
function getCombNoSame(arr = [], comb = 1) {
  const base = getCombArrNoSame(arr.length, comb),
    convert = (v) => arr[v],
    makeArr = (comb) => comb.map(convert);
  return base.map(makeArr);
  //console.log(getComb(['a', 'b', 'c'], 2));
  //     [ 'a', 'a' ],
  //     [ 'a', 'b' ],
  //     [ 'a', 'c' ],
  //     [ 'b', 'b' ],
  //     [ 'b', 'c' ],
  //     [ 'c', 'c' ]
  //   ]
}

function Main(input) {
  input = input.trim().split("\n");
  const NMQ = input[0].split(" ");
  var N = parseInt(NMQ[0], 10);
  var M = parseInt(NMQ[1], 10);
  var Q = parseInt(NMQ[2], 10);
  var a = [];
  var b = [];
  var c = [];
  var d = [];
  var aaa = [];
  var max = 0;

  for (var i = 0; i < Q; i++) {
    var abcd = input[i + 1].split(" ");
    a = a.concat(parseInt(abcd[0], 10));
    b = b.concat(parseInt(abcd[1], 10));
    c = c.concat(parseInt(abcd[2], 10));
    d = d.concat(parseInt(abcd[3], 10));
  }
  for (var i = 0; i < M; i++) {
    aaa = aaa.concat(i + 1);
  }
  var comb = getCombNoSame(aaa, N);

  for (var i = 0; i < comb.length; i++) {
    var score = 0;
    for (var q = 0; q < Q; q++) {
      if (comb[i][b[q] - 1] - comb[i][a[q] - 1] == c[q]) {
        score += d[q];
      }
    }
    if (score > max) {
      max = score;
    }
  }
  console.log(max);
}

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


const Main = (input) => {
  const tmp = input.trim().split(' ').map(n => parseInt(n))
  const A = tmp[0]
  const B = tmp[1]
  const N = tmp[2]

  let x = Math.min(B - 1, N)

  const result = Math.floor(A * x / B) - (A * Math.floor(x / B))

  console.log(result)
  return result
}

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

Score : 400 points

Problem Statement

Given are integers A, B, and N.

Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.

Here floor(t) denotes the greatest integer not greater than the real number t.

Constraints

1 ≤ A ≤ 10^{6}

1 ≤ B ≤ 10^{12}

1 ≤ N ≤ 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B N

Output

Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.

Sample Input 1

5 7 4

Sample Output 1

2

When x=3, floor(Ax/B)-A×floor(x/B) = floor(15/7) - 5×floor(3/7) = 2. This is the maximum value possible.

Sample Input 2

11 10 9

Sample Output 2

9


"use strict";

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

    // for(let i=1; i<=N; i++) {
    //     let temp = Math.floor((A * i) / B) - (A * Math.floor(i / B));
    //     console.log(temp)
    // }

    let answer = -10e5;

    // 0が2回出た時点でループ
    if(A < B) {
        let cnt = 0;

        for(let i=1; i<=N; i++) {
            let temp = Math.floor((A * i) / B) - (A * Math.floor(i / B));

            answer = Math.max(answer, temp);

            if(temp === 0) cnt++;
            if(cnt === 2) break;
        }
    } else {
    // 0が初めて出た時点でループ
        for(let i=1; i<=N; i++) {
            let temp = Math.floor((A * i) / B) - (A * Math.floor(i / B));

            answer = Math.max(answer, temp);

            if(temp === 0) break;
        }
    }

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


// inputに入力データ全体が入る
function Main(input) {
	var ans = 0
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.trim().split("\n")
	// var arr = input.trim().split("\n")
	var n = input[0].split(' ').map(n => parseInt(n))
	var A = n[0]
	var B = n[1]
	var N = n[2]
	var cnt = N
	var p = 0
	while ( 0 < cnt) {
		var t = Math.floor(A * cnt / B) - A * Math.floor(cnt / B)
		if (ans < t ) {
			ans = t
			break
		} else if (t === 0 ) {
			p++
			if (p > 30) {
				break
			}
		}
		cnt--
	}

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


function main(input) {
    const parsedInput = parser(input);
    console.log(minX(parsedInput.a, parsedInput.b, parsedInput.n));
}

function parser(inputStr) {
    const splitInput = inputStr.split(' ');
    return {
        a: Number(splitInput[0]),
        b: Number(splitInput[1]),
        n: Number(splitInput[2]),
    };
}

function minX(a, b, n) {
    const results = [];
    for (var x = 1; x <= n; x++ ){
        results.push(Math.floor((a * x) / b) - a * Math.floor(x / b));
    }
    return Math.max(...results);
}
// test
// const Q1 = '5 7 4'
// const Q2 = '11 10 9';
// main(Q1);
// main(Q2);
// main(Q2);
// main(Q3);
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Scanner(input) {
	var self = this;
	self.itemNo = 0;
	self.orgStr = input;
	self.splitedStrs = (function(target) {
		var result = [];
		var target = target.replace(/[\n \t]+/g, " ");
		var strs = target.split(" ");
		for (var i = 0, len = strs.length; i < len; i++) {
			result.push(strs[i]);
		}
		return result;
	}(input));

	self.next = function() {
		var result = self.splitedStrs[self.itemNo];
		self.itemNo++;
		return (result != null) ? result : null;
	}

	self.nextInt = function() {
		var result = self.splitedStrs[self.itemNo];
		self.itemNo++;
		return (result != null) ? parseInt(result) : null;
	}

	self.nextBigDecimal = function() {
		var result = self.splitedStrs[self.itemNo];
		self.itemNo++;
		return (result != null) ? parseFloat(result) : null;
	}

	self.nextByte = function() {
		var result = self.splitedStrs[self.itemNo];
		self.itemNo++;
		return (result != null) ? new Int8Array(result) : null;
	}

}

function Main(sc) {

	var N = sc.nextInt();
	var M = sc.nextInt();
	var anss = [];

	if (N == M * 2 + 1) {
		for (var i = 0; i < M; i++) {
			var ans = (Math.floor(N / 2) - i) + " " + (Math.floor(N / 2) + i + 1);
			anss.push(ans);
		}
	} else {
		for (var i = 0; i < M; i++) {
			var start = 0;
			var skip = 0;
			if (i % 2 == 0) {
				start = parseInt(i / 2);
				skip = M - i;
			} else {
				start = parseInt(i / 2) + parseInt(N / 2) + 1;
				skip = M - i;
			}
			var ans = start + " " + (start + skip);
			anss.push(ans);
		}
	}

	console.log(anss.join("\n"));
}
Main(new Scanner(require("fs").readFileSync("/dev/stdin", "utf8")));
// Main(new Scanner("33"));

// var str1 = sc.next(); // Stringで取得
// var int1 = sc.nextInt(); // intで取得
// var bd1 = sc.nextBigDecimal(); // BigDecimalで取得
// var byte1 = sc.nextByte(); // byteで取得
// for (var i = 0; i < 1000000000; i++) var toDelay = "aaa"; // 1000msくらいの遅延

Score : 500 points

Problem Statement

You are going to hold a competition of one-to-one game called AtCoder Janken. (Janken is the Japanese name for Rock-paper-scissors.)
N players will participate in this competition, and they are given distinct integers from 1 through N.
The arena has M playing fields for two players. You need to assign each playing field two distinct integers between 1 and N (inclusive).
You cannot assign the same integer to multiple playing fields.
The competition consists of N rounds, each of which proceeds as follows:

For each player, if there is a playing field that is assigned the player's integer, the player goes to that field and fight the other player who comes there.

Then, each player adds 1 to its integer. If it becomes N+1, change it to 1.

You want to ensure that no player fights the same opponent more than once during the N rounds.
Print an assignment of integers to the playing fields satisfying this condition.
It can be proved that such an assignment always exists under the constraints given.

Constraints

1 \leq M

M \times 2 +1 \leq N \leq 200000

Input

Input is given from Standard Input in the following format:

N M

Output

Print M lines in the format below.
The i-th line should contain the two integers a_i and b_i assigned to the i-th playing field.

a_1 b_1
a_2 b_2
:
a_M b_M

Sample Input 1

4 1

Sample Output 1

2 3

Let us call the four players A, B, C, and D, and assume that they are initially given the integers 1, 2, 3, and 4, respectively.

The 1-st round is fought by B and C, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 2, 3, 4, and 1, respectively.

The 2-nd round is fought by A and B, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 3, 4, 1, and 2, respectively.

The 3-rd round is fought by D and A, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 4, 1, 2, and 3, respectively.

The 4-th round is fought by C and D, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 1, 2, 3, and 4, respectively.

No player fights the same opponent more than once during the four rounds, so this solution will be accepted.

Sample Input 2

7 3

Sample Output 2

1 6
2 5
3 4


const processData = (lines) => {
  let [n, m] = lines[0].split(' ').map(x => +x)
  if (n%2 === 1) {
    let end = n - 1
    let start = 1
    while (m) {
      console.log(`${start++} ${end--}`)
      m--
    }
  } else {
    let end = n/2+1
    let start = n/2
    while (m) {
      console.log(`${start--} ${end++}`)
      m--
    }
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})


function Scanner(input) {
	var self = this;
	self.itemNo = 0;
	self.orgStr = input;
	self.splitedStrs = (function(target) {
		var result = [];
		var target = target.replace(/[\n \t]+/g, " ");
		var strs = target.split(" ");
		for (var i = 0, len = strs.length; i < len; i++) {
			result.push(strs[i]);
		}
		return result;
	}(input));

	self.next = function() {
		var result = self.splitedStrs[self.itemNo];
		self.itemNo++;
		return (result != null) ? result : null;
	}

	self.nextInt = function() {
		var result = self.splitedStrs[self.itemNo];
		self.itemNo++;
		return (result != null) ? parseInt(result) : null;
	}

	self.nextBigDecimal = function() {
		var result = self.splitedStrs[self.itemNo];
		self.itemNo++;
		return (result != null) ? parseFloat(result) : null;
	}

	self.nextByte = function() {
		var result = self.splitedStrs[self.itemNo];
		self.itemNo++;
		return (result != null) ? new Int8Array(result) : null;
	}

}

function Main(sc) {

	var N = sc.nextInt();
	var anss = [];

	wrtnObj = {};
	for (var i = 0; i < N; i++) {
		wrtnObj[i + 1] = sc.nextInt();
	}

	orderedSubTree = {};
	for (var i = 0; i < N - 1; i++) {
		var n1 = sc.nextInt();
		var n2 = sc.nextInt();
		if (!orderedSubTree[n1]) orderedSubTree[n1] = [n2];
		else orderedSubTree[n1].push(n2);
		if (!orderedSubTree[n2]) orderedSubTree[n2] = [n1];
		else orderedSubTree[n2].push(n1);
	}

	// 木をたどって要素を順に取得していく
	wrtnNoLists = {};
	nexts = [];
	crawlNode = function (tgtNo, fromNo) {
		wrtnNos = (wrtnNoLists[fromNo]) ? wrtnNoLists[fromNo].concat() : [];
		// 自分の数字を詰め込んで、確定
		wrtnNos.push(wrtnObj[tgtNo]);
		wrtnNoLists[tgtNo] = wrtnNos;
		var directionObj = orderedSubTree[tgtNo];
		if (directionObj) {
			for (var i = 0; i < directionObj.length; i++) {
				var nextNo = directionObj[i];
				if (fromNo != nextNo) {
					nexts.push([nextNo, tgtNo]);
				}
			}
		}
	}

	nexts.push([1, -1]);
	for (var dbg = 0; dbg < 10000000; dbg++) {
		var next = nexts.shift();
		crawlNode(next[0], next[1]);
		if (nexts.length == 0) break;
	}
	console.log(wrtnNos);
	return;

	for (var i = 1; i <= N; i++) {

		var list = wrtnNoLists[i];
		var list2 = [];

		for (var j = 0; j < list.length; j++) {
			var wk = list[j];
			if (list2.length == 0) {
				list2.push(wk);
			}
			// 最終より大きい場合push
			else if (wk > list2[list2.length - 1]) {
				list2.push(wk);
			}
			// 最初より同じか小さい場合
			else if (wk <= list2[0]) {
				list2[0] = wk;
			}
			// 最初より大きくて最終より小さい場合、l[i-1]<wk<l[i]	となるl[i]とwkを置換する
			else {
				for (var k = 1; k < list2.length; k++) {
					if (list2[k-1] < wk && wk <= list2[k]) {
						list2[k] = wk;
						break;
					}
				}
			}
		}
		anss.push(list2.length);
	}

	console.log(anss.join("\n"));
}
Main(new Scanner(require("fs").readFileSync("/dev/stdin", "utf8")));
// Main(new Scanner("33"));

// var str1 = sc.next(); // Stringで取得
// var int1 = sc.nextInt(); // intで取得
// var bd1 = sc.nextBigDecimal(); // BigDecimalで取得
// var byte1 = sc.nextByte(); // byteで取得
// for (var i = 0; i < 1000000000; i++) var toDelay = "aaa"; // 1000msくらいの遅延
// console.log(wrtnNos); return;

Score : 600 points

Problem Statement

We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i.
Vertex i has an integer a_i written on it.
For every integer k from 1 through N, solve the following problem:

We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.

Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.

Constraints

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

1 \leq a_i \leq 10^9

1 \leq u_i , v_i \leq N

u_i \neq v_i

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

Output

Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.

Sample Input 1

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

Sample Output 1

1
2
3
3
4
4
5
2
2
3

For example, the sequence A obtained from the shortest path from Vertex 1 to Vertex 5 is 1,2,5,3,4. Its longest increasing subsequence is A_1, A_2, A_4, A_5, with the length of 4.


"use strict";
function main(input) {
    var line = input.split(" ");
    let S = parseInt(line[0]);
    let W = parseInt(line[1]);
    if(W>=S) console.log("unsafe");
    else console.log("safe");
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

There are S sheep and W wolves.

If the number of wolves is greater than or equal to that of sheep, the wolves will attack the sheep.

If the wolves will attack the sheep, print unsafe; otherwise, print safe.

Constraints

1 \leq S \leq 100

1 \leq W \leq 100

Input

Input is given from Standard Input in the following format:

S W

Output

If the wolves will attack the sheep, print unsafe; otherwise, print safe.

Sample Input 1

4 5

Sample Output 1

unsafe

There are four sheep and five wolves. The number of wolves is not less than that of sheep, so they will attack them.

Sample Input 2

100 2

Sample Output 2

safe

Many a sheep drive away two wolves.

Sample Input 3

10 10

Sample Output 3

unsafe


const main = (input) => {
  const args = input.split(' ');
  const s = parseInt(args[0], 10);
  const w = parseInt(args[1], 10);

  if (s > w) {
      console.log('safe');
  } else {
      console.log('unsafe');
  }
}

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


const main = input => {
  const i = input.split(" ").map(e => parseInt(e))
  const s = i[0]
  const w = i[1]
  return s <= w ? "unsafe" : "safe"
}

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


function Main(input) {
  input = input.split(' ');
  const sheeps = parseInt(input[0]);
  const wolves = parseInt(input[1]);
  console.log('%s', sheeps > wolves ? 'safe' : 'unsafe');
}

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


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


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

    input.splice(0, 1);

    input = new Set(input);
    input = Array.from(input);
    console.log(input.length);
}

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

Score : 300 points

Problem Statement

You drew lottery N times. In the i-th draw, you got an item of the kind represented by a string S_i.

How many kinds of items did you get?

Constraints

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

S_i consists of lowercase English letters and has a length between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

Print the number of kinds of items you got.

Sample Input 1

3
apple
orange
apple

Sample Output 1

2

You got two kinds of items: apple and orange.

Sample Input 2

5
grape
grape
grape
grape
grape

Sample Output 2

1

Sample Input 3

4
aaaa
a
aaa
aa

Sample Output 3

4


function main(input) {
  const lines = input.split("\n");
  const N = lines[0];

  const items = {}
  for(let i = 1; i <= N; i++) {
    const name = lines[i];
    items[name] = 1;
  }
  const res = Object.keys(items).length;

  console.log(res);
}

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


/**
 * @param {String} raw_input 入力
 */
function Main(raw_input) {
	const [ first, ...trail ] = raw_input.split("\n");
	const [n, m] = toNumArray(first);
	const aList = toNumArray(trail[0]);

	console.log(Math.max(-1, n - sum(aList)));
}

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

////////// ユーティリティ関数

/**
 * 文字列を数値配列
 * @param {String} str 文字列
 */
function toNumArray(str, delimitor = ' ') {
	return str.split(delimitor).map(s => parseInt(s, 10));
}

/**
 * 文字列をVigInt配列に変換する
 * @param {String} str 文字列
 */
function toBitIntArray(str, delimitor = ' ') {
	return str.split(delimitor).map(s => BigInt(s));
}

/**
 * 合計を出す
 * @param {Array<Number>} n 数値配列
 */
function sum(n) {
	return n.reduce((a, b) => a + b);
}

Score : 200 points

Problem Statement

Takahashi has N days of summer vacation.

His teacher gave him M summer assignments. It will take A_i days for him to do the i-th assignment.

He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.

What is the maximum number of days Takahashi can hang out during the vacation if he finishes all the assignments during this vacation?

If Takahashi cannot finish all the assignments during the vacation, print -1 instead.

Constraints

1 \leq N \leq 10^6

1 \leq M \leq 10^4

1 \leq A_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 ... A_M

Output

Print the maximum number of days Takahashi can hang out during the vacation, or -1.

Sample Input 1

41 2
5 6

Sample Output 1

30

For example, he can do the first assignment on the first 5 days, hang out on the next 30 days, and do the second assignment on the last 6 days of the vacation. In this way, he can safely spend 30 days hanging out.

Sample Input 2

10 2
5 6

Sample Output 2

-1

He cannot finish his assignments.

Sample Input 3

11 2
5 6

Sample Output 3

0

He can finish his assignments, but he will have no time to hang out.

Sample Input 4

314 15
9 26 5 35 8 9 79 3 23 8 46 2 6 43 3

Sample Output 4

9


function main(input) {
  const args = input.split('\n')
  const nm = args[0].split(' ')
  const n = Number(nm[0])
  const m = Number(nm[1])
  const works = args[1].split(' ').map(v => Number(v))
  const sum = works.reduce((prev, curr) => prev + curr)
  if (n < sum) {
    console.log(-1)
  } else {
    console.log(n - sum)
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'))


function compareNumber(a, b) {
    return Number(a) < Number(b);
}

function Main(input) {
  var lines = input.split('\n');
  var N = Number(lines[0]);
  var A = lines[1].split(' ');
  A.sort(compareNumber);
  var index = 0;
  var count;
  for (var i = 1; i <= N; i ++) {
    count = 0;
    while (Number(A[index]) == i && index < N) {
      index ++;
      count ++;
    }
    console.log(count);
  }
}

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

Score : 300 points

Problem Statement

A company has N members, who are assigned ID numbers 1, ..., N.

Every member, except the member numbered 1, has exactly one immediate boss with a smaller ID number.

When a person X is the immediate boss of a person Y, the person Y is said to be an immediate subordinate of the person X.

You are given the information that the immediate boss of the member numbered i is the member numbered A_i. For each member, find how many immediate subordinates it has.

Constraints

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

1 \leq A_i < i

Input

Input is given from Standard Input in the following format:

N
A_2 ... A_N

Output

For each of the members numbered 1, 2, ..., N, print the number of immediate subordinates it has, in its own line.

Sample Input 1

5
1 1 2 2

Sample Output 1

2
2
0
0
0

The member numbered 1 has two immediate subordinates: the members numbered 2 and 3.

The member numbered 2 has two immediate subordinates: the members numbered 4 and 5.

The members numbered 3, 4, and 5 do not have immediate subordinates.

Sample Input 2

10
1 1 1 1 1 1 1 1 1

Sample Output 2

9
0
0
0
0
0
0
0
0
0

Sample Input 3

7
1 2 3 4 5 6

Sample Output 3

1
1
1
1
1
1
0


'use strict';
const p = s => console.log(s);

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

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

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

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


function main(input) {
  let n,k = 0;
  [n, k] = input[0].trim().split(" ").map(i => parseInt(i));

  let sum = 0;

  function　sum1toN(n) {
    return n*(n+1)/2;
  }

  for(let i=k;i<=n+1;i++){
    const min = sum1toN(i-1);
    const max = sum1toN(n) - sum1toN(n-i);
    sum = (sum+(max-min+1))%(10**9+7);
  }
  console.log(sum);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"));


"use strict"
function main(arg) {
    var tmp = arg.trim().split("\n")[0].split(" ").map(Number)
    var N = tmp[0]
    var K = tmp[1]
    var counter = 0
    for (let i = K; i <= N + 1; i++) {
        var min = 0
        var max = 0
        for (var j = 0; j < i; j++) {
            min+=j
        }
        for (var j = N; j > N - i; j--) {
            max+=j
        }
        counter += (max-min) + 1
    }
    console.log(counter)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


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

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

function main(){
  var n = next();
  var a = [];
  for(var i = 0; i < n; i++){
    a.push([next(),i]);
  }
  a.sort((a,b)=>b[0]-a[0]);
  var dp = xArray(0,n+1);
  for(var i = 0; i < n; i++){
    dp[i+1] = dp[i] + (n-i-a[i][1]-1) * a[i][0];
    for(var j = i; j; j--){
      dp[j] += (a[i][1]-(i-j)) * a[i][0];
      var t = dp[j-1] + (n-j-a[i][1]) * a[i][0];
      if(dp[j] < t)dp[j] = t;
    }
    dp[0] += (a[i][1]-i) * a[i][0];
  }
  return Math.max(...dp);
}

Score : 500 points

Problem Statement

There are N children standing in a line from left to right. The activeness of the i-th child from the left is A_i.

You can rearrange these children just one time in any order you like.

When a child who originally occupies the x-th position from the left in the line moves to the y-th position from the left, that child earns A_x \times |x-y| happiness points.

Find the maximum total happiness points the children can earn.

Constraints

2 \leq N \leq 2000

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum total happiness points the children can earn.

Sample Input 1

4
1 3 4 2

Sample Output 1

20

If we move the 1-st child from the left to the 3-rd position from the left, the 2-nd child to the 4-th position, the 3-rd child to the 1-st position, and the 4-th child to the 2-nd position, the children earns 1 \times |1-3|+3 \times |2-4|+4 \times |3-1|+2 \times |4-2|=20 happiness points in total.

Sample Input 2

6
5 5 6 1 1 1

Sample Output 2

58

Sample Input 3

6
8 6 9 1 2 1

Sample Output 3

85