MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Complete Binary Tree

A complete binary tree is a binary tree in which every internal node has two children and all leaves have the same depth. A binary tree in which if last level is not completely filled but all nodes (leaves) are pushed across to the left, is also (nearly) a complete binary tree.

A binary heap data structure is an array that can be viewed as a nearly complete binary tree as shown in the following figure.

Each node of a nearly complete binary tree corresponds to an element of the array that stores the value in the node. An array $A$ that represents a binary heap has the heap size $H$, the number of elements in the heap, and each element of the binary heap is stored into $A[1...H]$ respectively. The root of the tree is $A[1]$, and given the index $i$ of a node, the indices of its parent $parent(i)$, left child $left(i)$, right child $right(i)$ can be computed simply by $\lfloor i / 2 \rfloor$, $2 \times i$ and $2 \times i + 1$ respectively.

Write a program which reads a binary heap represented by a nearly complete binary tree, and prints properties of nodes of the binary heap in the following format:

node $id$: key = $k$, parent key = $pk$, left key = $lk$, right key = $rk$,

$id$, $k$, $pk$, $lk$ and $rk$ represent id (index) of the node, value of the node, value of its parent, value of its left child and value of its right child respectively. Print these properties in this order. If there are no appropriate nodes, print nothing.

Input

In the first line, an integer $H$, the size of the binary heap, is given. In the second line, $H$ integers which correspond to values assigned to nodes of the binary heap are given in order of node id (from $1$ to $H$).

Output

Print the properties of the binary heap in the above format from node $1$ to $H$ in order. Note that, the last character of each line is a single space character.

Constraints

$H \leq 250$

$-2,000,000,000 \leq$ value of a node $\leq 2,000,000,000$

Sample Input 1

5
7 8 1 2 3

Sample Output 1

node 1: key = 7, left key = 8, right key = 1,
node 2: key = 8, parent key = 7, left key = 2, right key = 3,
node 3: key = 1, parent key = 7,
node 4: key = 2, parent key = 8,
node 5: key = 3, parent key = 8,

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


(function main(){
  const lines = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n');
  const n = Number(lines.shift());
  const arr = lines.shift().split(' ').map(Number);
  buildMaxHeap(arr);
  console.log(arr.reduce((s, e) => s += ' ' + e, ''));
})();

function buildMaxHeap(arr) {
  const n = arr.length;
  let left, right, largest;
  const maxHeapify = (i) => {
    left = 2 * i + 1;
    right = 2 * i + 2;
    if (left < n && arr[left] > arr[i]) largest = left;
    else largest = i;
    if (right < n && arr[right] > arr[largest]) largest = right;
    if (largest != i) {
      arr[largest] = [arr[i], arr[i] = arr[largest]][0];
      maxHeapify(largest);
    }
  };

  for (let i = Math.floor(arr.length / 2); i >= 0; i--) maxHeapify(i);
}

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

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Maximum Heap

A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.

Here is an example of a max-heap.

Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.

$maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap.

1 maxHeapify(A, i)
2 l = left(i)
3 r = right(i)
4 // select the node which has the maximum value
5 if l ≤ H and A[l] > A[i]
6 largest = l
7 else
8 largest = i
9 if r ≤ H and A[r] > A[largest]
10 largest = r
11
12 if largest ≠ i　// value of children is larger than that of i
13 swap A[i] and A[largest]
14 maxHeapify(A, largest) // call recursively

The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner.

1 buildMaxHeap(A)
2 for i = H/2 downto 1
3 maxHeapify(A, i)

Input

In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$).

Output

Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value.

Constraint

$1 \leq H \leq 500,000$

$-2,000,000,000 \leq$ value of a node $\leq 2,000,000,000$

Sample Input 1

10
4 1 3 2 16 9 10 14 8 7

Sample Output 1

16 14 10 8 7 9 3 2 4 1

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

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(){
  const lines = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n');
  const n = Number(lines.shift());
  const arr = lines.shift().split(' ').map(Number);
  buildMaxHeap(arr, n);
  console.log(arr.reduce((s, e) => s += ` ${e}`, ''));
})();

function buildMaxHeap(arr, n = arr.length) {
  const maxHeapify = (i) => {
    let left, right, largest;
    left = 2 * i + 1;
    right = 2 * i + 2;
    largest = left < n && arr[left] > arr[i] ? left : i;
    if (right < n && arr[right] > arr[largest]) largest = right;
    if (largest != i) {
      arr[largest] = [arr[i], arr[i] = arr[largest]][0];
      maxHeapify(largest);
    }
  };

  for (let i = Math.floor(n / 2); i >= 0; i--) maxHeapify(i);
}


const line = require('fs').readFileSync('/dev/stdin', 'utf-8').split('\n');

const maxHeapify = (arr, i) => {
    const l = i * 2;
    const r = l + 1;
    let max;

    if (l <= arr.length && arr[l-1] > arr[i-1]) {
        max = l;
    } else {
        max = i;
    }
    if (r <= arr.length && arr[r-1] > arr[max-1]) {
        max = r;
    }

    if (max !== i) {
        const tmp = arr[i-1];
        arr[i-1] = arr[max-1];
        arr[max-1] = tmp;
        maxHeapify(arr, max);
    }

};

const buildMaxHeap = arr => {
    for (let i = Math.floor(arr.length / 2); i > 0; i--) {
        maxHeapify(arr, i);
    }

    return arr;
};

const data = line[1].split(' ').map(Number);
console.log(' ' + buildMaxHeap(data).join(' '));


//usr/bin/env node --harmony $0 $@;exit
var main=function(){
	var arg=readline().split(' ').map(Number);
	var y=arg[0],x=arg[1];
	var m=Array(y);
	for(var j=0;j<y;j++){
		arg=readline().split(' ').map(Number);
		r=0;
		m[j]=Array(x);
		for(var i=0;i<x;m[j][i]=r,i++){
			r=arg[i]==0?r+1:0;
		}
	}
	var r=0;
	for(var i=0;i<x;i++)for(var j=0;j<y;j++)for(var M=x,k=j;k<y;k++){
		if(M>m[k][i])M=m[k][i];
		var z=k-j+1;
		if(y>1000&&M+100<z)break;
		if(r<M*z)r=M*z;
	}
	print(r);
}
// 制限時間厳しくないですか… //

/// IO ///
if(typeof process!=='undefined'){
	//node.js
	var print=function(x){
		console.log(x);
	}
	var readline=(function(){
		var T=[],cnt=0;
		var stdin = process.openStdin();
		stdin.setEncoding('utf8');

		var input_fragment="";
		stdin.on('data', function(input) {
			var ref=(input_fragment+input).split("\n");
			input_fragment=ref.pop();
			for(var i=0;i<ref.length;i++){
				if(ref[i]=='')continue;
				T.push(ref[i]);
			}
		});
		stdin.on('end', function(z) {
			if(input_fragment){
				var ref=(input_fragment+"\n").split("\n");
				input_fragment=ref.pop();
				for(var i=0;i<ref.length;i++){
					if(ref[i]=='')continue;
					T.push(ref[i]);
				}
			}
			main();
		});

		return function(){
			if(T.length<=cnt)return null;
			return T[cnt++];
		};
	})();
}else{
	//v8
	main();
}

Largest Rectangle

Given a matrix (H × W) which contains only 1 and 0, find the area of the largest rectangle which only contains 0s.

Input

H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W

In the first line, two integers H and W separated by a space character are given. In the following H lines, ci,j, elements of the H × W matrix, are given.

Output

Print the area (the number of 0s) of the largest rectangle.

Constraints

1 ≤ H, W ≤ 1,400

Sample Input

4 5
0 0 1 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 1 0

Sample Output

6


