const SieveOfEratosthenes = (n) => {
    let flg = (new Array(n)).fill(0)/* set flg[i] to true when it is seived */
    let primes = []/* list of prime numbers */
    for(let i=2; i*i<=n; i++) {
        if(!flg[i]) {
            primes.push(i)
            for(let j=i; j*j<=n; j+=i) {
                flg[j] = 1
            }
        }
    }
    return primes
}

const factorizationBySoE = (n, primes) => {
    //const primes = SieveOfEratosthenes(n)
    let factors = {}
    primes.some(p => {
        if(n < p) return true
        while(n%p===0) {
            if(!factors[p])factors[p]=1
            else factors[p]++
            n/=p
        }
    })
    if(n>1)factors[n]=1
    return factors
}

const getGCD = (a,b) => {
    if(b===0)return a
    else if(a===0)return b
    return getGCD(b, a%b)
}

const main = (arg) => {
    const N = Number(arg.split("\n")[0])
    const a = arg.split("\n")[1].split(" ").map(Number)

    const MAX_A = 10**6+1

    //  check if p is in {a} (paircoprime)
    const primes = SieveOfEratosthenes(A)
//    return
    let set = [...new Array(MAX_A)].fill(0)
    isPairCoprime = true
    for(let i=0; i<N; i++) {
        const factors = Object.keys(factorizationBySoE(a[i], primes))
        for(let j=0; j<factors.length; j++ ) {
            // console.log(`i=${i}, j=${j}, ${factors[j]}`)
            // console.log(factors)
            if(set[factors[j]] === 1) {
                isPairCoprime = false
            }
            set[factors[j]] = 1
        }
    }
/*
    for(let i=0; i<N; i++) {
        set[a[i]]++
    }
//  return
    for(let i=2; i<MAX_A; i++) {
         let cnt=0
         for(let j=i; j<MAX_A; j+=i) {
             cnt+=set[j]
         }
        if(cnt>1) {
             isPairCoprime = false
         }
     }
 */
    if(isPairCoprime) {
        console.log("pairwise coprime")
        return
    }
     // return
    // setcoprime
    // let gcd = getGCD(a[0], a[1])
    let gcd = 0
    for(let i=0; i<a.length; i++) {
        gcd = getGCD(gcd, a[i])
        // console.log(gcd)
    }

    if(gcd===1) {
        console.log("setwise coprime")
        return
    }

    console.log("not coprime")
}

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

Score : 100 points

Problem Statement

Takahashi is meeting up with Aoki.

They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.

Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.

Will he arrive in time?

Constraints

1 \leq D \leq 10000

1 \leq T \leq 10000

1 \leq S \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

D T S

Output

If Takahashi will reach the place in time, print Yes; otherwise, print No.

Sample Input 1

1000 15 80

Sample Output 1

Yes

It takes 12.5 minutes to go 1000 meters to the place at a speed of 80 meters per minute. They have planned to meet in 15 minutes so he will arrive in time.

Sample Input 2

2000 20 100

Sample Output 2

Yes

It takes 20 minutes to go 2000 meters to the place at a speed of 100 meters per minute. They have planned to meet in 20 minutes so he will arrive just on time.

Sample Input 3

10000 1 1

Sample Output 3

No

He will be late.


var D = 1000;
var S = 80;
var T = 15;

if(D / S <= T){
  document.write('Yes');
}else{
  document.write('No');
}

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.


function Main(input) {
    input = input.trim().split(" ");
    const d = input[0];
    const t = input[1];
    const s = input[2];

    const arriveTime = d / s;
    if(arriveTime <= t) {
        console.log("Yes");
    } else {
        console.log("No");
    }
}

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


let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  const [d, t, s] = readLine()
    .split(" ")
    .map((n) => parseInt(n));

  if (s * t >= d) console.log("YES");
  else console.log("NO");
}


//let input = "codeforces\natcoder";

function main(input){
  input = input.trim();
  list = input.split("\n");
  let d = list[0];
  let s = list[1];
  console.log(d + " " + s);
  let answer = 1000;
  let temp = 0;
  for(let i=0; i<d.length - s.length; i++){
    temp = 0;
    for(let j=0; j<s.length; j++){
      let dStr = d.substr(i+j,1);
      let sStr = s.substr(j,1);
      if(dStr===sStr){
        //console.log(dStr + " " + sStr + " onaji");
      }else{
        //console.log(dStr + " " + sStr + " tigau");
        temp++;
      }
    } // j loop
    if(temp < answer){answer = temp;}
    //console.log(" ");
  } // i loop
  console.log(answer);
}
//main(input);
main(require("fs").readFileSync("dev/stdin","utf8"));

Score : 200 points

Problem Statement

Given are two strings S and T.

Let us change some of the characters in S so that T will be a substring of S.

At least how many characters do we need to change?

Here, a substring is a consecutive subsequence. For example, xxx is a substring of yxxxy, but not a substring of xxyxx.

Constraints

The lengths of S and T are each at least 1 and at most 1000.

The length of T is at most that of S.

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the minimum number of characters in S that need to be changed.

Sample Input 1

cabacc
abc

Sample Output 1

1

For example, changing the fourth character a in S to c will match the second through fourth characters in S to T.

Since S itself does not have T as its substring, this number of changes - one - is the minimum needed.

Sample Input 2

codeforces
atcoder

Sample Output 2

6


const dfs = (graph, visited, point) => {
    let count = 1
    visited.add(point)

    for (let p in graph[point]) {
        if (!visited.has(p)) {
            count += dfs(graph, visited, p)
        }
    }

    return count
}

const processData = (lines) => {
    const [n, m] = lines[0].split(' ').map( x => +x)
    let friendships = {}
    for (let i=0; i<m; i++) {
        const f = lines[i+1].split(' ').map(x => +x)
        if (!friendships[f[0]]) {
            friendships[f[0]] = {}
        }
        if (!friendships[f[1]]) {
            friendships[f[1]] = {}
        }
        friendships[f[0]][f[1]] = true
        friendships[f[1]][f[0]] = true
    }

    let maxCount = 1
    let visited = new Set()
    for (let p in friendships) {
        if (!visited.has(p)) {
            maxCount = Math.max(maxCount, dfs(friendships, visited, p))
        }
    }

    console.log(maxCount)
}

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)
})

Score : 400 points

Problem Statement

There are N persons called Person 1 through Person N.

You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times.

If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts.

Takahashi the evil wants to divide the N persons into some number of groups so that every person has no friend in his/her group.

At least how many groups does he need to make?

Constraints

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

0 \leq M \leq 2\times 10^5

1\leq A_i,B_i\leq N

A_i \neq B_i

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
\vdots
A_M B_M

Output

Print the answer.

Sample Input 1

5 3
1 2
3 4
5 1

Sample Output 1

3

Dividing them into three groups such as \{1,3\}, \{2,4\}, and \{5\} achieves the goal.

Sample Input 2

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

Sample Output 2

4

Sample Input 3

10 4
3 1
4 1
5 9
2 6

Sample Output 3

3


function Main(input) {
  const LINES = input.split("\n");
  const N = parseInt(LINES[0]);
  const X = parseInt(LINES[1]);
  const T = parseInt(LINES[2]);

  let answer = 0;
  answer = Math.floor(N / X) * T;
  if N % X != 0{
    answer += T;
  }

  console.log(answer);

}
// デバッグ用
function debug(){
var input = document.getElementById("input").value;
Main(input);
}

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

Score : 100 points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.

How long does it take to make N takoyaki?

Constraints

1 \leq N,X,T \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X T

Output

Print an integer representing the minimum number of minutes needed to make N pieces of takoyaki.

Sample Input 1

20 12 6

Sample Output 1

12

He can make 12 pieces of takoyaki in the first 6 minutes and 8 more in the next 6 minutes, so he can make 20 in a total of 12 minutes.

Note that being able to make 12 in 6 minutes does not mean he can make 2 in 1 minute.

Sample Input 2

1000 1 1000

Sample Output 2

1000000

It seems to take a long time to make this kind of takoyaki.


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	const inputLines = input.split("\n");
	const line0 = inputLines[0];
	var mySum = 0;
	for (var i = 0; i < line0.length; i++) {
		var a = line0.substr(i, 1);
		mySum += parseInt(a, 10);
	}

	console.log(mySum%9 === 0 ? "Yes" : "No");

	// tmp = input[1].split(" ");
	// //文字列から10進数に変換するときはparseIntを使います
	// var a = parseInt(input[0], 10);
	// var b = parseInt(tmp[0], 10);
	// var c = parseInt(tmp[1], 10);
	// var s = input[2];

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

// node index.js
// 1
// 2 3
// test
// (Ctrl + D)

Score : 200 points

Problem Statement

An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.

Determine whether N is a multiple of 9.

Constraints

0 \leq N < 10^{200000}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a multiple of 9, print Yes; otherwise, print No.

Sample Input 1

123456789

Sample Output 1

Yes

The sum of these digits is 1+2+3+4+5+6+7+8+9=45, which is a multiple of 9, so 123456789 is a multiple of 9.

Sample Input 2

0

Sample Output 2

Yes

Sample Input 3

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280

Sample Output 3

No


function main(lines) {
  const [H, W] = na();
  const [Ch, Cw] = sa().map(v => v-1);
  const [Dh, Dw] = sa().map(v => v-1);
  const maze = getLines(H);

  const deque = [[Ch, Cw, 0]];
  const done = Array(H).fill(0).map(_ => Array(W).fill(false));
  while (deque.length) {
    const [h, w, cost] = deque.pop();
    if (h == Dh && w == Dw) return cost;
    done[h][w] = true;
    for (let _h = h-2; _h <= h+2; _h++) {
      if (!maze[_h]) continue;
      for (let _w = w-2; _w <= w+2; _w++) {
        if (maze[_h][_w] != '.' || done[_h][_w]) continue;
        if (Math.hypot(_h-h, _w-w) <= 1) {
          deque.push([_h, _w, cost]);
        } else {
          deque.unshift([_h, _w, cost+1]);
        }
      }
    }
  }
  return -1;
}

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