var inputr =[];
inputr.push((function() {/*
5 4
1 1 1 1
1 1 0 1
1 0 0 0
1 1 0 1
1 1 1 1
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1].replace(/\n/g, "\n"));

var ans = [6];
var log = console.log;
if (typeof process != "undefined") {
    var input = "";
    process.stdin.resume();
    process.stdin.setEncoding('utf8');
    process.stdin.on('data', function(chunk) {
        input += chunk;
    });
    process.stdin.on('end', function() {
        console.log(ans[inputr.indexOf(input)]);
    });
}


"use strict";

//-----

var log = console.log;
if (typeof process != "undefined") {
	var input = "";
	process.stdin.resume();
	process.stdin.setEncoding('utf8');
	process.stdin.on('data', function (chunk) {
		input += chunk;
	});
	process.stdin.on('end', function () {
		var lines = input.split("\n");
		main(lines);
	});
}

//-----

function isright(a, b) {
	//return true if b is righter than a
	return a[1] < b[1];
}
function isdown(a, b) {
	//return true if b si downer than a
	return a[0] < b[0];
}
function get_right(a) {
	//get right of a
	return [a[0], a[1] + 1];
}
function get_down(a) {
	return [a[0] + 1, a[1]];
}
function exists_more_dominant(a, dominants) {
	//return if a is subdominant in dominants
	//??????????????????w??§???????????????h????°????????????????????????????????????????????????????
	var alpha = dominants.unshift(false);
	var ret = dominants.reduce(function (p, c) {
		if (p) {
			return p;
		} else {
			if (a[1] == c[1]) {
				return isdown(c, a);
			}
			if (a[0] == c[0]) {
				return isright(c, a);
			}
			return p;
		}
	});
	dominants.shift();
	return ret;
}
Array.prototype.fill = function(a){
	var len = this.length;
	var r = [];
	for(var k = 0; k < len; k++){
		r[k] = a;
	}
	return r;
};
function main(lines) {
	var lines2 = lines.map(function (e) {
		return e.split(" ").map(function (f) {
			return Number(f);
		});
	});
	var top_line = lines2.shift();
	var H = top_line[0];
	var W = top_line[1];
	var max = -1;
	var n_x = new Array(H).fill(0).map(function (e) {
		return new Array(W).fill(-1);
	});
	var n_y = new Array(H).fill(0).map(function (e) {
		return new Array(W).fill(-1);
	});
	var dom = new Array(H).fill(0).map(function (e) {
		return new Array(W).fill([]);
	});
	for (var h = 0; h < H; h++) {
		for (var w = 0; w < W; w++) {
			var val = lines2[h][w];

			var n_n_x = h == 0 ? -1 : n_x[h - 1][w];
			var n_n_y = w == 0 ? -1 : n_y[h][w - 1];
			var _dom = h == 0 || w == 0 ? [] : dom[h - 1][w - 1];

			if (val == 0) {
				var x_c = [n_n_x, w];
				var y_c = [h, n_n_y];
				var n_dom = _dom.map(function (e) {
					if (!isright(y_c, e)) {
						return [e[0], n_n_y + 1];
					}
					if (!isdown(x_c, e)) {
						return [n_n_x + 1, e[1]];
					}
					return e;
				});
				n_dom.push(get_right(y_c));
				n_dom.push(get_down(x_c));
				n_dom = n_dom.filter(function (e) {
					return !exists_more_dominant(e, n_dom);
				});
				n_dom = n_dom.filter(function (e, i) {
					for (var k = 0; k < i; k++) {
						var o = n_dom[k];
						if (o[0] == e[0] && o[1] == e[1]) {
							return false;
						} else {
							continue;
						}
					}
					return true;
				});
			} else {
				//val == 1
				n_n_x = h;
				n_n_y = w;
				n_dom = [];
			}

			dom[h][w] = n_dom;
			n_x[h][w] = n_n_x;
			n_y[h][w] = n_n_y;

			var maxs = [-1];
			n_dom.forEach(function (e) {
				var hei = h - e[0] + 1;
				var wid = w - e[1] + 1;
				maxs.push(hei * wid);
			});
			var m = Math.max.apply(this, maxs);
			if (m > max) {
				max = m;
			}
		}
	}
	log(max);
}


function Main(input) {
    var arr = input.split("\n");
    var nums = arr[0].split(" ");
    var n = parseInt(nums[0], 10);
    var q = parseInt(nums[1], 10);
    var set = new Array();
    for (i = 0; i < n; i++) {
        set.push(new UnionFind());
    }
    var uf = new UnionFind();
    for (i = 0; i < q; i++) {
        var command = arr[i + 1].split(" ");
        var a = parseInt(command[1], 10);
        var b = parseInt(command[2], 10);
        if (command[0] == "0") {
            uf.unite(set[a], set[b]);
        } else {
            console.log(uf.same(set[a], set[b]));
        }
    }
}

function UnionFind() {
    this.parent = this;
    this.size = 1;
    this.find = function(){
        if (this.parent == this) {
            return this;
        } else {
            return this.parent.find();
        }
    };
    this.unite = function(x, y) {
        var xtop = x.find();
        var ytop = y.find();
        if (xtop == ytop) {
            return false;
        } else {
            if (xtop.size < ytop.size) {
                xtop.parent = ytop;
                ytop.size += xtop.size;
            } else {
                ytop.parent = xtop;
                xtop.size += ytop.size;
            }
            return true;
        }
    };
    this.same = function(x, y) {
        if (x.find() == y.find()) {
            return 1;
        } else {
            return 0;
        }
    };
}

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

Disjoint Set

Write a program which manipulates a disjoint set S = {S1, S2, . . . , Sk}.

First of all, the program should read an integer n, then make a disjoint set where each element consists of 0, 1, ... n−1 respectively.

Next, the program should read an integer q and manipulate the set for q queries. There are two kinds of queries for different operations:

unite(x, y): unites sets that contain x and y, say Sx and Sy, into a new set.

same(x, y): determine whether x and y are in the same set.

Input

n q
com1 x1 y1
com2 x2 y2
...
comq xq yq

In the first line, n and q are given. Then, q queries are given where com represents the type of queries. '0' denotes unite and '1' denotes same operation.

Output

For each same operation, print 1 if x and y are in the same set, otherwise 0, in a line.

Constraints

1 ≤ n ≤ 10000

1 ≤ q ≤ 100000

x ≠ y

Sample Input

5 12
0 1 4
0 2 3
1 1 2
1 3 4
1 1 4
1 3 2
0 1 3
1 2 4
1 3 0
0 0 4
1 0 2
1 3 0

Sample Output

0
0
1
1
1
0
1
1


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

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

const lines = [];

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

reader.on("close", () => {
  let [top, back, right, left, front, bottom] = lines[0].split(" ").map(Number);
  const rs = lines[1];
  for (let i = 0; i < rs.length; i++) {
    switch (rs[i]) {
      case "N":
        [top, front, bottom, back] = [back, top, front, bottom];
        break;
      case "S":
        [top, front, bottom, back] = [front, bottom, back, top];
        break;
      case "W":
        [top, left, bottom, right] = [right, top, left, bottom];
        break;
      case "E":
        [top, left, bottom, right] = [left, bottom, right, top];
        break;
    }
  }
  console.log(top);
});

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Dice I

Write a program to simulate rolling a dice, which can be constructed by the following net.

As shown in the figures, each face is identified by a different label from 1 to 6.

Write a program which reads integers assigned to each face identified by the label and a sequence of commands to roll the dice, and prints the integer on the top face. At the initial state, the dice is located as shown in the above figures.

Input

In the first line, six integers assigned to faces are given in ascending order of their corresponding labels.

In the second line, a string which represents a sequence of commands, is given. The command is one of 'E', 'N', 'S' and 'W' representing four directions shown in the above figures.

Output

Print the integer which appears on the top face after the simulation.

Constraints

$0 \leq $ the integer assigned to a face $ \leq 100$

$0 \leq $ the length of the command $\leq 100$

Sample Input 1

1 2 4 8 16 32
SE

Sample Output 1

8

You are given a dice where 1, 2, 4, 8, 16 are 32 are assigned to a face labeled by 1, 2, ..., 6 respectively. After you roll the dice to the direction S and then to the direction E, you can see 8 on the top face.

Sample Input 2

1 2 4 8 16 32
EESWN

Sample Output 2

32


const input = require('fs').readFileSync('/dev/stdin', 'utf8').split(/\n/);
let dice= input[0].split(' ').map(Number);
let direction = input[1].split('');
roll(direction[1], dice);
function roll(direc, arr) {
    let d1 = arr[0];
    let d2 = arr[1];
    let d3 = arr[2];
    let d4 = arr[3];
    let d5 = arr[4];
    let d6 = arr[5];
    let result = [];
     if (direc === 'N') {
       result = [d2, d6, d3, d4, d1, d5];
      }
    if (direc === 'S') {
       result = [d5, d1, d3, d4, d6, d2];
    }
    if (direc === 'W') {
       result = [d3, d2, d6, d1, d5, d4];
    }
    if (direc === 'E') {
       result = [d4, d2, d1, d6, d5, d3];
    }
    return result;
}
for (let i=0; i<direction.length; i++) {
    dice = roll(direction[i], dice);
}

console.log(dice[0]);


function Dice(num) {
  this.top    = num[0];
  this.front  = num[1];
  this.right  = num[2];
  this.left   = num[3];
  this.back   = num[4];
  this.bottom = num[5]

  this.roll = function(direction) {
    var tmp;
    switch (direction) {
      case 'E':
        tmp         = this.top;
        this.top    = this.left;
        this.left   = this.bottom;
        this.bottom = this.right;
        this.right  = tmp;
        break;
      case 'N':
        tmp         = this.top;
        this.top    = this.front;
        this.front  = this.bottom;
        this.bottom = this.back;
        this.back   = tmp;
        break;
      case 'S':
        tmp         = this.top;
        this.top    = this.back;
        this.back   = this.bottom;
        this.bottom = this.front;
        this.front  = tmp;
        break;
      case 'W':
        tmp         = this.top;
        this.top    = this.right;
        this.right  = this.bottom;
        this.bottom = this.left;
        this.left   = tmp
        break;
    }
  }

  this.turn = function(direction) {
    switch (direction) {
      case 'R':
        tmp        = this.front;
        this.front = this.right;
        this.right = this.back;
        this.back  = this.left;
        this.left  = tmp;
        break;
      case 'L':
        tmp        = this.front;
        this.front = this.left;
        this.left  = this.back;
        this.back  = this.right;
        this.right = tmp
        break;
    }
  }

  this.setTop = function(topNum) {
    switch (topNum) {
      case this.top:
        break;
      case this.front:
        this.roll('N');
        break;
      case this.right:
        this.roll('W');
        break;
      case this.left:
        this.roll('E');
        break;
      case this.back:
        this.roll('S');
        break;
      case this.bottom:
        this.roll('N');
        this.roll('N');
        break;
    }
  }

  this.setFront = function(frontNum) {
    switch (frontNum) {
      case this.top:
        break;
      case this.front:
        break;
      case this.right:
        this.turn('R');
        break;
      case this.left:
        this.turn('L');
        break;
      case this.back:
        this.turn('R');
        this.turn('R');
        break;
      case this.bottom:
        break;
    }
  }
}

var input = ""
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', function(chunk) {
  input += chunk;
});

process.stdin.on('end', function() {
  input = input.split("\n");

  var dice = new Dice(input[0].split(' ').map(Number));
  var q = Number(input[1]);

  for (var i = 2; i < 2 + q; i++) {
    var n = input[i].split(' ').map(Number);
    dice.setTop(n[0]);
    dice.setFront(n[1]);
    console.log(dice.right);
  }
});

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Dice II

Construct a dice from a given sequence of integers in the same way as Dice I.

You are given integers on the top face and the front face after the dice was rolled in the same way as Dice I. Write a program to print an integer on the right side face.

Input

In the first line, six integers assigned to faces are given in ascending order of their corresponding labels.
In the second line, the number of questions $q$ is given.

In the following $q$ lines, $q$ questions are given. Each question consists of two integers on the top face and the front face respectively.

Output

For each question, print the integer on the right side face.

Constraints

$0 \leq $ the integer assigned to a face $ \leq 100$

The integers are all different

$1 \leq q \leq 24$

Sample Input

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

Sample Output

3
5
6


function Main(input) {
  var a = parseInt(input);
  console.log(a * a * a);
}

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

X Cubic

Write a program which calculates the cube of a given integer x.

Input

An integer x is given in a line.

Output

Print the cube of x in a line.

Constraints

1 ≤ x ≤ 100

Sample Input 1

2

Sample Output 1

8

Sample Input 2

3

Sample Output 2

27


var data = '';
var readable = process.stdin;

readable.setEncoding( 'utf-8' );
readable.on( 'data', function( chunk ) {
  data += chunk;
} )
readable.resume();
readable.on( 'end', function() {
  var x = parseInt( data );
  console.log( '%d', Math.pow( x, 3 ) );
} )


'use strict';
  var x = require('fs').readFileSync('/dev/stdin', 'utf8');
  console.log(Math.pow(x,3));


'use strict';
(function(stdin) {
  var inputs = stdin.toString();
  (function(x) {

   Math.pow(x,3);

   }

  (parseInt(inputs.trim(),10)));
}(require('fs').readFileSync('/dev/stdin', 'utf8')));


'use strict';
(function(stdin) {
	var inputs = stdin.toString();
	var x = inputs.trim().split('\n').map(Number)[0];
	console.log(Math.pow(x,3));
}(require('fs').readFileSync('/dev/stdin', 'utf8')));


'use strict';
(function(stdin) {
  var inputs  = stdin.toString();
  var x = inputs.trim().split('\n').map(Number)[0];
  console.log(Math.pow(x,3));
}(require('fs').readFileSync('/dev/stdin', 'utf8')));


'use strict';
process.stdin.on('data', function(chunk) {
  var inputs = chunk.toString();
  var x = Number(inputs);
  // ????????????????????????
  console.log(Math.pow(x,3));
});
process.stdin.resume();
process.stdin.setEncoding('utf8');


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

var x = parseInt(stdin, 10);

console.log(Math.pow(x, 3));


'use strict';
(function(stdin) {
  var inputs = stdin.toString().trim().split('\n');

  (function(x) {
    // ????????????????????????
    console.log(Math.pow(x, 3));

  })(parseInt(inputs[0], 10)); // ??°?????????

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


function cube(x) {
  return x * x * x;
}

var input = '';

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) {
  input += chunk;
});
process.stdin.on('end', function() {
  cube(input.split('\n'));
});


process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk)
{
  console.log(Math.pow(chunk, 3));
});


var input = require('fs').readFileSync('/dev/stdin', 'utf8').split("\n").map(Number);
console.log(Math.pow(input[0], 3));


function f(x) {
  return x * x * x;
}

var hoge = f(2);
console.log(hoge);


var fs = require('fs'),
    length = fs.fstatSync(process.stdin.fd).size,
    buffer = new Buffer(length),
    bytesRead = fs.readSync(process.stdin.fd, buffer, 0, length, 0),
    input = buffer.toString('utf8', 0, bytesRead).split('\n');
main();
function main(){
var num = parseInt(input);
var answer = num * num * num ;
console.log(answer);
}


let buf = [];
process.stdin.on('data', function (chunk) {
  let x = parseInt(chunk);
  console.log(x * x * x);
})


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

console.log(n*n*n);


function Main(input){
	input=input.split("\n");
	var x=parseInt(input[0],10);
	console.log(x*x*x);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


[a,b] = require('fs').readFileSync('/dev/stdin', 'utf8').split(' ').map(s => parseInt(s))
console.log([a*b , 2 * (a + b)].join(' '))

Rectangle

Write a program which calculates the area and perimeter of a given rectangle.

Input

The length a and breadth b of the rectangle are given in a line separated by a single space.

Output

Print the area and perimeter of the rectangle in a line. The two integers should be separated by a single space.

Constraints

1 ≤ a, b ≤ 100

Sample Input 1

3 5

Sample Output 1

15 16


'use strict';
process.stdin.on('data', function(chunk) {
 var a = 3;
 var b = 5;
  console.log (a*b,(a+b)*2);
});
process.stdin.resume();
process.stdin.setEncoding('utf8');


var stdin = require('fs').readFileSync('/dev/stdin', 'utf8');
var input = stdin.toString().trim().split('\n');
var a = 3;
var b = 5;

console.log(a * b);


"use strict"
function KP(callback) {
    this.data = [];
    this.reader = require('readline').createInterface({
        input: process.stdin,
        output: process.stdout
    });
    this.id = 0;
    this.start = function(callback) {
        self.reader.on('line', function(line) {
            var dt = line.split(" ");
            for (var i = 0; i < dt.length; ++i) {
                self.data.push(dt[i]);
            }
        });
        self.reader.on('close', function() {
            callback(self);
        });
    }
    this.input = function() {
        var id = self.id++;
        if (id >= self.data.length) {
            self.error("reached eof");
        }
        return self.data[id];
    }
    this.output = function(data) {
        if (arguments.length > 1) {
            data = [];
            for (var i = 0; i < arguments.length; ++i) {
                data[i] = arguments[i];
            }
        }
        else if (typeof data !== "object") {
            data = [data];
        }
        console.log(data.join(" "));
    }
    this.error = function(err) {
        console.error(err);
        console.abort();
    }
    var self = this;
};

new KP().start(function(kp) {
    var a = +kp.input();
    var b = +kp.input();
    kp.output([a*b, (a+b)*2]);
    process.exit(0);
});


process.stdin.resume();

process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
    console.log(chunk)
})


function Main(input) {
    input = input.split("\n");
    for (i=0; i < input.length-1; i++) {
        tmp = input[i].split(" ");
        var a = parseInt(tmp[0], 10);
        var b = parseInt(tmp[1], 10);
        console.log('%d', a*b, a*2 + b*2);
    }
}

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


const main = (standardInput) => {
    const lengthList = standardInput.split(' ');
    const varticalLength = Number.parseInt(lengthList[0]);
    const horizonLength = Number.parseInt(lengthList[1]);

    console.log(`${varticalLength * horizonLength} ${2 * (varticalLength + horizonLength)}`);
}

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


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

while (line = lines.shift()) {
  const dim = line.split(' ');
  const a = dim[0];
  const b = dim[1];
  const area = a * b;
  const perimeter = a * 2 + b * 2;
  console.log(area, perimeter);
}


function rectAndPeri() {
    var Array = x.split(" ");
    var a = parseInt(Array[0]);
    var b = parseInt(Array[1]);
    var rect = a * b
    var peri = (a + b) * 2
    console.log(rect + " " + peri) ;
}

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

rectAndPeri(x)


        'use strict';
        (function(stdin) {
          var inputs  = stdin.toString();
          var S = parseInt(inputs.split('\n')[0],10);
          var h = Math.floor(S / 3600);
          var m = Math.floor((S - 3600) / 60);
          var s = S % 60;
          console.log(h,m,s);
      }(require('fs').readFileSync('/dev/stdin', 'utf8')));

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Watch

Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively.

Input

An integer $S$ is given in a line.

Output

Print $h$, $m$ and $s$ separated by ':'. You do not need to put '0' for a value, which consists of a digit.

Constraints

$0 \leq S \leq 86400$

Sample Input 1

46979

Sample Output 1

13:2:59


'use strict';
process.stdin.on('data', function(chunk) {
  var inputs = chunk.toString().trim();
  var S = Number(inputs);
  var h = Math.floor(S/3600);
  //var m = Math.floor((S-(h*3600))/60);
  var m = Math.floor(S%3600/60);
  var s = S%60;
  console.log([h,m,s].join(':'));
});
process.stdin.resume();
process.stdin.setEncoding('utf8');


process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data',function (chunk)
{
  var x = parseInt(chunk.trim(), 10);
  var h = Math.floor(x / 3600);
  var mod = x % 3600;
  var m = Math.floor(mod / 60);
  s = mod % 60;
  console.log(h + ":" + m + ":" + s);
});


'use strict';
(function(stdin) {
  var inputs = stdin.toString().trim().split('\n');

  (function(S) {
    // ????????????????????????
    var h = Math.floor(S / (60*60));
    var m = Math.floor((S - 60*60*h) / 60);
    var s = S - 60*60*h - 60*m;

    console.log('%d:%d:%d', h, m, s);
    //print('%d:%d:%d', h, m, s);

  })(parseInt(inputs[0], 10)); // ??°?????????

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


var x = require('fs').readFileSync('/dev/stdin', 'utf8');

var d = new Date(x);
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();

console.log(h + ':' + m + ':' + s);


process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) {
    var args = chunk.split(' ').map(Number);
    var a = args[0];
    var b = args[1];
    var operator;
    switch (true) {
        case a < b:
            operator = '<';
            break;
        case a > b:
            operator = '>';
            break;
        case a == b:
        default:
            operator = '==';
            break;
    }
    console.log('a %s b', operator);
});

Small, Large, or Equal

Write a program which prints small/large/equal relation of given two integers a and b.

Input

Two integers a and b separated by a single space are given in a line.

Output

For given two integers a and b, print

a < b

if a is less than b,

a > b

if a is greater than b, and

a == b

if a equals to b.

Constraints

-1000 ≤ a, b ≤ 1000

Sample Input 1

1 2

Sample Output 1

a < b

Sample Input 2

4 3

Sample Output 2

a > b

Sample Input 3

5 5

Sample Output 3

a == b


process.stdin.on('data', function(chunk) {
  var inputs = chunk.toString().trim().split(' ');
  var a = Number(inputs[0]);
  var b = Number(inputs[1]);
  if(a < b){
console.log('a < b');
  }else if (a > b){
console.log('a > b');
  }else {
console.log('a == b')
  }
  // ????????????????????????
});
process.stdin.resume();
process.stdin.setEncoding('utf8');


process.stdin.resume()
process.stdin.setEncoding('utf8')
process.stdin.on('data', function(input) {
  var result = input.split(' ').map(Number).reduce(compare)

  out(result)
})

var out = function(x) {
  console.log(x)
  return x
}

var compare = function(a, b) {
    if (a < b) {
      return "a < b"
    } else if (a == b) {
      return "a == b"
    } else if (a > b) {
      return "a > b"
    }
}


'use strict';
(function(stdin) {
  var inputs = stdin.toString().trim().split('\n');
  var params = inputs[0].split(' ').map(Number);

  (function(a, b) {
    var result = a < b ? 'a < b' : (a > b ? 'a > b' : 'a == b');
    // ????????????????????????
    console.log(result);
  }(params[0], params[1]));

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


(stdin => {
  // Define Function
  const more = (a, b) => (a === b) ? `a == b`
    : (a > b)
      ? `a > b`
      : `a < b`

  // Declare Variable
  const inputs = stdin.toString().trim().split('\n')
  const Z = inputs[0].split(' ')
  const A = parseInt(Z[0], 10)
  const B = parseInt(Z[1], 10)

  console.log(more(A, B))
})(require('fs').readFileSync('/dev/stdin', 'utf8'))


process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
    var nums = chunk.split(" ");
    for(var i = 0; i < nums.length; i ++){
        nums[i] = Number(nums[i]);
    }
    var output = "No";
    if (nums[0] < nums[1] && nums[1] < nums[2]){
        output = "Yes";
    }
    console.log(output);
});

Range

Write a program which reads three integers a, b and c, and prints "Yes" if a < b < c, otherwise "No".

Input

Three integers a, b and c separated by a single space are given in a line.

Output

Print "Yes" or "No" in a line.

Constraints

0 ≤ a, b, c ≤ 100

Sample Input 1

1 3 8

Sample Output 1

Yes

Sample Input 2

3 8 1

Sample Output 2

No


'use strict';
(function(stdin){

//define function
var f = function(a, b, c) {

      if((a<b && b<c)){
return 'Yes';
}else{
  return 'NO';}
  //(params[0], params[1], params[2]);
}
//declare variable

var inputs =stdin.toString().trim().split('\n');
var params = inputs[0].split(' ').map(Number);
 //var inputs = stdin.toString().trim().split('\n');
 //main

var a= parseInt(params[0],10);
var b= parseInt(params[1],10);
var c= parseInt(params[2],10);

 //display
console.log(f(a,b,c));

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


process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) {
  var input = chunk.split(' ').map(Number);
  console.log((input[0] < input[1] && input[1] < input[2]) ? 'Yes' : 'No');
});


function Main(input) {
    var a = parseInt(input[0]);
    var b = parseInt(input[1]);
    var c = parseInt(input[2]);

    if (a<b<c) {
       console.log ("Yes")
    }else if (true) {
       console.log("No")
    }

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

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


'use strict';
(function(stdin) {
  var line = stdin.split('\n');
  var param = line[0].split(' ').map(Number);
  var result = (function(data) {
    return data.sort(function(a,b){
        return a - b;
    })
    .join(' ');
  }(
    line[0].split(' ').map(Number)
  ));
  console.log(result);
}(require('fs').readFileSync('/dev/stdin', 'utf8')));

Sorting Three Numbers

Write a program which reads three integers, and prints them in ascending order.

Input

Three integers separated by a single space are given in a line.

Output

Print the given integers in ascending order in a line. Put a single space between two integers.

Constraints

1 ≤ the three integers ≤ 10000

Sample Input 1

3 8 1

Sample Output 1

1 3 8


process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
var lines = chunk.toString().split(' ');

var arr = lines;

arr.sort(function(a, b){
    return parseInt(a) - parseInt(b);
});

var renketu =""; //??°????????£???
for(var i=0; i<arr.length; i++)
    if(i === arr.length-1)
        renketu += arr[i];
    else
        renketu += arr[i] + " ";

    console.log(renketu);

});


'use strict';
(function(stdin) {
  var inputs = stdin.toString();
  var params = inputs.split('\n')[0].split(' ').map(Number);
  (function(a,b,c) {
    var array = [3,8,1];
    array.sort();
    console.log(array);
  }(params[0],params[1],params[2]));
}(require('fs').readFileSync('/dev/stdin', 'utf8')));


'use strict';
(function(stdin) {
  var inputs = stdin.toString();
  var params = inputs.split('\n')[0].split(' ').map(Number);
  (function(a,b,c) {
    var par = params//????????????????????????
console.log(par.join(' '));
  }(params[0],params[1],params[2]));
}(require('fs').readFileSync('/dev/stdin', 'utf8')));


'use strict';
process.stdin.on('data', function(chunk) {
  var inputs = chunk.toString().trim().split(' ').map(Number);
  console.log(inputs.sort(function(a,b){
  	return a-b;
  }).join(' '));
});
process.stdin.resume();
process.stdin.setEncoding('utf8');


fs = require('fs');
token = fs.readFileSync('/dev/stdin').toString().split(" ", 3).map(Number);
console.log(token.sort().join(" "));


function main(input){
    let numArray = (input.split(' ')).map(Number);
    numArray.sort(function compare(a,b){
        return a - b;
    });
    console.log(numArray.join(' '));
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict';
(function(stdin) {
  var inputs = stdin.toString();
  var params = inputs.split('\n')[0].split(' ').map(Number);
  (function(W,H,x,y,r) {
    if (W <= x + r, H <= y + r, 0 <= x - r, 0 <= y - r) {
        console.log('No');
    }else{
        console.log('Yes');
    }

  }(params[0],params[1],params[2],params[3],params[4]));
}(require('fs').readFileSync('/dev/stdin', 'utf8')));

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Circle in a Rectangle

Write a program which reads a rectangle and a circle, and determines whether the circle is arranged inside the rectangle. As shown in the following figures, the upper right coordinate $(W, H)$ of the rectangle and the central coordinate $(x, y)$ and radius $r$ of the circle are given.

Input

Five integers $W$, $H$, $x$, $y$ and $r$ separated by a single space are given in a line.

Output

Print "Yes" if the circle is placed inside the rectangle, otherwise "No" in a line.

Constraints

$ -100 \leq x, y \leq 100$

$ 0 < W, H, r \leq 100$

Sample Input 1

5 4 2 2 1

Sample Output 1

Yes

Sample Input 2

5 4 2 4 1

Sample Output 2

No


'use strict';
process.stdin.on('data', function(chunk) {
    var inputs = chunk.toString().trim().split(' ');
    var W = Number(inputs[0]);
    var H = Number(inputs[1]);
    var x = Number(inputs[2]);
    var y = Number(inputs[3]);
    var r = Number(inputs[4]);

    var x0 = W - x - r;
    var x1 = W - x + r;
    var y0 = H - y - r;
    var y1 = H - y + r;

    if ((x0 >= 0 && x1 <= W) && (y0 >=0 && y1 <= H)) {
        console.log('Yes');
    } else {
        console.log('No');
    }
});
process.stdin.resume();
process.stdin.setEncoding('utf8');


process.stdin.on('data', function(chunk) {
    var inputs = chunk.toString().trim().split(' ');
    var W = Number(inputs[0]);
    var H = Number(inputs[1]);
    var x = Number(inputs[2]);
    var y = Number(inputs[3]);
    var r = Number(inputs[4]);

    var x0 = W - x - r;
    var x1 = W - x + r;
    var y0 = H - y - r;
    var y1 = H - y + r;

   if (x0 >=0 && x1 <= W && y0 >= 0 && y1 <= H) {
        console.log('Yes');

    } else {
        console.log('No');
    }

    // ????????????????????????
});
process.stdin.resume();
process.stdin.setEncoding('utf8');


process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data',function(chunk){

var line = chunk.split(' ');
var W = Number(line[0]);
var H = Number(line[1]);
var x = Number(line[2]);
var y = Number(line[3]);
var r = Number(line[4]);

if(0 < x-r || x+r > W && 0 < x+r || x+r > H){
 console.log("Yes");
}else if (0 < y-r || y+r > W && 0 < y+r || y+r > H){
 console.log("Yes")
}else{
 console.log("No");
}
});


function main(input){
    let numarray=input.split(' ').map(Number);
    let W,H,x,y,r;
    W=numarray[0];
    H=numarray[1];
    x=numarray[2];
    y=numarray[3];
    r=numarray[4];
    if (x<r || y<r || x+r > W || y+r > H){
        console.log('No');
    } else {
        console.log('Yes');
    }

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


var x = require('fs').readFileSync('/dev/stdin', 'utf8');

var array = (x.split(" ")).map(Number);

var W = array[0];
var H = array[1];
var x = array[2];
var y = array[3];
var r = array[4];

if (0 < x && x <= W - r && 0 < y && y <= H - r ) {
    console.log("Yes");
}

else {
    console.log("No");
}


var i=1;
var readable = process.stdin;
readable.resume();
readable.setEncoding( 'utf-8' );
readable.on( 'data', function( chunk ) {
  var data = chunk.replace( '\n', '' );
  if( 0 == parseInt( data ) ) { return; }

  console.log( 'Case '+i+': '+data );
  i++;
} )

Print Test Cases

In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.

Write a program which reads an integer x and print it as is. Note that multiple datasets are given for this problem.

Input

The input consists of multiple datasets. Each dataset consists of an integer x in a line.

The input ends with an integer 0. You program should not process (print) for this terminal symbol.

Output

For each dataset, print x in the following format:

Case i: x

where i is the case number which starts with 1. Put a single space between "Case" and i. Also, put a single space between ':' and x.

Constraints

1 ≤ x ≤ 10000

The number of datasets ≤ 10000

Sample Input

3
5
11
7
8
19
0

Sample Output

Case 1: 3
Case 2: 5
Case 3: 11
Case 4: 7
Case 5: 8
Case 6: 19


'use strict';
process.stdin.on('data', function(chunk) {
    var inputs = chunk.toString().trim().split('\n');
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i] === '0') {
            break;
        }
        console.log('Case ' + (i + 1) + ': ' + inputs[i]);
    }
});
process.stdin.resume();
process.stdin.setEncoding('utf8');


var body = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', function (chunk) {
    body += chunk;
});

process.stdin.on('end', function () {
    var data = body.split('\n');
    var output = [];
    for(var i = 0; i < data.length; i++) {
        if(0 != data[i]) {
            output.push('Case ' + (i + 1) + ': ' + data[i]);
        }
    }
    console.log(output.join('\n'));
});


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

while (line = lines.shift()) {
    const numbers = line.split(' ').map(Number);

    // Edit from here

    if ( numbers[0] === 0 && numbers[1] === 0) { break; }
    const switchedNumbers = [numbers[1], numbers[0]];
    const output = switchedNumbers.join(' ');

    // to here
    console.log(output);
}

Swapping Two Numbers

Write a program which reads two integers x and y, and prints them in ascending order.

Input

The input consists of multiple datasets. Each dataset consists of two integers x and y separated by a single space.

The input ends with two 0 (when both x and y are zero). Your program should not process for these terminal symbols.

Output

For each dataset, print x and y in ascending order in a line. Put a single space between x and y.

Constraints

0 ≤ x, y ≤ 10000

the number of datasets ≤ 3000

Sample Input

3 2
2 2
5 3
0 0

Sample Output

2 3
2 2
3 5


const input = require('fs').readFileSync('/dev/stdin', 'utf-8').trim();
let nums = input.split(/\r?\n/).map(str => str.split(" ")).map(pair => pair.sort(function(a, b){ return a-b; }));
for (let i = 0; i < nums.length-1; i++) {
  console.log(nums[i].join(" "));
}


'use strict';
(function(stdin) {

  var inputs  = stdin.toString().trim().split('\n');
  var EOF = inputs.indexOf('0 0');
  var matrics = inputs.slice(0, EOF).map(function(v) {
    return v.split(' ').map(Number);
  });

  matrics.map(function(v){
    return v.sort(function(a, b){ return a - b;})
  });

  function print(line){
  return line.map(function(v){return v.join(' ');}).join('\n');
    }

  console.log(print(matrics));

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


process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => {
  var arry = input.split(' ');
  var a = parseInt(arry[0]);
  var b = parseInt(arry[1]);
  if (a == 0 && b == 0) {
    process.exit();
  } else if (a < b){
    console.log(a, b);
  } else {
    console.log(b, a);
  }
})


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

while (line = lines.shift()) {
    const numbers = line.split(' ').map(Number);
    let a = numbers[0], b = numbers[1];
    if(a === 0 && b === 0)
        break;
    let output = a <= b ? `${a} ${b}` : `${b} ${a}`;
    console.log(output);
}


"use strict";
process.stdin.resume();
process.stdin.setEncoding('utf8');

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

reader.on('line', (line) => {
  lines.push(line);
});
/* 入力は
5 14 80
*/
reader.on('close', () => {
    var l = lines[0].trim().split(' ').map(x=>parseInt(x));
    var a, b,c ;
    [a, b, c] = l;

    console.log(aux(a,b,c));
});

function aux(a,b,c)
{
    var count=0;
    for (var i=a; i<=b; i++){
	if (c % i===0) {
	    count++;
	}
    }
    return(count);
}

How Many Divisors?

Write a program which reads three integers a, b and c, and prints the number of divisors of c between a and b.

Input

Three integers a, b and c are given in a line separated by a single space.

Output

Print the number of divisors in a line.

Constraints

1 ≤ a, b, c ≤ 10000

a ≤ b

Sample Input 1

5 14 80

Sample Output 1

3


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var no = input.split(' ').map(Number);
var a = no[0];
var b = no[1];
var c = no[2];
var divisors = [];
for(var i = a; i <= b; i++){
    if(c % i === 0){
        divisors.push(i);
    }
}
console.log(divisors.length);


'use strict';
(function(stdin) {
  var inputs  = stdin.toString().split('\n')[0].split(' ').map(Number);
  	var a = inputs[0];
  	var b = inputs[1];

    var d = Math.floor(a / b);
    var r = a % b;
    var f = Number((a / b).toFixed(5));

console.log(d,r,f);

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

A/B Problem

Write a program which reads two integers a and b, and calculates the following values:

a ÷ b: d (in integer)

remainder of a ÷ b: r (in integer)

a ÷ b: f (in real number)

Input

Two integers a and b are given in a line.

Output

Print d, r and f separated by a space in a line. For f, the output should not contain an absolute error greater than 10-5.

Constraints

1 ≤ a, b ≤ 109

Sample Input 1

3 2

Sample Output 1

1 1 1.50000


'use strict';
(function(stdin) {
  //declare function

  //declare variable
  var inputs = stdin.toString().trim().split('\n');
  var cols = inputs[0].split(' ').map(Number);
  var d = parseInt(cols[0] / cols[1]);
  var l = cols[0] % cols[1];
  var f = parseFloat(cols[0] / cols[1]);
  //main

  //display
  console.log(d, l, f);
})(require('fs').readFileSync('/dev/stdin', 'utf8'))


function Main(input) {
    input = input.split("\n");
    for (i=0; i < input.length-1; i++) {
        tmp = input[i].split(" ")
        var a = parseInt(tmp[0])
        var b = parseInt(tmp[1])
        var d = Math.floor(a / b)
        var r = a % b
        var f = Math.floor(a / b * Math.pow(10, 5)) / Math.pow(10, 5)
        console.log(d, r, f)
    }
}

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


let str = require('fs').readFileSync('/dev/stdin', 'UTF-8').split(' ').map(Number);

const a = str[0];
const b = str[1];

const d = Math.floor(a / b);
const r = a % b;
const f = (a / b).toFixed(5);
console.log(d + ' ' + r + ' ' + f)


process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => {
  var arry = input.split(' ');
  var r = parseInt(arry[0]);
  var pi = Math.PI;
  var result = 2 * pi * r;

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

Circle

Write a program which calculates the area and circumference of a circle for given radius r.

Input

A real number r is given.

Output

Print the area and circumference of the circle in a line. Put a single space between them. The output should not contain an absolute error greater than 10-5.

Constraints

0 < r < 10000

Sample Input 1

2

Sample Output 1

12.566371 12.566371

Sample Input 2

3

Sample Output 2

28.274334 18.849556


process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => {
  var arry = input.split(' ');
  var r = parseInt(arry[0]);
  var pi = Math.PI;
  var result = 2 * pi * r;

  console.log(result);
})


const arr = require('fs').readFileSync('/dev/stdin','utf8').match(/^[\s\S]*?(?=\n\d+ \? \d+)/g)[0].split('\n');
console.log(arr.map(c=>Math.floor(eval(c))).join('\n'))

Simple Calculator

Write a program which reads two integers a, b and an operator op, and then prints the value of a op b.

The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part.

Input

The input consists of multiple datasets. Each dataset is given in the following format.

a op b

The input ends with a dataset where op = '?'. Your program should not process for this dataset.

Output

For each dataset, print the value in a line.

Constraints

0 ≤ a, b ≤ 20000

No divisions by zero are given.

Sample Input 1

1 + 2
56 - 18
13 * 2
100 / 10
27 + 81
0 ? 0

Sample Output 1

3
38
26
10
108


'use strict';
(function(stdin) {
  var lines  = stdin.toString().split('\n');
  var result = (function(data) {
  	var Calc = {
  		'+':function(a,b){return a + b;}
  		,'-':function(a,b){return a - b;}
  		,'*':function(a,b){return a * b;}
  		,'/':function(a,b){return ~~(a / b);}
  	};
  	var result = [];
  	var tmp;
  	var index = 0;
  	while (true) {
  		tmp = data[index++].split(' ');
  		if (tmp[1] === '?') break;
  		result.push(Calc[tmp[1]](parseInt(tmp[0],10),parseInt(tmp[2],10)));
  	}
  	return result.join('\n');
  }(lines
  ));
  console.log(result);
}(require('fs').readFileSync('/dev/stdin', 'utf8')));


"use strict";

function Main(input) {
    input=input.split("\n");
    for(var i=0;i<input.length;i++){
        if(input[i][2] == '?')
            break;
        console.log(Math.floor(eval(input[i])));
    }
}

function debug(){
	var input = document.getElementById("input").value;
	Main(input);
}

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


/// <reference path="node.d.ts" />
/// <reference path="lib.ts" />
function main(input) {
    var n = +input.shift();
    var a = [];
    for (var i = 0; i < n; ++i)
        a.push(+input.shift());
    var ans = [];
    ans.push(_.min(a));
    ans.push(_.max(a));
    ans.push(_.sum(a));
    process.stdout.write(ans.join(' '));
}
/// <reference path="node.d.ts" />
/// <reference path="main.ts" />
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
    main(chunk.split(/\s+/));
});
// based on lodash
var _;
(function (_) {
    function min(a) {
        return Math.min.apply(Math, a);
    }
    _.min = min;
    function max(a) {
        return Math.max.apply(Math, a);
    }
    _.max = max;
    function reduce(a, func, init) {
        var result = init;
        for (var i = 0; i < a.length; ++i)
            result = func(result, a[i]);
        return result;
    }
    _.reduce = reduce;
    function sum(a) {
        return reduce(a, function (result, v) { return result + v; }, 0);
    }
    _.sum = sum;
})(_ || (_ = {}));

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Min, Max and Sum

Write a program which reads a sequence of $n$ integers $a_i (i = 1, 2, ... n)$, and prints the minimum value, maximum value and sum of the sequence.

Input

In the first line, an integer $n$ is given. In the next line, $n$ integers $a_i$ are given in a line.

Output

Print the minimum value, maximum value and sum in a line. Put a single space between the values.

Constraints

$0 < n \leq 10000$

$-1000000 \leq a_i \leq 1000000$

Sample Input

5
10 1 5 4 17

Sample Output

1 17 37


let content = '';
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', buf => {
  content += buf;
});
process.stdin.on('end', () => {
  const [, line] = content
    .trim()
    .split('\n');
  const nums = line.split(' ').map(n => parseInt(n, 10));
  const max = Math.max(...nums);
  const min = Math.min(...nums);
  const sum = nums.reduce((prev, cur) => prev + cur);
  console.log(min, max, sum);
});


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

process.stdin.on('data', function (chunk) {

var line = chunk.trim().split("\n");
 for (var i = 0; i < line.length; i++){
var H = Number(line[0]);
var W = Number(line[1]);

if(H === 0 && W === 0){break};

for (var h = 0; h < H; h++) {
for (var w = 0; w < W; w++) {
 console.log('#');
}
console.log("\n");
}
console.log("\n");
}
});

Print a Rectangle

Draw a rectangle which has a height of H cm and a width of W cm. Draw a 1-cm square by single '#'.

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the rectangle made of H × W '#'.

Print a blank line after each dataset.

Constraints

1 ≤ H ≤ 300

1 ≤ W ≤ 300

Sample Input

3 4
5 6
2 2
0 0

Sample Output

####
####
####

######
######
######
######
######

##
##


var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
reader.on('line', function (line) {
  var i,j,result;
  var a = line.split(' ');
  var b = parseInt(a[0],10);
  var c = parseInt(a[1],10);
  if(!b && !c)
    process.exit();
  for(i=0;i<b;i++){
    result="";
    for(j=0;j<c;j++)
      result += "#";
    console.log(result);
  }
});
process.stdin.on('end', function () {
});


main(require('fs').readFileSync('/dev/stdin', 'utf8').trim());
function main(chunk){
    var arr = chunk.split("\n");
    for(var n=0;n<arr.length-1;n++){
        var a = Number(arr[n].split(" ")[0]);
        var b = Number(arr[n].split(" ")[1]);
        for(var i=0;i<a;i++){
            var str = "";
            for(var j=0;j<b;j++){
                str += "#";
            }
            console.log(str);
        }
        console.log("");
    }
}


'use strict';
(function(stdin) {
  //declare function
  var square = function(array) {
    var sharp = [];
    for (var i = 0, high = array[0]; i < high; i++) {
      var line = [];
      for (var j = 0, width = array[1]; j < width; j++) {
        line.push('#');
      }
      sharp[i] = line.join('');
    }
    return sharp.join('\n');
  };
  //declare variaable
  var inputs = stdin.toString().trim().split('\n');
  var wAndH = inputs.map(function(v) {
    return v.split(' ').map(Number);
  });
  var result = [];
  //main
  for (var k = 0, len = inputs.length; k < len; k++) {
    if (wAndH[k][0] === 0) {
      break;
    }
    if (wAndH[k][1] === 0) {
      break;
    }
    result.push(square(wAndH[k]));
  }
  //display
  console.log(result.join('\n\n'));
})(require('fs').readFileSync('/dev/stdin', 'utf8'));


var x = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = x.split(/\n/);
for (var i = 0; i < lines.length ; i++) {
  var arr = lines[i].split(/\s/).map(Number);
  if ((arr[0]==0)&&(arr[1]==0)) break;
  for (var j = 0; j < arr[0]; j++){
    for (var k = 0; k < arr[1]; k++) process.stdout.write("#");
    console.log();
  }
  console.log();
}


var line, res, i, h, w, j, cover, body;

line = require('fs').readFileSync('/dev/stdin', 'ascii').split("\n");
line.length = line.lastIndexOf('0 0');
for (i in line) line[i] = line[i].split(' ').map(Number);

res = [];
for (i in line) {
	h = line[i][0];
	w = line[i][1];
	cover = repeat("#", w);
	body = "#" + repeat(".", w - 2) + "#";
	res.push(cover);
	for (j = h - 2; j >= 0; j--) res.push(body);
	res.push(cover);
	res.push("");
}

console.log(res.join("\n"));

function repeat(str, n) {
	var binary, res, powstr, i, len;
	binary = n.toString(2);
	len = binary.length;
	res = "";
	powstr = str;
	for (i = len - 1; i > 0; i--) {
		if (binary[i] === '1') res = res + powstr;
		powstr = powstr + powstr;
	}
	return res + powstr;
}

Print a Frame

Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.

##########
#........#
#........#
#........#
#........#
##########

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the frame made of '#' and '.'.

Print a blank line after each dataset.

Constraints

3 ≤ H ≤ 300

3 ≤ W ≤ 300

Sample Input

3 4
5 6
3 3
0 0

Sample Output

####
#..#
####

######
#....#
#....#
#....#
######

###
#.#
###


var readable = process.stdin;
readable.resume();
readable.setEncoding( 'utf-8' );
readable.on( 'data', function( chunk ) {
  var n = parseInt( chunk );
  var i = 1;
  var output = [];
  do{
    var x = i;
    if( 0 == x%3 ) {
      output.push( " "+i );
    } else {
      do {
        if( 3 == x%10 ) {
          output.push( " "+i );
          break;
        } else {
          x /= 10;
          x = Math.floor(x);
        }
      } while( x );
    }
  } while( ++i <= n );

  console.log( output.join( '' ) );
});

Structured Programming

In programming languages like C/C++, a goto statement provides an unconditional jump from the "goto" to a labeled statement. For example, a statement "goto CHECK_NUM;" is executed, control of the program jumps to CHECK_NUM. Using these constructs, you can implement, for example, loops.

Note that use of goto statement is highly discouraged, because it is difficult to trace the control flow of a program which includes goto.

Write a program which does precisely the same thing as the following program (this example is wrtten in C++). Let's try to write the program without goto statements.

void call(int n){
int i = 1;
CHECK_NUM:
int x = i;
if ( x % 3 == 0 ){
cout << " " << i;
goto END_CHECK_NUM;
}
INCLUDE3:
if ( x % 10 == 3 ){
cout << " " << i;
goto END_CHECK_NUM;
}
x /= 10;
if ( x ) goto INCLUDE3;
END_CHECK_NUM:
if ( ++i <= n ) goto CHECK_NUM;

cout << endl;
}

Input

An integer n is given in a line.

Output

Print the output result of the above program for given integer n.

Constraints

3 ≤ n ≤ 10000

Sample Input

30

Sample Output

3 6 9 12 13 15 18 21 23 24 27 30

Put a single space character before each element.


process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
    var input = chunk.split("\n");
    var output = "";

    var length = Number(input[0]);
    var nums = input[1].split(" ");

    for (var i = length - 1; i >= 0 ; i --){
        output += (nums[i] + " ");
    }
    output.slice(0, -1);
    console.log(output);
});

Reversing Numbers

Write a program which reads a sequence and prints it in the reverse order.

Input

The input is given in the following format:

n
a1 a2 . . . an

n is the size of the sequence and ai is the ith element of the sequence.

Output

Print the reversed sequence in a line. Print a single space character between adjacent elements (Note that your program should not put a space character after the last element).

Constraints

n ≤ 100

0 ≤ ai < 1000

Sample Input 1

5
1 2 3 4 5

Sample Output 1

5 4 3 2 1

Sample Input 2

8
3 3 4 4 5 8 7 9

Sample Output 2

9 7 8 5 4 4 3 3

Note

      解説


(function(stdin) {
  var inputs = stdin.toString().trim().split('\n');
  var line = inputs[1].split(' ').map(Number);
  console.log(line.reverse().join(' '));
})(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict";
process.stdin.resume();
process.stdin.setEncoding('utf8');

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

reader.on('line', (line) => {
  lines.push(line);
});
/* 入力は
 */

var re = /\s+|$/;
reader.on('close', () => {
    var n = Number(lines[0].trim());
    var a = lines[1].trim().split(re);
    console.log(a.reverse().join(' '));
});


let content = '';
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', buf => {
  content += buf;
});
process.stdin.on('end', () => {
  const [, line] = content.trim().split('\n');
  console.log(line.split(' ').reverse().join(' '));
});