let lineCount = 0;
const s = () => lines[lineCount++];
const n = () => Number(s());
const b = () => BigInt(s());
const sa = () => s().split(' ');
const na = () => sa().map(Number);
const ba = () => sa().map(BigInt);
const getLines = (n) => lines.slice(lineCount, lineCount += n);

const ans = main(lines);
console.log( ans );

Score : 400 points

Problem Statement

A maze is composed of a grid of H \times W squares - H vertical, W horizontal.

The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is ..

There is a magician in (C_h,C_w). He can do the following two kinds of moves:

Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.

Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.

In either case, he cannot go out of the maze.

At least how many times does he need to use the magic to reach (D_h, D_w)?

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

S_{C_h C_w} and S_{D_h D_w} are ..

(C_h,C_w) \neq (D_h,D_w)

Input

Input is given from Standard Input in the following format:

H W
C_h C_w
D_h D_w
S_{11}\ldots S_{1W}
\vdots
S_{H1}\ldots S_{HW}

Output

Print the minimum number of times the magician needs to use the magic. If he cannot reach (D_h,D_w), print -1 instead.

Sample Input 1

4 4
1 1
4 4
..#.
..#.
.#..
.#..

Sample Output 1

1

For example, by walking to (2,2) and then using the magic to travel to (4,4), just one use of magic is enough.

Note that he cannot walk diagonally.

Sample Input 2

4 4
1 4
4 1
.##.
####
####
.##.

Sample Output 2

-1

He cannot move from there.

Sample Input 3

4 4
2 2
3 3
....
....
....
....

Sample Output 3

0

No use of magic is needed.

Sample Input 4

4 5
1 2
2 5
#.###
####.
#..##
#..##

Sample Output 4

2


let magicCount=0
function main(arg) {

    let [h,w] = arg.split("\n")[0].split(" ").map(x=>Number(x))
    let [ch,cw] = arg.split("\n")[1].split(" ").map(x=>Number(x))
    let [dh,dw] = arg.split("\n")[2].split(" ").map(x=>Number(x))
    let input = arg.split("\n")

    input.shift()
    input.shift()
    input.shift()
    let s = []
    for(let i=0; i<h; i++) {
        let sw = []
        for(let j=0; j<w; j++) {
            sw.push(input[i].split("")[j])

        }
        s.push(sw)
    }

    // seen: 0 is for unsearched yet. -1 is no need for search.
    let seen = []
    for(let i=0; i<h; i++) {
        let _seen = []
        for(let j=0; j<w; j++) {
            if(s[i][j]==="."){
                _seen.push(false)
            } else {
                _seen.push(false)
            }
        }
        seen.push(_seen)
    }
    //console.log(seen)

    //let magicCount = 0
    //while(true) {
        dfs(s,ch-1,cw-1,seen,h,w,dh-1,dw-1)
        if(seen[dh-1][dw-1]===true) {
            //break
        } else {
            // magic will be used
            //dfs(s,ch-1,cw-1,seen,h,w,true)
            //magicCount++
        }
//break
    // }

    console.log(magicCount)
    //console.log(seen)

}

function dfs(field,h,w,seen,H,W,dh,dw) {
    //return
    seen[h][w] = true;
    //console.log(seen)
//return
    let dx = [1, 0, -1, 0]
    let dy = [0, 1, 0, -1]
    //dx = dx.map(x=>x*magic)
    //dy = dy.map(y=>y*magic)
// 四方向を探索
    for (let dir = 0; dir < 4; ++dir) {
        let nh = h + dx[dir];
        let nw = w + dy[dir];

        // 場外アウトしたり、移動先が壁の場合はスルー
        if (nh < 0 || nh >= H || nw < 0 || nw >= W) continue;
        if (field[nh][nw] == '#') continue;

        // 移動先が探索済みの場合
        if (seen[nh][nw]) continue;

        // 再帰的に探索
        dfs(field, nh, nw, seen, H, W,dh,dw);
    }

    for (let dir_x = 0; dir_x < 5; ++dir_x) {
        for (let dir_y = 0; dir_y < 5; ++dir_y) {
            let nh = h + dir_x;
            let nw = w + dir_y;

            // 場外アウトしたり、移動先が壁の場合はスルー
            if (nh < 0 || nh >= H || nw < 0 || nw >= W) continue;
            if (field[nh][nw] == '#') continue;

            // 移動先が探索済みの場合
            if (seen[nh][nw]) continue;

            // 再帰的に探索
            dfs(field, nh, nw, seen, H, W,dh,dw);
            magicCount++
        }
    }
}

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


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

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

function main(){
  var n = next();
  var dp = xArray(-1,n,n), mx = 0, add = 0;
  var a = nexts(2).sort((a,b)=>a-b).map(a=>a-1);
  var q = [];
  var map = xArray(0,n);
  dp[a[0]][a[1]] = 0;
  map[a[0]]++, map[a[1]]++;
  for(var i = 1; i < n; i++){
    a = nexts(3).sort((a,b)=>a-b).map(a=>a-1);
    if(a[0] === a[2]){
      add++;
      continue;
    }
    q = [];
    solve(a[0],a[0],a[1],a[2]);
    if(a[0] !== a[1])solve(a[1],a[1],a[0],a[2]);
    else{
      for(var j = 0; j < a[0]; j++){
        solve(j,a[0],j,a[2]);
      }
      for(var j = a[0]+1; j < a[2]; j++){
        solve(a[0],j,j,a[2]);
      }
      for(var j = a[2]; j < n; j++){
        solve(a[0],j,a[2],j);
      }
    }
    if(a[1] !== a[2])solve(a[2],a[2],a[0],a[1]);
    else{
      for(var j = 0; j < a[0]; j++){
        solve(j,a[1],j,a[0]);
      }
      for(var j = a[0]; j < a[2]; j++){
        solve(j,a[2],a[0],j);
      }
      for(var j = a[2]+1; j < n; j++){
        solve(a[2],j,a[0],j);
      }
    }
    while(q.length){
      var w = q.pop(), v = q.pop(), u = q.pop();
      dp[u][v] = Math.max(dp[u][v], w);
    }
    for(var j = 0; j < 3; j++){
      var t = a[j];
      if(map[t] === 1)map[t] = 2, dp[t][t] = Math.max(0,dp[t][t]);
      else if(map[t] === 0){
        map[t] = 1;
        for(var k = 0; k < t; k++){
          if(map[k] === 0)continue;
          dp[k][t] = Math.max(0,dp[k][t]);
        }
        for(var k = t+1; k < n; k++){
          if(map[k] === 0)continue;
          dp[t][k] = Math.max(0,dp[t][k]);
        }
      }
    }
  }
  a = next()-1;
  solve(a,a,a,a);
  return mx+add;
  function solve(t,u,v,w){
    var x = Math.max(dp[v][w], dp[t][u]+1);
    q.push(v,w,x);
    mx = Math.max(mx,x);
  }
}

Score : 600 points

Problem Statement

We have 3N cards arranged in a row from left to right, where each card has an integer between 1 and N (inclusive) written on it. The integer written on the i-th card from the left is A_i.

You will do the following operation N-1 times:

Rearrange the five leftmost cards in any order you like, then remove the three leftmost cards. If the integers written on those three cards are all equal, you gain 1 point.

After these N-1 operations, if the integers written on the remaining three cards are all equal, you will gain 1 additional point.

Find the maximum number of points you can gain.

Constraints

1 \leq N \leq 2000

1 \leq A_i \leq N

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_{3N}

Output

Print the maximum number of points you can gain.

Sample Input 1

2
1 2 1 2 2 1

Sample Output 1

2

Let us rearrange the five leftmost cards so that the integers written on the six cards will be 2\ 2\ 2\ 1\ 1\ 1 from left to right.

Then, remove the three leftmost cards, all of which have the same integer 2, gaining 1 point.

Now, the integers written on the remaining cards are 1\ 1\ 1.

Since these three cards have the same integer 1, we gain 1 more point.

In this way, we can gain 2 points - which is the maximum possible.

Sample Input 2

3
1 1 2 2 3 3 3 2 1

Sample Output 2

1

Sample Input 3

3
1 1 2 2 2 3 3 3 1

Sample Output 3

3