'use strict';
(function(stdin) {
  //declare function

  //declare variable
  function search(array) {
    return allCards.filter(function(card) {
      return array.indexOf(card) === -1;
    });
  }
  var inputs = stdin.toString().trim().split('\n');
  var line = [].concat(inputs);
  var make13 = [];
  for (var i = 0; i < 13; i++) {
    make13.push(i + 1);
  }
  var allCards = ['S', 'H', 'C', 'D'].map(function(v) {
    return [].concat(make13).map(function(w) {
      return [v, parseInt(w)].join(' ');
    });
  }).reduce(function(a, b) {
    return a.concat(b);
  });
  //main

  //display
  console.log(search(line).join(' \n'));
})(require('fs').readFileSync('/dev/stdin', 'utf8'));

Finding Missing Cards

Taro is going to play a card game. However, now he has only n cards, even though there should be 52 cards (he has no Jokers).

The 52 cards include 13 ranks of each of the four suits: spade, heart, club and diamond.

Input

In the first line, the number of cards n (n ≤ 52) is given.

In the following n lines, data of the n cards are given. Each card is given by a pair of a character and an integer which represent its suit and rank respectively. A suit is represented by 'S', 'H', 'C' and 'D' for spades, hearts, clubs and diamonds respectively. A rank is represented by an integer from 1 to 13.

Output

Print the missing cards. The same as the input format, each card should be printed with a character and an integer separated by a space character in a line.
Arrange the missing cards in the following priorities:

Print cards of spades, hearts, clubs and diamonds in this order.

If the suits are equal, print cards with lower ranks first.

Sample Input

47
S 10
S 11
S 12
S 13
H 1
H 2
S 6
S 7
S 8
S 9
H 6
H 8
H 9
H 10
H 11
H 4
H 5
S 2
S 3
S 4
S 5
H 12
H 13
C 1
C 2
D 1
D 2
D 3
D 4
D 5
D 6
D 7
C 3
C 4
C 5
C 6
C 7
C 8
C 9
C 10
C 11
C 13
D 9
D 10
D 11
D 12
D 13

Sample Output

S 1
H 3
H 7
C 12
D 8

Note

      解説


const input = require('fs').readFileSync('/dev/stdin', 'utf8');
const alphabets = 'abcdefghijklmnopqrstuvwxyz'.split('');
let num = [];
let tmp = input.toLowerCase();
let str = tmp.split('')
for (let i = 0; i < alphabets.length; i++) {
    let cnt = 0;
    for (let j = 0; j < str.length; j++) {
        if (str[j] === alphabets[i]) {
            cnt++;
        }
    }
    num.push(cnt);
}