function Main(input){
const a = input.trim();
  if(a.includes('R')) {
    console.log(1);
  }else if(a.includes('RR')) {
      console.log(2);
    } else if(a.includes('RRR')) {
      console.log(3);
    } else {
      console.log(0);
  }
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

We have weather records at AtCoder Town for some consecutive three days. A string of length 3, S, represents the records - if the i-th character is S, it means it was sunny on the i-th day; if that character is R, it means it was rainy on that day.

Find the maximum number of consecutive rainy days in this period.

Constraints

|S| = 3

Each character of S is S or R.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of consecutive rainy days in the period.

Sample Input 1

RRS

Sample Output 1

2

We had rain on the 1-st and 2-nd days in the period. Here, the maximum number of consecutive rainy days is 2, so we should print 2.

Sample Input 2

SSS

Sample Output 2

0

It was sunny throughout the period. We had no rainy days, so we should print 0.

Sample Input 3

RSR

Sample Output 3

1

We had rain on the 1-st and 3-rd days - two "streaks" of one rainy day, so we should print 1.


'use strict';Object.defineProperty(exports,'__esModule',{value:true});var fs=require('fs');var _length = function (xs) {
  return xs.length;
};
var _indexImpl = function (just) {
  return function (nothing) {
    return function (xs) {
      return function (i) {
        return i < 0 || i >= xs.length ? nothing : just(xs[i]);
      };
    };
  };
};
var _concat = function (xss) {
  if (xss.length <= 10000) {
    return Array.prototype.concat.apply([], xss);
  }
  var result = [];
  for (var i = 0, l = xss.length; i < l; i++) {
    var xs = xss[i];
    for (var j = 0, m = xs.length; j < m; j++) {
      result.push(xs[j]);
    }
  }
  return result;
};var _arrayMap = function (f) {
  return function (arr) {
    var l = arr.length;
    var result = new Array(l);
    for (var i = 0; i < l; i++) {
      result[i] = f(arr[i]);
    }
    return result;
  };
};var Semigroupoid = function (compose) {
    this.compose = compose;
};
var semigroupoidFn = new Semigroupoid(function (f) {
    return function (g) {
        return function (x) {
            return f(g(x));
        };
    };
});
var compose = function (dict) {
    return dict.compose;
};var flip = function (f) {
    return function (b) {
        return function (a) {
            return f(a)(b);
        };
    };
};
var $$const = function (a) {
    return function (v) {
        return a;
    };
};var _unit = {};var _showIntImpl = function (n) {
  return n.toString();
};var Show = function (show) {
    this.show = show;
};
var showInt = new Show(_showIntImpl);
var show = function (dict) {
    return dict.show;
};var Functor = function (map) {
    this.map = map;
};
var map = function (dict) {
    return dict.map;
};
var mapFlipped = function (dictFunctor) {
    return function (fa) {
        return function (f) {
            return map(dictFunctor)(f)(fa);
        };
    };
};
var $$void = function (dictFunctor) {
    return map(dictFunctor)($$const(_unit));
};
var functorFn = new Functor(compose(semigroupoidFn));
var functorArray = new Functor(_arrayMap);var _concatArray = function (xs) {
  return function (ys) {
    if (xs.length === 0) return ys;
    if (ys.length === 0) return xs;
    return xs.concat(ys);
  };
};var Semigroup = function (append) {
    this.append = append;
};
var semigroupArray = new Semigroup(_concatArray);
var append = function (dict) {
    return dict.append;
};var Alt = function (Functor0, alt) {
    this.Functor0 = Functor0;
    this.alt = alt;
};
var altArray = new Alt(function () {
    return functorArray;
}, append(semigroupArray));var _arrayApply = function (fs) {
  return function (xs) {
    var l = fs.length;
    var k = xs.length;
    var result = new Array(l * k);
    var n = 0;
    for (var i = 0; i < l; i++) {
      var f = fs[i];
      for (var j = 0; j < k; j++) {
        result[n++] = f(xs[j]);
      }
    }
    return result;
  };
};var Category = function (Semigroupoid0, identity) {
    this.Semigroupoid0 = Semigroupoid0;
    this.identity = identity;
};
var identity = function (dict) {
    return dict.identity;
};
var categoryFn = new Category(function () {
    return semigroupoidFn;
}, function (x) {
    return x;
});var Apply = function (Functor0, apply) {
    this.Functor0 = Functor0;
    this.apply = apply;
};
var applyArray = new Apply(function () {
    return functorArray;
}, _arrayApply);
var apply = function (dict) {
    return dict.apply;
};var Applicative = function (Apply0, pure) {
    this.Apply0 = Apply0;
    this.pure = pure;
};
var pure = function (dict) {
    return dict.pure;
};
var liftA1 = function (dictApplicative) {
    return function (f) {
        return function (a) {
            return apply(dictApplicative.Apply0())(pure(dictApplicative)(f))(a);
        };
    };
};var _arrayBind = function (arr) {
  return function (f) {
    var result = [];
    for (var i = 0, l = arr.length; i < l; i++) {
      Array.prototype.push.apply(result, f(arr[i]));
    }
    return result;
  };
};var Bind = function (Apply0, bind) {
    this.Apply0 = Apply0;
    this.bind = bind;
};
var bindArray = new Bind(function () {
    return applyArray;
}, _arrayBind);
var bind = function (dict) {
    return dict.bind;
};var Monad = function (Applicative0, Bind1) {
    this.Applicative0 = Applicative0;
    this.Bind1 = Bind1;
};
var ap = function (dictMonad) {
    return function (f) {
        return function (a) {
            return bind(dictMonad.Bind1())(f)(function (f$prime) {
                return bind(dictMonad.Bind1())(a)(function (a$prime) {
                    return pure(dictMonad.Applicative0())(f$prime(a$prime));
                });
            });
        };
    };
};var Bifunctor = function (bimap) {
    this.bimap = bimap;
};
var bimap = function (dict) {
    return dict.bimap;
};var _foldrArray = function (f) {
  return function (init) {
    return function (xs) {
      var acc = init;
      var len = xs.length;
      for (var i = len - 1; i >= 0; i--) {
        acc = f(xs[i])(acc);
      }
      return acc;
    };
  };
};
var _foldlArray = function (f) {
  return function (init) {
    return function (xs) {
      var acc = init;
      var len = xs.length;
      for (var i = 0; i < len; i++) {
        acc = f(acc)(xs[i]);
      }
      return acc;
    };
  };
};var Plus = function (Alt0, empty) {
    this.Alt0 = Alt0;
    this.empty = empty;
};var refEq = function (r1) {
  return function (r2) {
    return r1 === r2;
  };
};var Eq = function (eq) {
    this.eq = eq;
};
var eqChar = new Eq(refEq);
var eq = function (dict) {
    return dict.eq;
};var _boolConj = function (b1) {
  return function (b2) {
    return b1 && b2;
  };
};
var _boolDisj = function (b1) {
  return function (b2) {
    return b1 || b2;
  };
};
var _boolNot = function (b) {
  return !b;
};var HeytingAlgebra = function (conj, disj, ff, implies, not, tt) {
    this.conj = conj;
    this.disj = disj;
    this.ff = ff;
    this.implies = implies;
    this.not = not;
    this.tt = tt;
};
var not = function (dict) {
    return dict.not;
};
var disj = function (dict) {
    return dict.disj;
};
var heytingAlgebraBoolean = new HeytingAlgebra(_boolConj, _boolDisj, false, function (a) {
    return function (b) {
        return disj(heytingAlgebraBoolean)(not(heytingAlgebraBoolean)(a))(b);
    };
}, _boolNot, true);var Monoid = function (Semigroup0, mempty) {
    this.Semigroup0 = Semigroup0;
    this.mempty = mempty;
};
var mempty = function (dict) {
    return dict.mempty;
};var Nothing = function () {
    function Nothing() {}    Nothing.value = new Nothing();
    return Nothing;
}();
var Just = function () {
    function Just(value0) {
        this.value0 = value0;
    }    Just.create = function (value0) {
        return new Just(value0);
    };
    return Just;
}();
var maybe = function (v) {
    return function (v1) {
        return function (v2) {
            if (v2 instanceof Nothing) {
                return v;
            }            if (v2 instanceof Just) {
                return v1(v2.value0);
            }            throw new Error("Failed pattern match at Data.Maybe (line 217, column 1 - line 217, column 51): " + [v.constructor.name, v1.constructor.name, v2.constructor.name]);
        };
    };
};
var isNothing = maybe(true)($$const(false));
var functorMaybe = new Functor(function (v) {
    return function (v1) {
        if (v1 instanceof Just) {
            return new Just(v(v1.value0));
        }        return Nothing.value;
    };
});
var fromJust = function (dictPartial) {
    return function (v) {
        if (v instanceof Just) {
            return v.value0;
        }        throw new Error("Failed pattern match at Data.Maybe (line 268, column 1 - line 268, column 46): " + [v.constructor.name]);
    };
};var Foldable = function (foldMap, foldl, foldr) {
    this.foldMap = foldMap;
    this.foldl = foldl;
    this.foldr = foldr;
};
var foldr = function (dict) {
    return dict.foldr;
};
var foldl = function (dict) {
    return dict.foldl;
};
var foldMapDefaultR = function (dictFoldable) {
    return function (dictMonoid) {
        return function (f) {
            return foldr(dictFoldable)(function (x) {
                return function (acc) {
                    return append(dictMonoid.Semigroup0())(f(x))(acc);
                };
            })(mempty(dictMonoid));
        };
    };
};
var foldableArray = new Foldable(function (dictMonoid) {
    return foldMapDefaultR(foldableArray)(dictMonoid);
}, _foldlArray, _foldrArray);
var find = function (dictFoldable) {
    return function (p) {
        var go = function (v) {
            return function (v1) {
                if (v instanceof Nothing && p(v1)) {
                    return new Just(v1);
                }                return v;
            };
        };
        return foldl(dictFoldable)(go)(Nothing.value);
    };
};var semigroupFirst = new Semigroup(function (v) {
    return function (v1) {
        if (v instanceof Just) {
            return v;
        }        return v1;
    };
});
var monoidFirst = new Monoid(function () {
    return semigroupFirst;
}, Nothing.value);
var functorFirst = functorMaybe;
var altFirst = new Alt(function () {
    return functorFirst;
}, append(semigroupFirst));
var plusFirst = new Plus(function () {
    return altFirst;
}, mempty(monoidFirst));var semigroupLast = new Semigroup(function (v) {
    return function (v1) {
        if (v1 instanceof Just) {
            return v1;
        }        if (v1 instanceof Nothing) {
            return v;
        }        throw new Error("Failed pattern match at Data.Maybe.Last (line 52, column 1 - line 54, column 36): " + [v.constructor.name, v1.constructor.name]);
    };
});
var monoidLast = new Monoid(function () {
    return semigroupLast;
}, Nothing.value);
var functorLast = functorMaybe;
var altLast = new Alt(function () {
    return functorLast;
}, append(semigroupLast));
var plusLast = new Plus(function () {
    return altLast;
}, mempty(monoidLast));var _pureE = function (a) {
  return function () {
    return a;
  };
};
var _bindE = function (a) {
  return function (f) {
    return function () {
      return f(a())();
    };
  };
};var monadEffect = new Monad(function () {
    return applicativeEffect;
}, function () {
    return bindEffect;
});
var bindEffect = new Bind(function () {
    return applyEffect;
}, _bindE);
var applyEffect = new Apply(function () {
    return functorEffect;
}, ap(monadEffect));
var applicativeEffect = new Applicative(function () {
    return applyEffect;
}, _pureE);
var functorEffect = new Functor(liftA1(applicativeEffect));var _map_ = function (f) {
  return function (a) {
    return function () {
      return f(a());
    };
  };
};
var _new = function (val) {
  return function () {
    return { value: val };
  };
};
var _read = function (ref) {
  return function () {
    return ref.value;
  };
};
var _modify$prime = function (f) {
  return function (ref) {
    return function () {
      var t = f(ref.value);
      ref.value = t.state;
      return t.value;
    };
  };
};
var _write = function (a) {
  return function (ref) {
    return function () {
      return ref.value = a;
    };
  };
};var modify = function (f) {
    return _modify$prime(function (s) {
        var s$prime = f(s);
        return {
            state: s$prime,
            value: s$prime
        };
    });
};
var functorST = new Functor(_map_);var _empty = function () {
  return [];
};
var _pushAll = function (as) {
  return function (xs) {
    return function () {
      return xs.push.apply(xs, as);
    };
  };
};
var _unsafeFreeze = function (xs) {
  return function () {
    return xs;
  };
};var push = function (a) {
    return _pushAll([a]);
};var Iterator = function () {
    function Iterator(value0, value1) {
        this.value0 = value0;
        this.value1 = value1;
    }    Iterator.create = function (value0) {
        return function (value1) {
            return new Iterator(value0, value1);
        };
    };
    return Iterator;
}();
var peek = function (v) {
    return function __do() {
        var i = _read(v.value1)();
        return v.value0(i);
    };
};
var next = function (v) {
    return function __do() {
        var i = _read(v.value1)();
        modify(function (v1) {
            return v1 + 1 | 0;
        })(v.value1)();
        return v.value0(i);
    };
};
var pushWhile = function (p) {
    return function (iter) {
        return function (array) {
            return function __do() {
                var $$break = _new(false)();
                while (map(functorST)(not(heytingAlgebraBoolean))(_read($$break))()) {
                    (function __do() {
                        var mx = peek(iter)();
                        if (mx instanceof Just && p(mx.value0)) {
                            push(mx.value0)(array)();
                            return $$void(functorST)(next(iter))();
                        }                        return $$void(functorST)(_write(true)($$break))();
                    })();
                }                return {};
            };
        };
    };
};
var iterator = function (f) {
    return map(functorST)(Iterator.create(f))(_new(0));
};
var iterate = function (iter) {
    return function (f) {
        return function __do() {
            var $$break = _new(false)();
            while (map(functorST)(not(heytingAlgebraBoolean))(_read($$break))()) {
                (function __do() {
                    var mx = next(iter)();
                    if (mx instanceof Just) {
                        return f(mx.value0)();
                    }                    if (mx instanceof Nothing) {
                        return $$void(functorST)(_write(true)($$break))();
                    }                    throw new Error("Failed pattern match at Data.Array.ST.Iterator (line 42, column 5 - line 44, column 47): " + [mx.constructor.name]);
                })();
            }            return {};
        };
    };
};
var exhausted = function () {
    var $13 = map(functorST)(isNothing);
    return function ($14) {
        return $13(peek($14));
    };
}();var Tuple = function () {
    function Tuple(value0, value1) {
        this.value0 = value0;
        this.value1 = value1;
    }    Tuple.create = function (value0) {
        return function (value1) {
            return new Tuple(value0, value1);
        };
    };
    return Tuple;
}();
var bifunctorTuple = new Bifunctor(function (f) {
    return function (g) {
        return function (v) {
            return new Tuple(f(v.value0), g(v.value1));
        };
    };
});var singleton = function (a) {
    return [a];
};
var index = _indexImpl(Just.create)(Nothing.value);
var unzip = function (xs) {
    return function __do() {
        var fsts = _empty();
        var snds = _empty();
        var iter = iterator(function (v) {
            return index(xs)(v);
        })();
        iterate(iter)(function (v) {
            return function __do() {
                $$void(functorST)(push(v.value0)(fsts))();
                return $$void(functorST)(push(v.value1)(snds))();
            };
        })();
        var fsts$prime = _unsafeFreeze(fsts)();
        var snds$prime = _unsafeFreeze(snds)();
        return new Tuple(fsts$prime, snds$prime);
    }();
};
var head = function (xs) {
    return index(xs)(0);
};
var groupBy = function (op) {
    return function (xs) {
        return function __do() {
            var result = _empty();
            var iter = iterator(function (v) {
                return index(xs)(v);
            })();
            iterate(iter)(function (x) {
                return $$void(functorST)(function __do() {
                    var sub = _empty();
                    push(x)(sub)();
                    pushWhile(op(x))(iter)(sub)();
                    var grp = _unsafeFreeze(sub)();
                    return push(grp)(result)();
                });
            })();
            return _unsafeFreeze(result)();
        }();
    };
};
var group = function (dictEq) {
    return function (xs) {
        return groupBy(eq(dictEq))(xs);
    };
};
var concatMap = flip(bind(bindArray));
var mapMaybe = function (f) {
    return concatMap(function () {
        var $94 = maybe([])(singleton);
        return function ($95) {
            return $94(f($95));
        };
    }());
};
var catMaybes = mapMaybe(identity(categoryFn));var functorNonEmptyArray = functorArray;
var bindNonEmptyArray = bindArray;var _unsafeCoerce = function (x) {
  return x;
};var unsafeFromArray = _unsafeCoerce;
var toArray = _unsafeCoerce;
var unzip$1 = function () {
    var $43 = bimap(bifunctorTuple)(unsafeFromArray)(unsafeFromArray);
    return function ($44) {
        return $43(unzip(toArray($44)));
    };
}();
var concatMap$1 = flip(bind(bindNonEmptyArray));
var concat = function () {
    var $60 = map(functorNonEmptyArray)(toArray);
    return function ($61) {
        return unsafeFromArray(_concat(toArray($60($61))));
    };
}();
var adaptMaybe = function (f) {
    var $64 = fromJust();
    return function ($65) {
        return $64(f(toArray($65)));
    };
};
var head$1 = adaptMaybe(head);
var adaptAny = function (f) {
    return function ($67) {
        return f(toArray($67));
    };
};
var length = adaptAny(_length);var _toCharArray = function (s) {
  return s.split("");
};var solve = function () {
    var count = function (s) {
        var v = function (v1) {
            {
                return 0;
            }        };
        var $4 = function () {
            var $6 = find(foldableArray)(function (na) {
                return head$1(na) === "R";
            });
            var $7 = group(eqChar);
            return function ($8) {
                return $6($7($8));
            };
        }()(_toCharArray(s));
        if ($4 instanceof Just) {
            return length($4.value0);
        }        return v();
    };
    var $9 = show(showInt);
    return function ($10) {
        return $9(count($10));
    };
}();var _readAll = function () {
  return function () {
    return fs.readFileSync("/dev/stdin", "utf8");
  };
};var _log = function (s) {
  return function () {
    console.log(s);
    return {};
  };
};var interact = function (solve) {
    return bind(bindEffect)(mapFlipped(functorEffect)(_readAll())(solve))(_log);
};var main = interact(solve);
var _default = {
    main: main
};exports.__reserved_default=_default;exports.main=main;
main();


inp = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n')
N = inp.shift() * 1
l = inp.shift().split(' ').map(x => +x).sort((a, b) => a - b)
c = 0
for (i=0; i<N-2; i++) {
  for (j=i+1; j<N-1; j++) {
      if (l[i] == l[j]) {
          continue;
      }
      len = l[i] + l[j]
      for (k=j+1; k<N; k++) {
          if (l[i] == l[k] || l[j] == l[k]) {
              continue;
          }
          if (l[k] < len) {
              c++
          }
      }
  }
}
console.log(c)

Score : 200 points

Problem Statement

We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i.

In how many ways can we choose three of the sticks with different lengths that can form a triangle?

That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions:

L_i, L_j, and L_k are all different.

There exists a triangle whose sides have lengths L_i, L_j, and L_k.

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 \cdots L_N

Output

Print the number of ways to choose three of the sticks with different lengths that can form a triangle.

Sample Input 1

5
4 4 9 7 5

Sample Output 1

5

The following five triples (i, j, k) satisfy the conditions: (1, 3, 4), (1, 4, 5), (2, 3, 4), (2, 4, 5), and (3, 4, 5).

Sample Input 2

6
4 5 4 3 3 5

Sample Output 2

8

We have two sticks for each of the lengths 3, 4, and 5. To satisfy the first condition, we have to choose one from each length.

There is a triangle whose sides have lengths 3, 4, and 5, so we have 2 ^ 3 = 8 triples (i, j, k) that satisfy the conditions.

Sample Input 3

10
9 4 6 1 9 6 10 6 6 8

Sample Output 3

39

Sample Input 4

2
1 1

Sample Output 4

0

No triple (i, j, k) satisfies 1 \leq i < j < k \leq N, so we should print 0.


"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(), k = next();
  var p = nexts(n).map(a=>a-1);
  var c = nexts(n);
  var ans = -2e18, a = Array(n);
  for(var i = 0; i < n; i++){
    var cnt = 1;
    a = a.fill(0);
    var id = p[i];
    a[0] = c[id];
    while(cnt < k && id !== i){
      id = p[id];
      a[cnt] = a[cnt-1] + c[id];
      cnt++;
    }
    cnt;
    if(a[cnt-1] > 0)for(var j = 0; j < cnt; j++){
      var t = BigInt(a[j]) + BigInt(Math.floor((k-j-1)/cnt)) * BigInt(a[cnt-1]);
      if(ans < t)ans = t;
    }else for(var j = 0; j < cnt; j++){
      var t = a[j];
      if(ans < t)ans = t;
    }
  }
  return ans;
}

Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.