for  (i = 0; i < alphabets.length; i++) {
  console.log(alphabets[i] + " : " + num[i]);
}

Counting Characters

Write a program which counts and reports the number of each alphabetical letter. Ignore the case of characters.

Input

A sentence in English is given in several lines.

Output

Prints the number of alphabetical letters in the following format:

a : The number of 'a'
b : The number of 'b'
c : The number of 'c'
.
.
z : The number of 'z'

Constraints

The number of characters in the sentence < 1200

Sample Input

This is a pen.

Sample Output

a : 1
b : 0
c : 0
d : 0
e : 1
f : 0
g : 0
h : 1
i : 2
j : 0
k : 0
l : 0
m : 0
n : 1
o : 0
p : 1
q : 0
r : 0
s : 2
t : 1
u : 0
v : 0
w : 0
x : 0
y : 0
z : 0


'use strict';
(function(stdin) {
  var lines  = stdin.toString();
  var re = /[a-z]+\n([1-9][0-9]*\n)+/g;
  var result = (function(data) {
    return data
      .map(function(v) {
        return v.slice(1,v[2] + 1)
          .map(Number)
          .reduce(function(str,num) {
            return str.slice(num) + str.slice(0,num);
          },v[0]);
      }).join('\n');

  }(lines.match(re).map(function(v){return v.trim().split('\n');})
  ));
  console.log(result);
}(require('fs').readFileSync('/dev/stdin', 'utf8')));

Shuffle

Your task is to shuffle a deck of n cards, each of which is marked by a alphabetical letter.

A single shuffle action takes out h cards from the bottom of the deck and moves them to the top of the deck.

The deck of cards is represented by a string as follows.

abcdeefab

The first character and the last character correspond to the card located at the bottom of the deck and the card on the top of the deck respectively.

For example, a shuffle with h = 4 to the above deck, moves the first 4 characters "abcd" to the end of the remaining characters "eefab", and generates the following deck:

eefababcd

You can repeat such shuffle operations.

Write a program which reads a deck (a string) and a sequence of h, and prints the final state (a string).

Input

The input consists of multiple datasets. Each dataset is given in the following format:

A string which represents a deck
The number of shuffle m
h1
h2
.
.
hm

The input ends with a single character '-' for the string.

Constraints

The length of the string ≤ 200

1 ≤ m ≤ 100

1 ≤ hi < The length of the string

The number of datasets ≤ 10

Output

For each dataset, print a string which represents the final state in a line.

Sample Input

aabc
3
1
2
1
vwxyz
2
3
4
-

Sample Output

aabc
xyzvw


const input = require('fs').readFileSync('/dev/stdin', 'utf8').split(/\n/);
let time = Number(input[0])
let aCount = 0;
let bCount = 0;
for (let i=1; i<time+1; i++) {
  let [a, b] = input[i].split(/\s/);
  if(a < b) {
      bCount += 3;
    } else if(a > b) {
      aCount += 3;
    } else {
        aCount++;
        bCount++;
    }
}
 console.log(aCount + " " + bCount);

Card Game

Taro and Hanako are playing card games. They have n cards each, and they compete n turns. At each turn Taro and Hanako respectively puts out a card.
The name of the animal consisting of alphabetical letters is written on each card, and the bigger one in lexicographical order becomes the winner of that turn. The winner obtains 3 points. In the case of a draw, they obtain 1 point each.

Write a program which reads a sequence of cards Taro and Hanako have and reports the final scores of the game.

Input

In the first line, the number of cards n is given. In the following n lines, the cards for n turns are given respectively. For each line, the first string represents the Taro's card and the second one represents Hanako's card.

Constraints

n ≤ 1000

The length of the string ≤ 100

Output

Print the final scores of Taro and Hanako respectively. Put a single space character between them.

Sample Input

3
cat dog
fish fish
lion tiger

Sample Output

1 7


var input = '';
var readable = process.stdin;
readable.resume();
readable.setEncoding( 'utf-8' );
readable.on( 'data', function( chunk ) {
  input += chunk;
});