function main(input) {
  let args = input.split('\n');
  args.pop();
  let count = 0;
  for (let i = 0;i < args.length;i++) {
    for (let j = i + 1;j < args.length;j++) {
      let result = (args[i] * 10000000000) * (args[j] * 10000000000);
      if (result % (10000000000 * 10000000000) == 0 && args[i] !== args[j]) {
    	count++;
      }
    }
  }
  console.log(count);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 300 points

Problem Statement

You are given N real values A_1, A_2, \ldots, A_N.
Compute the number of pairs of indices (i, j)
such that i < j and the product A_i \cdot A_j is integer.

Constraints

2 \leq N \leq 200\,000

0 < A_i < 10^4

A_i is given with at most 9 digits after the decimal.

Input

Input is given from Standard Input in the following format.

N
A_1
A_2
\vdots
A_N

Output

Print the number of pairs with integer product A_i \cdot A_j (and i < j).

Sample Input 1

5
7.5
2.4
17.000000001
17
16.000000000

Sample Output 1

3

There are 3 pairs with integer product:

7.5 \cdot 2.4 = 18

7.5 \cdot 16 = 120

17 \cdot 16 = 272

Sample Input 2

11
0.9
1
1
1.25
2.30000
5
70
0.000000001
9999.999999999
0.999999999
1.000000001

Sample Output 2

8


function Main(input) {
  let [l, ...valArr] = input.split('\n')
  valArr = valArr.map(e=>parseFloat(e)).sort(function(a,b) { return a - b})
  let result = []
  let counter = 0
  for(let ele of valArr){
    let opArr = valArr.slice(++counter, valArr.length)
    let temp = opArr.filter(e=> (e*ele)%1===0)
    if(temp.length){result = [...result, ...temp]}
  }
  console.log(result.length)
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function MainA(input){
    console.log(Number(input.trim()) >=30 ? 'Yes' : 'No');
}
MainA(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.

The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?

Constraints

-40 \leq X \leq 40

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print Yes if you will turn on the air conditioner; print No otherwise.

Sample Input 1

25

Sample Output 1

No

Sample Input 2

30

Sample Output 2

Yes


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

  // 1行目がinput[0], 2行目がinput[1], …に入る
  // var input1 = input.split("\n");
  // var input1 = input.split(" ");
  // var n = Number(input1[0].split(' ')[0])
  // var k = Number(input1[0].split(' ')[1])
  // var nums = input1[1].split(' ').map(function (v) { return Number(v) })

  let n = Number(input)

  // console.log(input1
  //   , n
  //   , k
  //   , nums)

  // var results = 0
  // var arrayNum = 0

  // for (var i = nums.length; i > 0; i--) {
  //   arrayNum += i
  // }

  // const retArr2 = new Array(arrayNum).fill(0).map(function (v, idx) {
  //   var getNum = 1

  //   var idx2 = idx
  //   // console.log('bg', idx, getNum)
  //   while ((idx2 - (nums.length - getNum + 1)) >= 0) {

  //     getNum++
  //     // console.log(idx2)
  //     idx2 = idx2 - (nums.length - getNum + 1)
  //     // console.log(idx2, nums.length, getNum, (nums.length - getNum + 2))
  //   }
  //   console.log('ed', idx2, getNum)

  //   const retArr = new Array(getNum).fill(null).map(function (v99, idx3) {
  //     return nums[idx2 + idx3]
  //   })

  //   if (getNum > 3) {
  //     throw new Error()
  //   }

  //   return {
  //     getNum: getNum,
  //     sum: retArr//.reduce(function (prev, curr) { return prev + curr }, 0)
  //   }
  // })

  // console.log(retArr2)

  // while (getNum < nums.length) {

  //   for (var n1 = 0; n1 < nums.length - getNum + 1; n1++) {
  //     var n = nums.length - getNum + 1
  //     var sumNums = new Array(n).fill(0)

  //     sumNums = sumNums.map(function (v, idx) {
  //       return new Array(getNum).fill(0).map(function (v2, idx2) {
  //         return nums[n1 + idx2]
  //       }).reduce(function (prev, curr) { return prev + curr }, 0)
  //     })

  //     console.log("sumNums1", sumNums)

  //     sumNums = sumNums.map(function (v3) {
  //       if ((v3 % k) === getNum) {
  //         return 1
  //       } else {
  //         return 0
  //       }
  //     }).reduce(function (prev, curr) { return prev + curr }, 0)
  //     console.log("sumNums2", sumNums)

  //     console.log("sumNums", sumNums, results)
  //     results += sumNums
  //   }

  //   getNum++
  //   console.log("getNum", getNum, nums.length, results)
  // }

  // //文字列から10進数に変換するときはparseIntを使います
  // // var a = parseInt(i[0], 10);
  // // var b = parseInt(i[1], 10);
  // // var c = parseInt(i[2], 10);
  // var i1 = i.map(v => parseInt(v, 10))

  if (n >= 30) {
    console.log("Yes");
  } else {
    console.log("No");
  }

  //出力
  // console.log(results, results);
}

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


function MainD(input){
    const arr = input.split('\n');
    const N = arr[0];
    const Ci = arr[1].split('');
    let answer = 0;

    // Wの数を数える
    let Wnum = 0;
    for(let i=0; i<Ci.length; i++){
        if(Ci[i] === 'W'){
            Wnum++;
        }
    }
    if(Wnum===0) return console.log(0); // Wが現れなかったら0を出力

    // Wの数以降のRの数を数える
    for(let i=Wnum-1; i<Ci.length; i++){
        if(Ci[i] === 'R'){
            answer++;
        }
    }
    console.log(answer);
}
MainD(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 400 points

Problem Statement

An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; R stands for red and W stands for white.

You can do the following two kinds of operations any number of times in any order:

Choose two stones (not necessarily adjacent) and swap them.

Choose one stone and change its color (from red to white and vice versa).

According to a fortune-teller, a white stone placed to the immediate left of a red stone will bring a disaster. At least how many operations are needed to reach a situation without such a white stone?

Constraints

2 \leq N \leq 200000

c_i is R or W.

Input

Input is given from Standard Input in the following format:

N
c_{1}c_{2}...c_{N}

Output

Print an integer representing the minimum number of operations needed.

Sample Input 1

4
WWRR

Sample Output 1

2

For example, the two operations below will achieve the objective.

Swap the 1-st and 3-rd stones from the left, resulting in RWWR.

Change the color of the 4-th stone from the left, resulting in RWWW.

Sample Input 2

2
RR

Sample Output 2

0

It can be the case that no operation is needed.

Sample Input 3

8
WRWWRWRR

Sample Output 3

3


console.log((args=>{
  const [n,c] = args.trim().split`\n`;
  const N = n|0;
  let j = N, count = 0;
  for ( let i = 0; i < j; i++ ) {
    if ( c[i] === 'R' ) continue;
    for (;j > i;) {
      if ( c[j--] === 'R' ) {
        count++;
        break;
      }
    }
  }
  return count;
})(require('fs').readFileSync('/dev/stdin', 'utf8')));


//let input = "7 4 2\n3";

function main(input){
  input = input.trim();
  let l1 = input.split("\n")[0];
  let l2 = input.split("\n")[1];
  let r = parseInt(l1.split(" ")[0]);
  let g = parseInt(l1.split(" ")[1]);
  let b = parseInt(l1.split(" ")[2]);
  let n = parseInt(l2);

  function hantei(){
    return(r<g && g<b);
  }

  function magic(){
    if(r>g){
      g = g*2;
    }else if(g>b){
      b = b*2
    }
  }

  for(i=0; i<n; i++){
    magic();
  }
  let answer = "";
  if(hantei()===true){
    answer = "Yes";
  }else{
    answer = "No";
  }
  console.log(answer);
}

//main(input);

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

Score: 200 points

Problem Statement

M-kun has the following three cards:

A red card with the integer A.

A green card with the integer B.

A blue card with the integer C.

He is a genius magician who can do the following operation at most K times:

Choose one of the three cards and multiply the written integer by 2.

His magic is successful if both of the following conditions are satisfied after the operations:

The integer on the green card is strictly greater than the integer on the red card.

The integer on the blue card is strictly greater than the integer on the green card.

Determine whether the magic can be successful.

Constraints

1 \leq A, B, C \leq 7

1 \leq K \leq 7

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C
K

Output

If the magic can be successful, print Yes; otherwise, print No.

Sample Input 1

7 2 5
3

Sample Output 1

Yes

The magic will be successful if, for example, he does the following operations:

First, choose the blue card. The integers on the red, green, and blue cards are now 7, 2, and 10, respectively.

Second, choose the green card. The integers on the red, green, and blue cards are now 7, 4, and 10, respectively.

Third, choose the green card. The integers on the red, green, and blue cards are now 7, 8, and 10, respectively.

Sample Input 2

7 4 2
3

Sample Output 2

No

He has no way to succeed in the magic with at most three operations.


"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 = () => {
    let [n, k] = nextIntArray()
    let a = next().split(" ").map(el => BigInt(el))
    let tmp = 1n
    for (let i = 0; i < k ; i++) {
        tmp = tmp * a[i]
    }
    let prev
    let ans = ""
    for (let i = k; i < n; i++) {
        prev = tmp
        tmp = tmp / a[i - k]
        tmp = tmp * a[i]
        if (tmp > prev) {
            ans += "Yes\n"
        } else {
            ans += "No\n"
        }
    }
    console.log(ans)
}
Main()

Score: 300 points

Problem Statement

M-kun is a student in Aoki High School, where a year is divided into N terms.

There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows:

For the first through (K-1)-th terms: not given.

For each of the K-th through N-th terms: the multiplication of the scores in the last K exams, including the exam in the graded term.

M-kun scored A_i in the exam at the end of the i-th term.

For each i such that K+1 \leq i \leq N, determine whether his grade for the i-th term is strictly greater than the grade for the (i-1)-th term.

Constraints

2 \leq N \leq 200000

1 \leq K \leq N-1

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 K
A_1 A_2 A_3 \ldots A_N

Output

Print the answer in N-K lines.

The i-th line should contain Yes if the grade for the (K+i)-th term is greater than the grade for the (K+i-1)-th term, and No otherwise.

Sample Input 1

5 3
96 98 95 100 20

Sample Output 1

Yes
No

His grade for each term is computed as follows:

3-rd term: (96 \times 98 \times 95) = 893760

4-th term: (98 \times 95 \times 100) = 931000

5-th term: (95 \times 100 \times 20) = 190000

Sample Input 2

3 2
1001 869120 1001

Sample Output 2

No

Note that the output should be No if the grade for the 3-rd term is equal to the grade for the 2-nd term.

Sample Input 3

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

Sample Output 3

Yes
Yes
No
Yes
Yes
No
Yes
Yes


Score: 400 points

Problem Statement

To become a millionaire, M-kun has decided to make money by trading in the next N days. Currently, he has 1000 yen and no stocks - only one kind of stock is issued in the country where he lives.

He is famous across the country for his ability to foresee the future. He already knows that the price of one stock in the next N days will be as follows:

A_1 yen on the 1-st day, A_2 yen on the 2-nd day, ..., A_N yen on the N-th day.

In the i-th day, M-kun can make the following trade any number of times (possibly zero), within the amount of money and stocks that he has at the time.

Buy stock: Pay A_i yen and receive one stock.

Sell stock: Sell one stock for A_i yen.

What is the maximum possible amount of money that M-kun can have in the end by trading optimally?

Constraints

2 \leq N \leq 80

100 \leq A_i \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N

Output

Print the maximum possible amount of money that M-kun can have in the end, as an integer.

Sample Input 1

7
100 130 130 130 115 115 150

Sample Output 1

1685

In this sample input, M-kun has seven days of trading. One way to have 1685 yen in the end is as follows:

Initially, he has 1000 yen and no stocks.

Day 1: Buy 10 stocks for 1000 yen. Now he has 0 yen.

Day 2: Sell 7 stocks for 910 yen. Now he has 910 yen.

Day 3: Sell 3 stocks for 390 yen. Now he has 1300 yen.

Day 4: Do nothing.

Day 5: Buy 1 stock for 115 yen. Now he has 1185 yen.

Day 6: Buy 10 stocks for 1150 yen. Now he has 35 yen.

Day 7: Sell 11 stocks for 1650 yen. Now he has 1685 yen.

There is no way to have 1686 yen or more in the end, so the answer is 1685.

Sample Input 2

6
200 180 160 140 120 100

Sample Output 2

1000

In this sample input, it is optimal to do nothing throughout the six days, after which we will have 1000 yen.

Sample Input 3

2
157 193

Sample Output 3

1216

In this sample input, it is optimal to buy 6 stocks in Day 1 and sell them in Day 2, after which we will have 1216 yen.


/*! path: /home/ts3min/work/tspro/src/contest/atcoder/msol2020/e.ts */
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = "./src/contest/atcoder/msol2020/e.ts");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./node_modules/webpack/buildin/module.js":
/*!***********************************!*\
  !*** (webpack)/buildin/module.js ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = function(module) {
	if (!module.webpackPolyfill) {
		module.deprecate = function() {};
		module.paths = [];
		// module.parent = undefined by default
		if (!module.children) module.children = [];
		Object.defineProperty(module, "loaded", {
			enumerable: true,
			get: function() {
				return module.l;
			}
		});
		Object.defineProperty(module, "id", {
			enumerable: true,
			get: function() {
				return module.i;
			}
		});
		module.webpackPolyfill = 1;
	}
	return module;
};

/***/ }),