readable.on( 'end', function() {
  var data = input.split( "\n" );
  var word = data[0];
  var q = data[1];
  var output = [];
  for( var i=0; i<q; i++ ) {
    var cmd = data[2+i].split( ' ' );
    var s = parseInt( cmd[1] );
    var e = parseInt( cmd[2] )+1;
    if( "print" == cmd[0] ) {
      output.push( word.substring( s, e ) );
    } else if( "reverse" == cmd[0] ) {
      var br = word.substring( s, e );
      word = word.substring( 0, s )+br.split( '' ).reverse().join( '' )+word.substring( e );
    } else if( "replace" == cmd[0] ) {
      word = word.substring( 0, s )+cmd[3]+word.substring( e );
    }
  }
  console.log( output.join( '\n' ) );
});

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Transformation

Write a program which performs a sequence of commands to a given string $str$. The command is one of:

print a b: print from the a-th character to the b-th character of $str$

reverse a b: reverse from the a-th character to the b-th character of $str$

replace a b p: replace from the a-th character to the b-th character of $str$ with p

Note that the indices of $str$ start with 0.

Input

In the first line, a string $str$ is given. $str$ consists of lowercase letters. In the second line, the number of commands q is given. In the next q lines, each command is given in the above mentioned format.

Output

For each print command, print a string in a line.

Constraints

$1 \leq $ length of $str \leq 1000$

$1 \leq q \leq 100$

$0 \leq a \leq b < $ length of $str$

for replace command, $b - a + 1 = $ length of $p$

Sample Input 1

abcde
3
replace 1 3 xyz
reverse 0 2
print 1 4

Sample Output 1

xaze

Sample Input 2

xyz
3
print 0 2
replace 0 2 abc
print 0 2

Sample Output 2

xyz
abc


var input = require('fs').readFileSync('/dev/stdin', 'utf8').trim();
var n = +input;

process.stdout.write(n + ': ');

var primes = [];

for (var i = 1; n > 1; i++) {
    var low = i * 6 - 1;
    var high = i * 6 + 1;
    while (n % low == 0) {
        primes.push(low);
        n /= low;
    }
    while (n % high == 0) {
        primes.push(high);
        n /= high;
    }
}

console.log(primes.join(' '));

Prime Factorization

Factorize a given integer n.

Input

n

An integer n is given in a line.

Output

Print the given integer n and :. Then, print prime factors in ascending order. If n is divisible by a prime factor several times, the prime factor should be printed according to the number of times. Print a space before each prime factor.

Constraints

2 ≤ n ≤ 109

Sample Input 1

12

Sample Output 1

12: 2 2 3

Sample Input 2

126

Sample Output 2

126: 2 3 3 7


var input = require('fs').readFileSync('/dev/stdin', 'utf8').trim();
//var input = 1463616;
var n = parseInt(input);
var on = n;

var primes = [];
while (n % 2 == 0) {
    primes.push(2);
    n = n / 2;
}
for (var i = 3; i * i <= n * n; i += 2) {
    while (n % i == 0) {
        primes.push(i);
        n /= i;
    }
}
if (n > 1) primes.push(n);

console.log(on + ': ' + primes.join(' '));


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

var lines = [];
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
reader.on('line', (line) => {
  lines.push(line);
});
reader.on('close', () => {
const n = Number(lines[0]);
const str = "ACL";
console.log(str.repeat(n));
});

Score : 100 points

Problem Statement

You are given an integer K.
Print the string obtained by repeating the string ACL K times and concatenating them.

For example, if K = 3, print ACLACLACL.

Constraints

1 \leq K \leq 5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the string obtained by repeating the string ACL K times and concatenating them.

Sample Input 1

3

Sample Output 1

ACLACLACL


// parameter "input" gets all data
function Main(input) {
	// the first line is assigned to input[0], the second line is assigned to input[1] similarly.
	input = input.split("\n");
	tmp = input[1].split(" ");
  	if(tmp.endsWith("s"){
    	console.log(tmp+"es");
    } else {
    	console.log(tmp+"s");
    }
}
// Don't edit this line!
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.

In Taknese, the plural form of a noun is spelled based on the following rules:

If a noun's singular form does not end with s, append s to the end of the singular form.

If a noun's singular form ends with s, append es to the end of the singular form.

You are given the singular form S of a Taknese noun. Output its plural form.

Constraints

S is a string of length 1 between 1000, inclusive.

S contains only lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the plural form of the given Taknese word.

Sample Input 1

apple

Sample Output 1

apples

apple ends with e, so its plural form is apples.

Sample Input 2

bus

Sample Output 2

buses

bus ends with s, so its plural form is buses.

Sample Input 3

box

Sample Output 3

boxs


function Main(input) {
    input = input.trim().split("\n").map(function(x) { return x.split(" ")});
    let N = parseInt(input[0][0], 10);
    let arr_D = [];
    for (let i = 0; i < N; i++){
        arr_D.push(input[i + 1].map(e => parseInt(e, 10)));
    }
    arr_D.push([0, 1]);
    let tmp = -1;
    let tmp2;
    let ans = 'No';
    for (let i = 0; i < N + 1; i++){
        if (arr_D[i][0] !== arr_D[i][1]){
            tmp2 = i;
            if (tmp2 - tmp > 3){
                ans = 'Yes';
                break;
            } else {
                tmp = tmp2;
            }
        }
    }
    console.log(ans);

}

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

Score : 200 points

Problem Statement

Tak performed the following action N times: rolling two dice.
The result of the i-th roll is D_{i,1} and D_{i,2}.

Check if doublets occurred at least three times in a row.
Specifically, check if there exists at lease one i such that D_{i,1}=D_{i,2}, D_{i+1,1}=D_{i+1,2} and D_{i+2,1}=D_{i+2,2} hold.

Constraints

3 \leq N \leq 100

1\leq D_{i,j} \leq 6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
D_{1,1} D_{1,2}
\vdots
D_{N,1} D_{N,2}

Output

Print Yes if doublets occurred at least three times in a row. Print No otherwise.

Sample Input 1

5
1 2
6 6
4 4
3 3
3 2

Sample Output 1

Yes

From the second roll to the fourth roll, three doublets occurred in a row.

Sample Input 2

5
1 1
2 2
3 4
5 5
6 6

Sample Output 2

No

Sample Input 3

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

Sample Output 3

Yes


const main = (input) => {
  const [, ...arr] = input.trim().split('\n')
  let count = 0

  for (let i=0; i<arr.length; i++) {
    const [a, b] = arr[i].split(' ').map(Number)

    if (a !== b) count = 0

    if (a === b) {
      count++
      if (count === 3) return console.log('Yes')
    }
  }
  return console.log('No')
}

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


function MainC(input){
    const N = Number(input);
    let answer = 0;
    for(let A=1; A<N; A++){
        for(let B=1; B<N/A; B++){
            answer++;
        }
    }
    console.log(answer);
}
MainC(require("fs").readFileSync("/dev/stdin", "utf8").trim());

Score : 300 points

Problem Statement

Given is a positive integer N.
How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?

Constraints

2 \leq N \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

3

Sample Output 1

3

There are 3 tuples of integers that satisfy A \times B + C = 3: (A, B, C) = (1, 1, 2), (1, 2, 1), (2, 1, 1).

Sample Input 2

100

Sample Output 2

473

Sample Input 3

1000000

Sample Output 3

13969985


"use strict"

const main = arg => {
  const input = arg.trim().split("\n");
  const N = parseInt(input[0].split(" ")[0]);
  if (N=0){
    console.log("1");
  }else{
    console.log("0");
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

Given is an integer x that is greater than or equal to 0, and less than or equal to 1.
Output 1 if x is equal to 0, or 0 if x is equal to 1.

Constraints

0 \leq x \leq 1

x is an integer

Input

Input is given from Standard Input in the following format:

x

Output

Print 1 if x is equal to 0, or 0 if x is equal to 1.

Sample Input 1

1

Sample Output 1

0

Sample Input 2

0

Sample Output 2

1


const Main = (input) => {
  const[A,B,C,D] = input.split(' ').map(Number);
  const numbers = [A * C, A * D, B * C, C * D];

  console.log(Math.max.apply(null, numbers));
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
// Main(`-1000000000 0 -1000000000 0`);

Score : 200 points

Problem Statement

Given are integers a,b,c and d.
If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y?

Constraints

-10^9 \leq a \leq b \leq 10^9

-10^9 \leq c \leq d \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

Print the answer.

Sample Input 1

1 2 1 1

Sample Output 1

2

If x = 1 and y = 1 then x \times y = 1.
If x = 2 and y = 1 then x \times y = 2.
Therefore, the answer is 2.

Sample Input 2

3 5 -4 -2

Sample Output 2

-6

The answer can be negative.

Sample Input 3

-1000000000 0 -1000000000 0

Sample Output 3

1000000000000000000


const main = arg => {
  const [a, b, c, d] = arg.split(' ').map(BigInt);
  const ary = [a * c, a * d, b * c, b * d];
  const max = ary.reduce((x, y) => x > y ? x : y);
  console.log(max.toString());
};
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


var Main  = function(input){
    const [a, b, c, d] = input.trim().split(' ').map(x => BigInt(x));
    var array=[];

    array.push(a*c,a*d,b*c,b*d);
    array.sort((a,b)=>(a>b)? -1: (a<b)? 1: 0);
    // Bigintのソート

    console.log(array[0].toString(10));
};

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


var Main  = function(input){
    var nums=input.split(" ").map((n)=>parseInt(n,10));
    var a = nums[0];
    var b = nums[1];
    var c = nums[2];
    var d = nums[3];

    var array=[];

    array.push(a*c,a*d,b*c,b*d);
    array.sort(function (x,y){return y-x;});

    console.log(array[0]+0);
};

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


"use strict"

function Main(input) {
  let lines = input.split('\n');
  const [a, b, c, d] = lines[0].split(' ').map(BigInt);

  let product_matrix = [];
  product_matrix.push(a * c);
  product_matrix.push(a * d);
  product_matrix.push(b * c);
  product_matrix.push(b * d);
  const max = product_matrix.reduce((a,b)=>a>b?a:b)

  console.log(max.toString());
}

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


function Main(input) {

	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");

    let [a,b,c,d] = input[0].split(" ").map(BigInt);

    let ac = a * c;
    let ad = a * d;
    let bc = b * c;
    let bd = b * d;

    let max = [ac,ad,bc,bd].sort()[3];

    if (max < 0) {
        if ((a < 0 && b > 0) || (a > 0 && b < 0)) max = 0;
        if ((c < 0 && d > 0) || (c > 0 && d < 0)) max = 0;
    }

    console.log(max.toString());

}

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


function Main(input){
    let s = (input.split("\n")[0]).split("");
    let t = (input.split("\n")[1]).split("");
    let ans = t.length;
    let diff = 0;
    for(let a = 0; a < s.length - t.length; a++){

        for(let b = 0; b < t.length; b++){
            if(t[b] != s[a+b]){
                diff++;
            }
        }
        ans = Math.min(diff, ans);
    }
    console.log(ans);
}
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.


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

const lines = input.split('\n')
let [D, T, S] = lines[0].split(' ').map(Number)

const ans = D <= T * S ? 'Yes' : 'No'
console.log(ans)


function Main(input) {
	input = input.trim().split("\n").map(function(x) { return x.split(" ")});
	let D = parseInt(input[0][0], 10);
	let T = parseInt(input[0][1], 10);
	let S = parseInt(input[0][2], 10);
	if (D / S <= T) console.log('Yes');
	else console.log('No');

}

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


    function Main(input){
        let s = (input.split("\n")[0]).split("");
        let t = (input.split("\n")[1]).split("");
        let num = 0;
        for(let i = 0; i <= s.length - t.length; i++){
            for(let a = 0; a < t.length; a++){
                if(t[a] != s[i+a]){
                    num++;
                }
            }
        }

        num = num <= t.length? num : t.length;
        console.log(num);

    }
    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 processData = (lines) => {
    const S = lines[0]
    const T = lines[1]
    let min = T.length
    for (let i=0; i<S.length-T.length+1; i++) {
        let changes = T.length;
        for (let j=0; j<T.length; j++) {
            if (S[i+j] === T[j]) {
                changes--
            }
        }
        min = Math.min(min, changes)
    }

    console.log(min)
}

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


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

	var result = t.length;
	for (var i = 0; i < s.length - t.length;i++) {
		var current = 0;
		for (var j = 0; j < t.length; j++) {
			const a = s.substr(i + j, 1);
			const b = t.substr(j, 1);

			// console.log({
			// 	i: i,
			// 	j: j,
			// 	a: a,
			// 	b: b,
			// 	current: current,
			// 	result: result
			// });

			if (a !== b) {
				current += 1;
			}
		}
		if (current < result) {
			result = current;
		}
	}

	console.log(result);
	// 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)


let input = require('fs').readFileSync('/dev/stdin', 'utf8')
// let input = require('fs').readFileSync('./sample_d.txt', 'utf8')
.split(/\n| /)
.slice(0 ,-1)
.map(item => parseInt(item))

const [N, M, ..._pair] = input

let r = new Array(N).fill(-1)

const root = x => {
    if (r[x] < 0) return x
    return r[x] = root(r[x])
}

const unite = (x, y) => {
    x = root(x)
    y = root(y)
    if (x == y) return false
    if (r[x] > r[y]) [x, y] = [y, x]
    r[x] += r[y]
    r[y] = x
    return true
}

const size = x => {
    return -r[root(x)]
}

for (let i=0; i<_pair.length; i+=2){
    unite(_pair[i]-1, _pair[i+1]-1)
}

//最大の友達集合を求める
let ans = 0
for ( let i=0; i<N; i++){
    ans = Math.max(ans, size(i));
}

console.log(ans)

// const [N, M, ..._pair] = input
// const pair = []
// for(let i=0; i<N; i++){
//     pair.push(new Array(N-i).fill(true))
// }

// for(let i=0; i<_pair.length; i+=2){
//     const a = [_pair[i], _pair[i+1]].sort()
//     pair[a[0]-1][a[1]-a[0]] = false
// }

// const member = [ new Set() ]

// pair[0].forEach( (item, index) => {
//     if(item) member[0].add(index+1)
//     else{
//         member.push(new Set())
//         member[member.length-1].add(index+1)
//     }
// } )

// for( let i=1; i<N; i++){
//     for( let j=1; j<pair[i].length; j++){
//         if(!pair[i][j]){
//             member.forEach( (sample, index) => {
//                 if( sample.has(i+1) && sample.has(i+j+1) ){
//                     sample.delete(i+j)
//                     if(member.length - 1 <= index) member.push(new Set())
//                     member[index+1].add(i+j)
//                 }
//             })
//         }
//     }
// }

// console.log(member.length)

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


const input = require("fs").readFileSync("/dev/stdin", "utf8")
const lines = input.split('\n')
let [N, M] = lines[0].split(' ').map(Number)

const A = []
const B = []
for (let i = 0; i < M; i++) {
    const l = lines[i + 1].split(' ').map(Number)
    A[i] = l[0]
    B[i] = l[1]
}

const g = {}
for (let i = 0; i < M; i++) {
    const l = [A[i], B[i]]
    if (!g[A[i]] && !g[B[i]]) {
        g[A[i]] = l
        g[B[i]] = l
    } else if (g[A[i]] && g[B[i]]) {
        if (g[A[i]] !== g[B[i]]) {
            if (g[A[i]].length < g[B[i]].length) {
                g[A[i]].forEach(n => {
                    g[B[i]].push(n)
                    g[n] = g[B[i]]
                })
            } else {
                g[B[i]].forEach(n => {
                    g[A[i]].push(n)
                    g[n] = g[A[i]]
                })
            }
        }
    } else if (g[A[i]]) {
        if (!g[B[i]]) {
            g[B[i]] = g[A[i]]
        }
        g[B[i]].push(B[i])
    } else if (g[B[i]]) {
        if (!g[A[i]]) {
            g[A[i]] = g[B[i]]
        }
        g[A[i]].push(A[i])
    }
}

let ans = 0
for (let key in g) {
    ans = Math.max(ans, g[key].length)
}
console.log(ans)


// inputに入力データ全体が入る
function Main(input) {
	input = input.split(" ");
	var n = parseInt(input[0]);//作りたい数
	var x = parseInt(input[1]);//一回で作れる最大数
	var t = parseInt(input[2]);//一回にかかる時間
	//出力　作りたい数を作れる時間
	console.log(Math.ceil(n/x)*t);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、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) {
	input = input.split("");
  	let result = 0;
  	for(let i =0; i< input.length ; i++){
    	result += parseInt(i, 10);
    }
  	if(result % 9 === 0 ){
      console.log('Yes')
    }else{
      console.log('No')
    }
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

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


// inputに入力データ全体が入る
function Main(input) {
	input = input.split("");
  	let result = 0;
  	for(let i of input){
    	result += parseInt(i);
    }
  	if(result % 9 === 0 ){
      console.log('Yes')
    }else{
      console.log('No')
    }
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
    input = parseInt(input);
    n = input.toString(10).replace(/\D/g, '0').split('').map(Number);

    total = 0;

    for (let i = 0; i < n.length; i++) {
        num = n[i];
        total += num;
    }

    if (total % 9 === 0) {

        console.log("Yes");

    } else if(total % 9 != 0){
        console.log("No");
    }

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


function main(lines) {
  const [H, W] = na();
  const [Ch, Cw] = na();
  const [Dh, Dw] = na();
  const maze = lines.slice(3).map(l => l.split(''));

  let points = new Set([`${Ch-1} ${Cw-1}`]);
  let warpCount = 0;
  let arrived, ans = -1;
  while (points.size) {
    arrived = search(maze, points, Dh-1, Dw-1);
    if (arrived) {
      ans = warpCount;
      break;
    }
    warpCount++;
    points = warp(maze, points);
  }

  return ans;
}

function search(graph, points, dh, dw) {
  for (const pStr of points) {
    const [h, w] = pStr.split(' ').map(Number);
    if (graph[h][w] != '.') continue;
    const queue = [[h, w]];
    while (queue.length) {
      let [h, w] = queue.shift();
      if (h == dh && w == dw) return true;
      graph[h][w] = true;
      points.add(`${h} ${w}`);
      if (graph[h-1] && graph[h-1][w] == '.') queue.push([h-1, w]);
      if (graph[h+1] && graph[h+1][w] == '.') queue.push([h+1, w]);
      if (graph[h][w-1] == '.') queue.push([h, w-1]);
      if (graph[h][w+1] == '.') queue.push([h, w+1]);
    }
  }
}

function warp(graph, fromPoints) {
  const points = new Set();
  for (const pStr of fromPoints) {
    const [h, w] = pStr.split(' ').map(Number);
    for (let _h = h-2; _h <= h+2; _h++) {
      for (let _w = w-2; _w <= w+2; _w++) {
        if (graph[_h] && graph[_h][_w] == '.') points.add(`${_h} ${_w}`);
      }
    }
  }
  return points;
}

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


function Main(input) {
  input=input.split("\n");
  const H=input[0].split(' ')[0]-0;
  const W=input[0].split(' ')[1]-0;
  const CH=input[1].split(' ')[0]-0;
  const CW=input[1].split(' ')[1]-0;
  const DH=input[2].split(' ')[0]-0;
  const DW=input[2].split(' ')[1]-0;
  var map=[];
  map=new Array(H+1);
  map[0]=new Array(W+1);
  map[0].fill(false);
  for(var i=1;i<=H;i++){
    map[i]=[false].concat(input[i+2].split('').map(e=>{
      return e==='.'?Infinity:false;
    }));
  }
  //console.log(map);
  var answer=map.concat([]);
  var newRoad=[[CH,CW]];
  answer[CH][CW]=0;
  var next=[];
  do{
    next=[];
    newRoad.forEach(e=>{
      [-1,0,1].forEach(a=>{
        [-1,0,1].forEach(b=>{
          if(0<e[0]+a&&e[0]+a<=H&&0<e[1]+b&&e[1]+b<=W&&answer[e[0]+a][e[1]+b]!==false&&Math.abs(a)+Math.abs(b)===1){
            if(answer[e[0]][e[1]]<answer[e[0]+a][e[1]+b]){
              next.push([e[0]+a,e[1]+b]);
              answer[e[0]+a][e[1]+b]=answer[e[0]][e[1]];
            }
          }
        });
      });
      [-2,-1,0,1,2].forEach(a=>{
        [-2,-1,0,1,2].forEach(b=>{
          if(0<e[0]+a&&e[0]+a<=H&&0<e[1]+b&&e[1]+b<=W&&answer[e[0]+a][e[1]+b]!==false){
            if(answer[e[0]][e[1]]+1<answer[e[0]+a][e[1]+b]){
              next.push([e[0]+a,e[1]+b]);
              answer[e[0]+a][e[1]+b]=answer[e[0]][e[1]]+1;
            }
          }
        });
      });

    });
    newRoad=next.concat([]);
  }while(newRoad.length>0);
  console.log(answer[DH][DW]===Infinity?-1:answer[DH][DW]);

}

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


"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
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);
  var q = [];
  dp[a[0]-1][a[1]-1] = 0;
  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);
    }
  }
  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