/***/ "./src/contest/atcoder/msol2020/e.ts":
/*!*******************************************!*\
  !*** ./src/contest/atcoder/msol2020/e.ts ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(module) {
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.main = void 0;
const fs_1 = __importDefault(__webpack_require__(/*! fs */ "fs"));
const io_1 = __webpack_require__(/*! ../../common/io */ "./src/contest/common/io.ts");
const INF = 1 << 30;
var Axis;
(function (Axis) {
    Axis["X"] = "X";
    Axis["Y"] = "Y";
    Axis["N"] = "N";
})(Axis || (Axis = {}));
function calc({ N, C, cand }) {
    let finalCost = 0;
    for (let i = 0; i < N; i++) {
        if (cand[i] != Axis.N) {
            continue;
        }
        let cost = Math.min(Math.abs(C[i].x), Math.abs(C[i].y)) * C[i].p;
        for (let j = 0; j < N; j++) {
            if (cand[j] == Axis.Y) {
                cost = Math.min(cost, Math.abs(C[i].x - C[j].x) * C[i].p);
            }
            else if (cand[j] == Axis.X) {
                cost = Math.min(cost, Math.abs(C[i].y - C[j].y) * C[i].p);
            }
        }
        finalCost += cost;
    }
    return finalCost;
}
function rec(i, k, sys) {
    const { cand, N, C, ans } = sys;
    if (i === N) {
        const res = calc({ N, C, cand });
        ans[k] = Math.min(ans[k], res);
        return;
    }
    cand[i] = Axis.N;
    rec(i + 1, k, sys);
    cand[i] = Axis.X;
    rec(i + 1, k + 1, sys);
    cand[i] = Axis.Y;
    rec(i + 1, k + 1, sys);
}
function solve({ N, C }) {
    const ans = Array(N + 1).fill(INF);
    const cand = Array(N);
    const sys = {
        N, C, ans, cand,
    };
    rec(0, 0, sys);
    return ans;
}
function main(line) {
    const nextInt = io_1.getNextInt(line);
    const N = nextInt();
    const C = [];
    for (let i = 0; i < N; i++) {
        const x = nextInt();
        const y = nextInt();
        const p = nextInt();
        C.push({ x, y, p });
    }
    console.log(solve({ N, C }).join('\n'));
}
exports.main = main;
if (__webpack_require__.c[__webpack_require__.s] === module) {
    const line = fs_1.default.readFileSync("/dev/stdin", "utf8");
    main(line);
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../node_modules/webpack/buildin/module.js */ "./node_modules/webpack/buildin/module.js")(module)))

/***/ }),

/***/ "./src/contest/common/io.ts":
/*!**********************************!*\
  !*** ./src/contest/common/io.ts ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.getNextBigInt = exports.getNextInt = exports.getNext = exports.getIteratorWithParser = exports.getIterator = void 0;
function* getIterator(line) {
    const tokens = line.split(/\s+/);
    for (const token of tokens) {
        yield token;
    }
}
exports.getIterator = getIterator;
function* getIteratorWithParser(line, parser) {
    const tokens = line.split(/\s+/);
    for (const token of tokens) {
        yield parser(token);
    }
}
exports.getIteratorWithParser = getIteratorWithParser;
function getNext(line) {
    const it = getIterator(line);
    return () => it.next().value;
}
exports.getNext = getNext;
function getNextInt(line) {
    const it = getIterator(line);
    return () => parseInt(it.next().value);
}
exports.getNextInt = getNextInt;
function getNextBigInt(line) {
    const it = getIterator(line);
    return () => BigInt(it.next().value);
}
exports.getNextBigInt = getNextBigInt;

/***/ }),

/***/ "fs":
/*!*********************!*\
  !*** external "fs" ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("fs");

/***/ })

/******/ });
//# sourceMappingURL=submit.js.map

Score: 500 points

Problem Statement

New AtCoder City has an infinite grid of streets, as follows:

At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.

A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.

A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.

There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.

The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.

M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.

Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.

M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.

For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?

Constraints

1 \leq N \leq 15

-10 \ 000 \leq X_i \leq 10 \ 000

-10 \ 000 \leq Y_i \leq 10 \ 000

1 \leq P_i \leq 1 \ 000 \ 000

The locations of the N residential areas, (X_i, Y_i), are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N

Output

Print the answer in N+1 lines.

The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.

Sample Input 1

3
1 2 300
3 3 600
1 4 800

Sample Output 1

2900
900
0
0

When K = 0, the residents of Area 1, 2, and 3 have to walk the distances of 1, 3, and 1, respectively, to reach a railroad.

Thus, the sum of the walking distances of all citizens, S, is 1 \times 300 + 3 \times 600 + 1 \times 800 = 2900.

When K = 1, if we build a railroad along the street corresponding to the line y = 4 in the coordinate plane, the walking distances of the citizens of Area 1, 2, and 3 become 1, 1, and 0, respectively.

Then, S = 1 \times 300 + 1 \times 600 + 0 \times 800 = 900.

We have many other options for where we build the railroad, but none of them makes S less than 900.

When K = 2, if we build a railroad along the street corresponding to the lines x = 1 and x = 3 in the coordinate plane, all citizens can reach a railroad with the walking distance of 0, so S = 0. We can also have S = 0 when K = 3.

The figure below shows the optimal way to build railroads for the cases K = 0, 1, 2.

The street painted blue represents the roads along which we build railroads.

Sample Input 2

5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400

Sample Output 2

13800
1600
0
0
0
0

The figure below shows the optimal way to build railroads for the cases K = 1, 2.

Sample Input 3

6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200

Sample Output 3

26700
13900
3200
1200
0
0
0

The figure below shows the optimal way to build railroads for the case K = 3.

Sample Input 4

8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903

Sample Output 4

2576709
1569381
868031
605676
366338
141903
0
0
0

The figure below shows the optimal way to build railroads for the case K = 4.


(async () => {
  process.stdin.setEncoding('utf8');
  let text = '';
  for await (const chunk of process.stdin) text += chunk;

  const lines = text.toString().split('\n');
  const tmpArray = lines[1].split(' ');
  const count = lines[0];
  let result = 0;

  for (let i = 0; i < tmpArray.length; i++) {
    if (i % 2 === 0) {
      if (tmpArray[i] % 2 === 1) {
        result ++;
      }
    }
  }

  console.log(result);
})();

Score : 100 points

Problem Statement

How many multiples of d are there among the integers between L and R (inclusive)?

Constraints

All values in input are integers.

1 \leq L \leq R \leq 100

1 \leq d \leq 100

Input

Input is given from Standard Input in the following format:

L R d

Output

Print the number of multiples of d among the integers between L and R (inclusive).

Sample Input 1

5 10 2

Sample Output 1

3

Among the integers between 5 and 10, there are three multiples of 2: 6, 8, and 10.

Sample Input 2

6 20 7

Sample Output 2

2

Among the integers between 6 and 20, there are two multiples of 7: 7 and 14.

Sample Input 3

1 100 1

Sample Output 3

100


function Main(input){
    const num = input.split('\n')[1].split(' ').map(Number);
    let odd_count = 0;
    // 奇数のマスのみチェック
    for(let n=0; n <num.length; n+=2){
       if(num[n] % 2 == 1)
           odd_count++;
    }
    // countの数を出力
    console.log(odd_count);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 200 points

Problem Statement

We have N squares assigned the numbers 1,2,3,\ldots,N. Each square has an integer written on it, and the integer written on Square i is a_i.

How many squares i satisfy both of the following conditions?

The assigned number, i, is odd.

The written integer is odd.

Constraints

All values in input are integers.

1 \leq N, a_i \leq 100

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \cdots a_N

Output

Print the number of squares that satisfy both of the conditions.

Sample Input 1

5
1 3 4 5 7

Sample Output 1

2

Two squares, Square 1 and 5, satisfy both of the conditions.

For Square 2 and 4, the assigned numbers are not odd.

For Square 3, the written integer is not odd.

Sample Input 2

15
13 76 46 15 50 98 93 77 31 43 84 90 6 24 14

Sample Output 2

3


function Main(input) {
	const n = input.split("\n")[0]
	const ar = input.split("\n")[1].split(" ")
	ar2 = ar.filter((num, i)=> {
        return num % 2 === 0 ? false : i % 2 === 0 ? false : true;
    })
    console.log(ar2.length);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


var GET = (function () {function f(s) {return new g(s);}function g(s) {this._s = s.trim().split("\n");}g.prototype.getValue = function (n) {return this._s[n];};g.prototype.getArray = function (n) {return this.stoa(this._s[n]);};g.prototype.slice = function (s, limit) {return this._s.slice(s, +limit + s || undefined).map(v => this.stox(v));};g.prototype.sliceArray = function (s, limit) {return this._s.slice(s, +limit + s || undefined).map(v => this.stoa(v));};g.prototype.stoa = function (s) {return s.split(" ").map(v => this.stox(v));};g.prototype.stox = function (v) {var i = +v;return (i === i) ? i : v;};return f;})();
var o = GET(require("fs").readFileSync("/dev/stdin", "utf8"));

console.log(main());
function main(){
    var N = +o.getValue(0);

    var result = Array(1000).fill(0);
    for(var x = 1; 100 > x; x++) {
        for(var y = 1; 100 > y; y++) {
            for(var z = 1; 100 > z; z++) {
                var n = x**2 + y**2 + z**2 + x*y + x*z + y*z;
                if (n > 1000) break;
                result[n - 1] += 1;
            }
        }
    }

    return result.slice(0, N).join('\n');
}

Score : 300 points

Problem Statement

Let f(n) be the number of triples of integers (x,y,z) that satisfy both of the following conditions:

1 \leq x,y,z

x^2 + y^2 + z^2 + xy + yz + zx = n

Given an integer N, find each of f(1),f(2),f(3),\ldots,f(N).

Constraints

All values in input are integers.

1 \leq N \leq 10^4

Input

Input is given from Standard Input in the following format:

N

Output

Print N lines. The i-th line should contain the value f(i).

Sample Input 1

20

Sample Output 1

0
0
0
0
0
1
0
0
0
0
3
0
0
0
0
0
3
3
0
0

For n=6, only (1,1,1) satisfies both of the conditions. Thus, f(6) = 1.

For n=11, three triples, (1,1,2), (1,2,1), and (2,1,1), satisfy both of the conditions. Thus, f(6) = 3.

For n=17, three triples, (1,2,2), (2,1,2), and (2,2,1), satisfy both of the conditions. Thus, f(17) = 3.

For n=18, three triples, (1,1,3), (1,3,1), and (3,1,1), satisfy both of the conditions. Thus, f(18) = 3.


/*
-------関数一覧--------
arr1dto2d(Array) 一次元配列を二次元配列にします
pf(N)素因数分解した結果をオブジェクトで返します
gcd(a,b)最大公約数を返します
lcm(a,b)最小公倍数を返します
num(a,b)a-bを返します。ソート用です
isPrime(n)素数かどうか真偽値で返します
isNumber(n)数かどうか真偽値で返します
arrsum(arr)配列の合計値を返します
nibu(arr,n)n以下で最も大きい数の添字を返します(nを含みます)
br(input)入力を改行で区切ります
*/
const debugMode = false;
const inf = Number.MAX_SAFE_INTEGER;
const mod = 1000000007;
function Main(input){
  var arr = new Array(10010).fill(0);
  for(var i=1;i<=120;i++){
    for(var j=1;j<=120;j++){
      for(var k=1;k<=120;k++){
        var n = i*i+j*j+k*k+i*j+j*k+k*i
        if(n<10010){
          arr[n]++;
        }
      }
    }
  }
  for(var i=1;i<input-0+1;i++){
    console.log(arr[i])
    }
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
function pow(a,b){
    var ans = 0;
    for(var i=0n;i<b;i+=1n){
        if(ans == 0){
            ans = a;
        }else{
            ans *= a;
        }
    }
    return a;
}
function zisyozyunn(a){
  var arr = [];
  for(var i=0;i<input[0];i++){
    arr.push(i+1);
  }
  var sum = 0;
  for(var i=0;i<a.length;i++){
    var f = arr.findIndex(val => val==a[i]);
    sum += factorialize(a.length-1-i)*f;
    arr.splice(f,1);
  }
  return sum;
}
function arrsum(arr){
  var sum = 0;
  for (var i=0,len=arr.length; i<len; ++i) {
      sum += arr[i]-0;
  };
  return sum;
}
function debug(val){
  if(debugMode==true){
    console.log(val)
  }
}
function arrMaxPoint(arr){
	var max = Number.MIN_SAFE_INTEGER;
	var point = -1;
	for(var i=0;i<arr.length;i++){
		if(max<arr[i]){
			max = arr[i];
			point = i;
		}
	}
	return point;
}
function arrMinPoint(arr){
	var min = Number.MAX_SAFE_INTEGER;
	var point = -1;
	for(var i=0;i<arr.length;i++){
		if(min>arr[i]){
			min = arr[i];
			point = i;
		}
	}
	return point;
}
function isPrime(n){
    if(false===Number.isInteger(n)){
        return false;
    }
    if(n<=1){
        return false;
    }
    if(2===n){
        return true;
    }
    if(0===n%2){
        return false;
    }
    var square_root = Math.floor(Math.sqrt(n));
    for(var i=3; i<=square_root; i+=2){
        if(0===n%i){
            return false;
        }
    }
    return true;
}
function isNumber(val){
	const pat = /^([1-9]\d*|0)$/;
	return pat.test(val);
}
function factorialize(num) {
  if (num === 0) { return 1; }
  return num * factorialize(num-1);
}
function arr1dto2d (arr){
	for(var i=0;i<arr.length;i++){
    arr[i]=arr[i].split(" ").map(Number);
    }
  return arr;
}
function rotate(array) {
  const ROW = array.length;
  const COL = array[0].length;
  const row = ROW-1;
  var a = new Array(COL);
  for (var c=0; c<COL; c++) {
    a[c] = new Array(ROW);
    for (var r=0; r<ROW; r++) {
      a[c][r] = array[row-r][c];
    }
  }
  return a;
}
function part_in(base,push,st){
	for(var i=st,p=0;p<push.length;i++,p++){
		base[i] = push[p];
	}
	return base;
}
function part_reverse(arr,s,g){
	var push = arr.slice(s-1,g);
  push.reverse();
	arr = part_in(arr,push,s-1);
	return arr;
}
function zeroPadding(num,length){
    return (num + '000000000000000000000000000000000').slice(0,length);
}
function arrsum(arr){
    var sum = 0;
    for (var i=0,len=arr.length; i<len; ++i) {
        sum += arr[i]-0;
    };
    return sum;
}
function pf(n) {
    var result = {};

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

    var init = 2;

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

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

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

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

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

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

	// 平方根を保存
	var s = Math.floor(Math.sqrt(n));

	var r = 0;

	var result = {};

	// 2から平方根までの素因数を求める
	for (var i = 2;i <= s;i++) {

		if ((n % i) == 0) {

			r = 0; // 指数カウンタクリア

			do {

				r++; // 指数カウンタプラス

				n = n / i;

			} while ((n % i) == 0);

			// 素因数iを指数とともに保存
			result[i]=r;

		}

	}

	// 残った素数を追加
	if (n > s) {
		result[n] = 1;
	}

	return result;

}


const main = (input) => {
  const [n, ...rows] = input.trim().split('\n')
  const k = ['AC', 'WA', 'TLE', 'RE']
  const ans = {}
  for (let v of k) ans[v] = 0

  for (let r of rows) ans[r] += 1

  for (let v of k) console.log(`${v} x ${ans[v]}`)
}

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

Score : 200 points

Problem Statement

Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.

The problem has N test cases.

For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively.

See the Output section for the output format.

Constraints

1 \leq N \leq 10^5

S_i is AC, WA, TLE, or RE.

Input

Input is given from Standard Input in the following format:

N
S_1
\vdots
S_N

Output

Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively. Print the following:

AC x C_0
WA x C_1
TLE x C_2
RE x C_3

Sample Input 1

6
AC
TLE
AC
AC
WA
TLE

Sample Output 1

AC x 3
WA x 1
TLE x 2
RE x 0

We have 3, 1, 2, and 0 test case(s) for which the verdict is AC, WA, TLE, and RE, respectively.

Sample Input 2

10
AC
AC
AC
AC
AC
AC
AC
AC
AC
AC

Sample Output 2

AC x 10
WA x 0
TLE x 0
RE x 0


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  var A = input[1].split(" ").map(i => parseInt(i));
  A.sort((a,b) => b-a);
  var ans =0;
  var P = new Array(1).fill(A[0]);
  for(var i = 1;i<N;i++){
    ans += P[P.length-1];
    P.pop();
    P.push(A[i]);
    P.push(A[i]);
    P.sort((a,b)=>a-b);
  }

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

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

Score: 400 points

Problem Statement

Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.

The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.

When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.

What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?

Constraints

All values in input are integers.

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

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the maximum total comfort the N players can get.

Sample Input 1

4
2 2 1 3

Sample Output 1

7

By arriving at the place in the order Player 4, 2, 1, 3, and cutting into the circle as shown in the figure, they can get the total comfort of 7.

They cannot get the total comfort greater than 7, so the answer is 7.

Sample Input 2

7
1 1 1 1 1 1 1

Sample Output 2

6


const insert = (circle, person) => {
  let max = 0
  let index = 0

  circle.forEach((v, i) => {
    const prev = i - 1 === -1 ? circle.length - 1 : i - 1
    const comfortableness = Math.min(circle[prev], circle[i])

    if (comfortableness > max ) {
      max = comfortableness
      index = i
    }
  })

  circle.splice(index, 0, person)

  return max
}

const main = async () => {
  const input = require('fs').readFileSync('/dev/stdin', 'UTF-8').trim()
  const [hString, aStrings] = input.split('\n')
  const h = Number(hString)
  const as = aStrings.split(' ').map(Number)

  as.sort((a, b) => b - a)
  const circle = []

  const comfortableness = as.reduce((a, person) => a + insert(circle, person), 0)

  console.log(comfortableness)
}

main()


/**
 * FastPriorityQueue.js : a fast heap-based priority queue  in JavaScript.
 * (c) the authors
 * Licensed under the Apache License, Version 2.0.
 *
 * Speed-optimized heap-based priority queue for modern browsers and JavaScript engines.
 *
 * Usage :
         Installation (in shell, if you use node):
         $ npm install fastpriorityqueue
         Running test program (in JavaScript):
         // var FastPriorityQueue = require("fastpriorityqueue");// in node
         var x = new FastPriorityQueue();
         x.add(1);
         x.add(0);
         x.add(5);
         x.add(4);
         x.add(3);
         x.peek(); // should return 0, leaves x unchanged
         x.size; // should return 5, leaves x unchanged
         while(!x.isEmpty()) {
           console.log(x.poll());
         } // will print 0 1 3 4 5
         x.trim(); // (optional) optimizes memory usage
 */
'use strict';

var defaultcomparator = function(a, b) {
  return a < b;
};

// the provided comparator function should take a, b and return *true* when a < b
function FastPriorityQueue(comparator) {
  if (!(this instanceof FastPriorityQueue)) return new FastPriorityQueue(comparator);
  this.array = [];
  this.size = 0;
  this.compare = comparator || defaultcomparator;
}

// copy the priority queue into another, and return it. Queue items are shallow-copied.
// Runs in `O(n)` time.
FastPriorityQueue.prototype.clone = function() {
  var fpq = new FastPriorityQueue(this.compare);
  fpq.size = this.size;
  for (var i = 0; i < this.size; i++) {
    fpq.array.push(this.array[i]);
  }
  return fpq;
};

// Add an element into the queue
// runs in O(log n) time
FastPriorityQueue.prototype.add = function(myval) {
  var i = this.size;
  this.array[this.size] = myval;
  this.size += 1;
  var p;
  var ap;
  while (i > 0) {
    p = (i - 1) >> 1;
    ap = this.array[p];
    if (!this.compare(myval, ap)) {
      break;
    }
    this.array[i] = ap;
    i = p;
  }
  this.array[i] = myval;
};

// replace the content of the heap by provided array and "heapify it"
FastPriorityQueue.prototype.heapify = function(arr) {
  this.array = arr;
  this.size = arr.length;
  var i;
  for (i = this.size >> 1; i >= 0; i--) {
    this._percolateDown(i);
  }
};

// for internal use
FastPriorityQueue.prototype._percolateUp = function(i, force) {
  var myval = this.array[i];
  var p;
  var ap;
  while (i > 0) {
    p = (i - 1) >> 1;
    ap = this.array[p];
    // force will skip the compare
    if (!force && !this.compare(myval, ap)) {
      break;
    }
    this.array[i] = ap;
    i = p;
  }
  this.array[i] = myval;
};

// for internal use
FastPriorityQueue.prototype._percolateDown = function(i) {
  var size = this.size;
  var hsize = this.size >>> 1;
  var ai = this.array[i];
  var l;
  var r;
  var bestc;
  while (i < hsize) {
    l = (i << 1) + 1;
    r = l + 1;
    bestc = this.array[l];
    if (r < size) {
      if (this.compare(this.array[r], bestc)) {
        l = r;
        bestc = this.array[r];
      }
    }
    if (!this.compare(bestc, ai)) {
      break;
    }
    this.array[i] = bestc;
    i = l;
  }
  this.array[i] = ai;
};

// internal
// _removeAt(index) will remove the item at the given index from the queue,
// retaining balance. returns the removed item, or undefined if nothing is removed.
FastPriorityQueue.prototype._removeAt = function(index) {
  if (index > this.size - 1 || index < 0) return undefined;

  // impl1:
  //this.array.splice(index, 1);
  //this.heapify(this.array);
  // impl2:
  this._percolateUp(index, true);
  return this.poll();
};

// remove(myval) will remove an item matching the provided value from the
// queue, checked for equality by using the queue's comparator.
// return true if removed, false otherwise.
FastPriorityQueue.prototype.remove = function(myval) {
  for (var i = 0; i < this.size; i++) {
    if (!this.compare(this.array[i], myval) && !this.compare(myval, this.array[i])) {
      // items match, comparator returns false both ways, remove item
      this._removeAt(i);
      return true;
    }
  }
  return false;
};

// internal
// removes and returns items for which the callback returns true.
FastPriorityQueue.prototype._batchRemove = function(callback, limit) {
  // initialize return array with max size of the limit or current queue size
  var retArr = new Array(limit ? limit : this.size);
  var count = 0;

  if (typeof callback === 'function' && this.size) {
    var i = 0;
    while (i < this.size && count < retArr.length) {
      if (callback(this.array[i])) {
        retArr[count] = this._removeAt(i);
        count++;
        // move up a level in the heap if we remove an item
        i = i >> 1;
      } else {
        i++;
      }
    }
  }
  retArr.length = count;
  return retArr;
}

// removeOne(callback) will execute the callback function for each item of the queue
// and will remove the first item for which the callback will return true.
// return the removed item, or undefined if nothing is removed.
FastPriorityQueue.prototype.removeOne = function(callback) {
  var arr = this._batchRemove(callback, 1);
  return arr.length > 0 ? arr[0] : undefined;
};

// remove(callback[, limit]) will execute the callback function for each item of
// the queue and will remove each item for which the callback returns true, up to
// a max limit of removed items if specified or no limit if unspecified.
// return an array containing the removed items.
FastPriorityQueue.prototype.removeMany = function(callback, limit) {
  return this._batchRemove(callback, limit);
};

// Look at the top of the queue (one of the smallest elements) without removing it
// executes in constant time
//
// Calling peek on an empty priority queue returns
// the "undefined" value.
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/undefined
//
FastPriorityQueue.prototype.peek = function() {
  if (this.size == 0) return undefined;
  return this.array[0];
};

// remove the element on top of the heap (one of the smallest elements)
// runs in logarithmic time
//
// If the priority queue is empty, the function returns the
// "undefined" value.
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/undefined
//
// For long-running and large priority queues, or priority queues
// storing large objects, you may  want to call the trim function
// at strategic times to recover allocated memory.
FastPriorityQueue.prototype.poll = function() {
  if (this.size == 0) return undefined;
  var ans = this.array[0];
  if (this.size > 1) {
    this.array[0] = this.array[--this.size];
    this._percolateDown(0);
  } else {
    this.size -= 1;
  }
  return ans;
};

// This function adds the provided value to the heap, while removing
// and returning one of the smallest elements (like poll). The size of the queue
// thus remains unchanged.
FastPriorityQueue.prototype.replaceTop = function(myval) {
  if (this.size == 0) return undefined;
  var ans = this.array[0];
  this.array[0] = myval;
  this._percolateDown(0);
  return ans;
};

// recover unused memory (for long-running priority queues)
FastPriorityQueue.prototype.trim = function() {
  this.array = this.array.slice(0, this.size);
};

// Check whether the heap is empty
FastPriorityQueue.prototype.isEmpty = function() {
  return this.size === 0;
};

// iterate over the items in order, pass a callback that receives (item, index) as args.
// TODO once we transpile, uncomment
// if (Symbol && Symbol.iterator) {
//   FastPriorityQueue.prototype[Symbol.iterator] = function*() {
//     if (this.isEmpty()) return;
//     var fpq = this.clone();
//     while (!fpq.isEmpty()) {
//       yield fpq.poll();
//     }
//   };
// }
FastPriorityQueue.prototype.forEach = function(callback) {
  if (this.isEmpty() || typeof callback != 'function') return;
  var i = 0;
  var fpq = this.clone();
  while (!fpq.isEmpty()) {
    callback(fpq.poll(), i++);
  }
};

// return the k 'smallest' elements of the queue
// runs in O(k log k) time
// this is the equivalent of repeatedly calling poll, but
// it has a better computational complexity, which can be
// important for large data sets.
FastPriorityQueue.prototype.kSmallest = function(k) {
  if (this.size == 0) return [];
  var comparator = this.compare;
  var arr = this.array
  var fpq = new FastPriorityQueue(function(a,b){
   return comparator(arr[a],arr[b]);
  });
  k = Math.min(this.size, k);
  var smallest = new Array(k);
  var j = 0;
  fpq.add(0);
  while (j < k) {
    var small = fpq.poll();
    smallest[j++] = this.array[small];
    var l = (small << 1) + 1;
    var r = l + 1;
    if (l < this.size) fpq.add(l);
    if (r < this.size) fpq.add(r);
  }
  return smallest;
}

function maxIndex(ai) {
  let max = -1
  let ind = -1
  for(let i = 0; i < ai.length; i++) {
    if (max < ai[i]) {
      ind = i
      max = ai[i]
    }
  }
  return ind
}

function main(input) {
  const inputs =input.split('\n')
  const [N] = inputs[0].split(' ').map(Number)
  const Ai = inputs[1].split(' ').map(Number)

  const sortedAi = Ai.sort().reverse()
  // console.log(sortedAi)

  let number = sortedAi.shift()
  let currentAi = new FastPriorityQueue(function (a, b) {
    return a > b
  })
  currentAi.add(number)
  let countAi = number
  for(let i = 1; i < N ; i++) {
    const number = sortedAi.shift()
    const v = currentAi.poll()
    console.log('number:', number, 'v:', v)
    countAi += v
    currentAi.add(number)
    currentAi.add(number)
    console.log(currentAi)
  }
  console.log(countAi)
}

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


"use strict";

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

    let answer = 0;

    answer += A[0];
    let cnt = 1;

    for(let i=1; i<N; i++) {
        answer += A[i];
        cnt++;
        if(cnt >= N - 1) break;

        answer += A[i];
        cnt++;
        if(cnt >= N - 1) break;

        // console.log("cnt:" + cnt);
        // console.log("A[i]:" + A[i]);
        // console.log("answer:" + answer);
        // console.log("----")
    }

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


"use strict";

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

    console.log(A.reduce((m,n)=>m+n) - A[A.length-1] - A[A.length-2] + A[1]);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));