class _Node {
  constructor(key, parent = null, left = null, right = null) {
    this.key = key;
    this.parent = parent;
    this.left = left;
    this.right = right;
  }

  getChildrenNumber() {return Number(this.left !== null) + Number(this.right !== null);}

  isLeftChild() {
    if (this.parent === null) return null;
    return this.parent.left === this;
  }

  getLeftOrRight() {return this.isLeftChild() ? 'left' : 'right';}

  getSuccessor() {
    let n;
    if (this.right !== null) {
      n = this.right;
      while (n.left !== null) n = n.left;
    } else {
      n = this.parent;
      while (!n.isLeftChild && n.parent != null) n = n.parent;
    }
    return n;
  }
}

class BinaryTree {
  constructor() {
    this.root = null;
  }

  static get Node() { return _Node; }

  // insert(key) {
  //   if (this.root === null) {
  //     this.root = new BinaryTree.Node(key);
  //     return;
  //   }
  //   let x = this.root, y;
  //   let newNode = new BinaryTree.Node(key);
  //   while (x !== null) {
  //     y = x;
  //     x = x[key < x.key ? 'left' : 'right'];
  //   }
  //   newNode.parent = y;
  //   y[key < y.key ? 'left' : 'right'] = newNode;
  // }
    insert(key) {
      this.root = new BinaryTree.Node(key);
      this.insert = (key) => {
        let x = this.root, y;
        let newNode = new BinaryTree.Node(key);
        while (x !== null) {
          y = x;
          x = x[key < x.key ? 'left' : 'right'];
        }
        newNode.parent = y;
        y[key < y.key ? 'left' : 'right'] = newNode;
      }
    }

  find(key, n = this.root) {
    if (n === null || n.key === key) return n;
    return this.find(key, n[key < n.key ? 'left' : 'right']);
  }

  delete(key) {
    const n = this.find(key);
    if (n === null) return;
    let leftOrRight = n.getLeftOrRight();
    switch (n.getChildrenNumber()) {
    case 0:
      n.parent[leftOrRight] = null;
      break;
    case 1:
      n.parent[leftOrRight] = n.left || n.right;
      n.parent[leftOrRight].parent = n.parent;
      break;
    default:
      let skey = n.getSuccessor().key;
      this.delete(skey);
      n.key = skey;
    }
  }

  printByIneorder() {
    let str = '';
    const innerFunc = (n) => {
      if (n === null) return;
      innerFunc(n.left);
      str += ` ${n.key}`;
      innerFunc(n.right);
    }
    innerFunc(this.root);
    console.log(str);
  }

  printByPreorder() {
    let str = '';
    const innerFunc = (n) => {
      if (n === null) return;
      str += ` ${n.key}`;
      innerFunc(n.left);
      innerFunc(n.right);
    }
    innerFunc(this.root);
    console.log(str);
  }

  print() {
    this.printByIneorder();
    this.printByPreorder();
  }
}

(function main(){
  const lines = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n');
  const n = Number(lines.shift());

  const tree = new BinaryTree();
  lines.forEach(function(cmd) {
    switch (cmd.charAt(0)) {
    case 'i': tree.insert(Number(cmd.split(' ')[1])); break;
    case 'f': console.log(tree.find(Number(cmd.split(' ')[1])) ? 'yes' : 'no'); break;
    case 'd': tree.delete(Number(cmd.split(' ')[1])); break;
    default: tree.print();
    }
  });
})();

Binary Search Tree III

Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II.

insert $k$: Insert a node containing $k$ as key into $T$.

find $k$: Report whether $T$ has a node containing $k$.

delete $k$: Delete a node containing $k$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases:

If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$).

If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent.

If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given.

Output

For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not.

In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

18
insert 8
insert 2
insert 3
insert 7
insert 22
insert 1
find 1
find 2
find 3
find 4
find 5
find 6
find 7
find 8
print
delete 3
delete 7
print

Sample Output 1

yes
yes
yes
no
no
no
yes
yes
1 2 3 7 8 22
8 2 1 3 7 22
1 2 8 22
8 2 1 22

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());
  lines.shift().split(' ').map(Number).forEach(function(key, i, a) {
    console.log(`node ${i+1}: key = ${a[i]}, `+(i?`parent key = ${a[Math.floor((i-1)/2)]}, `:'')+(2*i+1<a.length?`left key = ${a[2*i+1]}, `:'')+(2*i+2<a.length?`right key = ${a[2*i+2]}, `:''));
  });
})();

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

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.

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');
  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;
  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(arr.length / 2); i >= 0; i--) maxHeapify(i);
}

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.


(function main(){
  const lines = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n');
  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;
  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];
    //   [arr[i], arr[largest]] = [arr[largest], arr[i]];
      maxHeapify(largest);
    }
  };

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


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

function buildMaxHeap(arr) {
  const n = arr.length;
  const maxHeapify = (i) => {
    let left, right, largest;
    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);
  return arr;
}


(function main(){
  const lines = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n');
  const n = Number(lines.shift());
  const arr = lines.shift().split(' ');
  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 && Number(arr[left]) > Number(arr[i])) largest = left;
    else largest = i;
    if (right < n && Number(arr[right]) > Number(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 - 1); i >= 0; i--) maxHeapify(i);
}


(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;
  const maxHeapify = (i) => {
    let left, right, largest = i;
    left = 2 * i + 1;
    right = 2 * i + 2;
    if (left < n && Number(arr[left]) > Number(arr[i])) largest = left;
    if (right < n && Number(arr[right]) > Number(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 - 1); 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 insert = (arr, n) => {
    arr.push(n);
    const helper = (i) => {
        if (i <= 1) return;
        const parentIndex = Math.floor(i/2);
        if (arr[i-1] > arr[parentIndex-1]) {
            const tmp = arr[i-1];
            arr[i-1] = arr[parentIndex-1];
            arr[parentIndex-1] = tmp;
            helper(parentIndex);
        }
    };
    helper(arr.length);
};

const extract = arr => {
    const n = arr.shift();
    arr.unshift(arr.pop());
    maxHeapify(arr, 1);
    return n;
};

const data = line.reduce((acc, x) => {
    const cmd = x.split(' ');
    switch(cmd[0]) {
        case 'insert':
            insert(acc, Number(cmd[1]));
            break;
        case 'extract':
            console.log(extract(acc));
            break;
    }
    return acc;
}, []);

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

Priority Queue

A priority queue is a data structure which maintains a set $S$ of elements, each of with an associated value (key), and supports the following operations:

$insert(S, k)$: insert an element $k$ into the set $S$

$extractMax(S)$: remove and return the element of $S$ with the largest key

Write a program which performs the $insert(S, k)$ and $extractMax(S)$ operations to a priority queue $S$.
The priority queue manages a set of integers, which are also keys for the priority.

Input

Multiple operations to the priority queue $S$ are given. Each operation is given by "insert $k$", "extract" or "end" in a line. Here, $k$ represents an integer element to be inserted to the priority queue.

The input ends with "end" operation.

Output

For each "extract" operation, print the element extracted from the priority queue $S$ in a line.

Constraints

The number of operations $\leq 2,000,000$

$0 \leq k \leq 2,000,000,000$

Sample Input 1

insert 8
insert 2
extract
insert 10
extract
insert 11
extract
extract
end

Sample Output 1

8
10
11
2


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

const list = input.trim().split('\n');
const [ n, m ]= list[0].split(' ');
const cm = list[1].trim().split(' ');

const genKey = (...args) => {
  const key = args.join(':');
  return key;
}

const dp = new Map();
const memo = (count, target) => {
  const key = genKey(count, target);
  let result = 0;
  if (dp.has(key)) {
    result = dp.get(key);
  } else if (target !== 0) {
    // 制約(1 ≤ n ≤ 50,000)よりベタ書きの初期化
    const nextCount = count + 1;
    let min = 50000;
    for (let i = 0; i < Number(m); i++) {
      const nextTarget = target - Number(cm[i]);
      if (nextTarget < 0) {
        continue;
      }
      const result = memo(nextCount, nextTarget);
      dp.set(genKey(nextCount, nextTarget), result);
      min = Math.min(min, result);
    }
    result = min + 1;
  }

  // 末尾再起
  return result;
}

console.log(memo(0, Number(n)));

// const CALL_STACK_SIZE_LIMIT = 3000;
// let callStackSize = 0;

// const dp = new Map();
// const memo = async (count, target) => {
//   if (++callStackSize > CALL_STACK_SIZE_LIMIT) {
//     console.log('call nextTick:', count);
//     await nextTick();
//     callStackSize = 0;
//   }
//   const key = genKey(count, target);
//   if (dp.has(key)) {
//     return dp.get(key);
//   } else if (target === 0) {
//     return 0;
//   }

//   // 制約(1 ≤ n ≤ 50,000)よりベタ書きの初期化
//   const nextCount = count + 1;
//   let min = 50000;
//   for (let i = 0; i < Number(m); i++) {
//     const nextTarget = target - Number(cm[i]);
//     if (nextTarget < 0) {
//       continue;
//     }
//     const result = await memo(nextCount, nextTarget);
//     dp.set(genKey(nextCount, nextTarget), result);
//     min = Math.min(min, result);
//   }

//   return min + 1;
// }

// (async () => {
//   console.log(await memo(0, Number(n)));
// })()

Coin Changing Problem

Find the minimum number of coins to make change for n cents using coins of denominations d1, d2,.., dm. The coins can be used any number of times.

Input

n m
d1 d2 ... dm

Two integers n and m are given in the first line. The available denominations are given in the second line.

Output

Print the minimum number of coins in a line.

Constraints

1 ≤ n ≤ 50000

1 ≤ m ≤ 20

1 ≤ denomination ≤ 10000

The denominations are all different and contain 1.

Sample Input 1

55 4
1 5 10 50

Sample Output 1

2

Sample Input 2

15 6
1 2 7 8 12 50

Sample Output 2

2

Sample Input 3

65 6
1 2 7 8 12 50

Sample Output 3

3


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

const list = input.trim().split('\n');
let [ n, m ] = list[0].split(' ');
n = Number(n);
m = Number(m);
let cm = list[1].trim().split(' ');
cm = cm.map(c => Number(c));

const dp = new Map();
dp.set(n, 0);
const memo = (count, yen) => {
  let nextCount;
  let nextYen = yen - 1;
  let result;
  if (!dp.has(yen)) {
    nextCount = count;
  } else {
    const min = Math.min(dp.get(yen), count);
    dp.set(yen, min);
    if (yen === 0) {
      result = dp.get(yen);
    } else {
      nextMin = min + 1;
      for (let i = 0; i < m; i++) {
        const afterYen = yen - cm[i];
        if (afterYen < 0) {
          continue;
        } else if (dp.has(afterYen)) {
          dp.set(afterYen, Math.min(dp.get(afterYen), nextMin));
        } else {
          dp.set(afterYen, nextMin);
        }
      }
    }
  }

  return result || memo(nextMin, nextYen);
}

console.log(memo(1, n));


function Main(input) {
    input = input.trim().split("\n").map(function(x) { return x.split(" ")});

    const lowerBound = (arr, n) => {
        let first = 0, last = arr.length - 1, middle;
        while (first <= last) {
            middle = Math.floor((first + last) / 2);
            if (arr[middle] < n) first = middle + 1;
            else last = middle - 1;
        }
        return first;
    }

    let n = parseInt(input[0][0], 10);
    let v_a = [];
    for (let i = 0; i < n; i++){
        v_a.push(parseInt(input[i + 1][0], 10));
    }
    let dp = Array.from({length: n}, () => Infinity);

    dp[0] = v_a[0];
    let index;
    for (let i = 1; i < n; i++){
        index = lowerBound(dp, v_a[i]);
        dp[index] = v_a[i];
    }

    console.log(lowerBound(dp,1e9+1));

}

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

Longest Increasing Subsequence

For a given sequence A = {a0, a1, ... , an-1}, find the length of the longest increasing subsequnece (LIS) in A.

An increasing subsequence of A is defined by a subsequence {ai0, ai1, ... , aik} where 0 ≤ i0 < i1 < ... < ik < n and ai0 < ai1 < ... < aik.

Input

n
a0
a1
:
an-1

In the first line, an integer n is given. In the next n lines, elements of A are given.

Output

The length of the longest increasing subsequence of A.

Constraints

1 ≤ n ≤ 100000

0 ≤ ai ≤ 109

Sample Input 1

5
5
1
3
2
4

Sample Output 1

3

Sample Input 2

3
1
1
1

Sample Output 2

1


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 main(lines){
	if(lines.pop() != ""){
		lines.push();
	}
	lines = lines.map(function(line){
		return line.split(" ").map(function(e){
			return Number(e);
		});
	});
	var top_line = lines.shift();
	var V = top_line[0];
	var E = top_line[1];
	var real_edge = [];
	var virt_edge = [];
	var mark = [];
	var status = [];
	var ord = [];
	var lowlink = [];
	var bridges = [];
	for(var i = 0; i < V ; i++){
		real_edge[i] = [];
		mark[i] = false;
		//ord?????????
		//lowlink??????(dfs????????????????§????){0,}??¨(?????????){0,1}??§?????????ord???????°????
		//?????????????????????????????§???????°???????ord
		ord[i] = 0;
		lowlink[i] = V;
		bridges[i] = [];
	}
	lines.forEach(function(edge){
		var a = edge[0];
		var b = edge[1];
		real_edge[a].push(b);
		real_edge[b].push(a);
	});
	var no = 0;
	var prev = 0;
	function dfs(now_point,prev){
		//now_point????????¨???????????????
		//now_ord????????¨???????????????
		//mark????¨???????????????????
		var np = now_point;
		var mk = mark;
		var targets = real_edge[np];
		mk[np] = true;
		ord[np] = no;
		lowlink[np] = no;
		no++;
		targets.forEach(function(target){
			if(target == prev){
				//??´???????????????????????????????????§
				return;
			}
			if(mk[target]){
				//?????????
				//lowlink?????´??°
				//????°????????????????
				lowlink[np] = Math.min(lowlink[np],target);
			}else{
				//???????????£????????¨?????????
				//??¢?´¢?????????
				dfs(target,np);
				//?????\????????????lowlink?????????
				//???????????????????±????lowlink???????°???????lowlink????????¨??????
				lowlink[np] = Math.min(lowlink[np],lowlink[target]);
			}
		});
	}
	dfs(0,V);
	lines.forEach(function(edge){
		var u = edge[0];
		var v = edge[1];
		if(ord[u] > ord[v]){
			var k = u;
			u = v;
			v = k;
		}
		if(ord[u] < lowlink[v]){
			//????????????
			var min = Math.min(u,v);
			var max = Math.max(u,v);
			bridges[min].push(max);
		}
	});
	bridges = bridges.map(function(e){
		return e.sort();
	});
	for(var s = 0 ; s < V ; s++){
		var len = bridges[s].length;
		for(var td = 0 ; td < len ;td++){
			var t = bridges[s][td];
			log(s+" "+t);
		}
	}
}

Bridges

Find bridges of an undirected graph G(V, E).

A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.

Input

|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1

, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.

si and ti represent source and target nodes of i-th edge (undirected).

Output

A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.

Constraints

1 ≤ |V| ≤ 100,000

0 ≤ |E| ≤ 100,000

The graph is connected

There are no parallel edges

There are no self-loops

Sample Input 1

4 4
0 1
0 2
1 2
2 3

Sample Output 1

2 3

Sample Input 2

5 4
0 1
1 2
2 3
3 4

Sample Output 2

0 1
1 2
2 3
3 4


"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 f = lines[0].trim().split(' ').map(Number);
    console.log(aux(f[0],f[1],f[2],f[3]));
});

function aux(x0,y0,x1,y1)
{
    return Math.sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0));
}

Distance

Write a program which calculates the distance between two points P1(x1, y1) and P2(x2, y2).

Input

Four real numbers x1, y1, x2 and y2 are given in a line.

Output

Print the distance in real number. The output should not contain an absolute error greater than 10-4.

Sample Input

0 0 1 1

Sample Output

1.41421356


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 origin_dice = new Dice(input[0].split(' ').map(Number));
  var target_dice = new Dice(input[1].split(' ').map(Number));
  var result = 'No'

  for (var i = 0; i < 8; i++) {
    for (var j = 0; j < 4; j++) {
      target_dice.turn('R');
      if (origin_dice.top    == target_dice.top    &&
          origin_dice.front  == target_dice.front  &&
          origin_dice.right  == target_dice.right  &&
          origin_dice.left   == target_dice.left   &&
          origin_dice.back   == target_dice.back   &&
          origin_dice.bottom == target_dice.bottom) {
        result = 'Yes'
      }
    }
    if (i < 4) {
      target_dice.roll('N');
    } else {
      target_dice.roll('W');
    }
  }
  console.log(result);
});

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

Dice III

Write a program which reads the two dices constructed in the same way as Dice I, and determines whether these two dices are identical. You can roll a dice in the same way as Dice I, and if all integers observed from the six directions are the same as that of another dice, these dices can be considered as identical.

Input

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

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

Output

Print "Yes" if two dices are identical, otherwise "No" in a line.

Constraints

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

Sample Input 1

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

Sample Output 1

Yes

Sample Input 2

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

Sample Output 2

No


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 n = Number(input[0]);
  var origin_dice = new Dice(input[1].split(' ').map(Number));
  var result = 'Yes'

  for (i = 2; i < 1 + n; i++) {
    var target_dice = new Dice(input[i].split(' ').map(Number));
    for (j = 0; j < 8; j++) {
      for (k = 0; k < 4; k++) {
        if (origin_dice.top    == target_dice.top    &&
            origin_dice.front  == target_dice.front  &&
            origin_dice.right  == target_dice.right  &&
            origin_dice.left   == target_dice.left   &&
            origin_dice.back   == target_dice.back   &&
            origin_dice.bottom == target_dice.bottom) {
          result = 'No';
        }
        target_dice.turn('R');
      }
      if (j < 4) {
        target_dice.roll('N');
      } else {
        target_dice.roll('W');
      }
    }
  }
  console.log(result);
});

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

Dice IV

Write a program which reads $n$ dices constructed in the same way as Dice I, and determines whether they are all different. For the determination, use the same way as Dice III.

Input

In the first line, the number of dices $n$ is given. In the following $n$ lines, six integers assigned to the dice faces are given respectively in the same way as Dice III.

Output

Print "Yes" if given dices are all different, otherwise "No" in a line.

Constraints

$2 \leq n \leq 100$

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

Sample Input 1

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

Sample Output 1

No

Sample Input 2

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

Sample Output 2

Yes


process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk)
{
	var x = parseInt(chunk.trim(), 10);
	console.log(x * x * x);
});

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 input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = input;

var x = parseInt(lines, 10);
var kotae = x*x*x;
console.log(kotae);


process.stdin.setEncoding('utf8');
process.stdin.on('readable', function() {
  var c = process.stdin.read();
  console.log(c * c * c);
});


'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')));


function a (x){
  console.log(x * x * x)
}


'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')));


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


function main(input) {
    console.log(Math.pow(Number(input), 3));
}

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(a,b) {
    //???????????????
    function f1 (a,b){
        return a*b;
    }
    function f2 (a,b){
        return (a+b)*2;
    }
    console.log(f1(a,b), f2(a,b));

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

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';
(function(stdin) {
  var inputs = stdin.toString();
  (function(array) {
    console.log(array.sort(function(a,b){
        return a - b;
    }).join(' '));
  }(inputs.split('\n')[0].split(' ').map(Number)));
}(require('fs').readFileSync('/dev/stdin', 'utf8')));


process.stdin.resume()
process.stdin.setEncoding('utf8')
process.stdin.on('data', function (chunk) {
  const input = chunk.split(' ').map(Number)
  const area = input[0] * input[1]
  const outer = input[0] * 2 +  input[1] * 2
  console.log(area + ' ' + outer)
})


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

  (function(a, b) {
    // ????????????????????????
    console.log((a + b)*2, a * b);

  })(params[0], params[1]);

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


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

  (function(a, b) {
    // ????????????????????????
    console.log(a * b, (a + b) * 2);

  })(params[0], params[1]);

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


//??????????????¨?????????
process.stdin.resume();

process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
    const chunks = chunk.split(' ');
    var hight = parseInt(chunks[0]);
    var width = parseInt(chunks[1]);
    var areaOfRectanglar = hight * width;
    var lengthOfRectanglar = (hight + width) * 2;
    console.log(areaOfRectanglar, lengthOfRectanglar);
})


x = require('fs').readFileSync('/dev/stdin', 'utf8');
arr = x.split(" ");
[a, b] =  arr.map(e => parseInt(e));
console.log(a*b+' '+2*(a+b));


const print2elm = (a,b) => f => console.log(f(a,b));

const input = require('fs').readFileSync('/dev/stdin', 'utf8');
const [a,b] = input.split(" ").map(Number);
const calc = print2elm(a,b);

calc((a,b) => a*b);
calc((a,b) => (a+b)*2);


var inputs = require('fs').readFileSync('/dev/stdin', 'utf8').split(" ");
h = inputs[0];
w = inputs[1];
w = parseInt(w, 10);
h = parseInt(h, 10);

console.log(h*w, 2*(h+w));


function main() {
  var d = new Date(input[0]);
  console.log(d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds())
}

var
input = '';

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

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


process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk){
var line = chunk.toString().split('\n');
var seconds = Number(line[0]);
var hour_sec = 60*60;
var minute_sec = 60;

var hour = Math.floor(seconds / hour_sec);
var minute =  Math.floor((seconds % hour_sec) / minute_sec);
var sec = seconds % hour_sec % minute_sec;

console.log(hour + ':'+minute+':'+sec);
});


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

var S = parseInt(input[0], 10);
var h = Math.floor(S / (60 * 60));
var m = Math.floor(S % (60 * 60) / 60);
var s = Math.floor(S % 60);

console.log([h,m,s].join(':'));


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

  (function(S) {
    // ????????????????????????

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

}(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) {
        if (a < b) {
            console.log('a < b');
        } else if (a > b) {
            console.log('a > b');
        } else {
            console.log('a = b');
        } //????????????????????????
    }(params[0], params[1]));
}(require('fs').readFileSync('/dev/stdin', 'utf8')));

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


'use strict';
(function(stdin) {

    var inputs = stdin.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');
    }

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


var arr = require('fs')
	.readFileSync('/dev/stdin', 'utf8')
	.split(" ")
	.map(function(elem) { return elem|0; });
if (arr[0] == arr[1]) console.log("a == b");
else if (arr[0] > arr[1]) console.log("a > b");
else console.log("a < b");


'use strict';
(function(stdin) {
  var inputs = stdin.toString();
  var params = inputs.split('\n')[0].split(' ').map(Number);
  (function(a,b,c) {
    if(a<b && b<c){
      console.log('Yes');
    }else{
      console.log('No');
    }
    //????????????????????????

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

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';
var Main = function(stdin) {
  var line = stdin.split('\n');
  var result = (function(data) {
  	return data.sort(function(a,b){
  		return a - b;
  	})
  	.join(' ');
  }(
  	line[0].split(' ').map(Number)
  ));
  console.log(result);
};

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


(function(stdin){
	var lines = stdin.toString().split(' ').map(Number);
	var resolt = lines.sort(function(a,b){
		return a -b;
	});
		console.log(resolt);
}(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) {
    if(b > a >c){
      console.log('1 3 8');
    }else{
      console.log('error');
    }
    //????????????????????????

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


process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (input) {
    //??\????????????????????????????????????
    var inputArray = input.split(' ');
    //??\?????????????????°????????????
    var num = inputArray.map(function(x){
        return parseInt(x);
    });
    console.log(num.sort()[0],num.sort[1],num.sort[2]);
});


var x = require('fs').readFileSync('/dev/stdin', 'utf8');
var y = x.split(' ').map(Number);
var arr = y.sort();
console.log(arr[0], arr[1], arr[2]);


var v = require('fs').readFileSync('/dev/stdin', 'utf8');
var n = v.split(" ").map(Number);
var W = n[0], H = n[1], x = n[2], y = n[3], r = n[4];
if (x-r >= 0 && y-r >= 0 && x-r < W && y-r < W && x < H && y < H && r >= 0 && r < W && r < H){
    console.log("Yes");
} else {
    console.log("No")
}

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();
  var cols = inputs.split(' ').map(Number);
  var a = cols[0];
  var b = cols[1];

 console.log(Math.floor(a / b)
  , a % b
  , (a / b).toFixed(10)
  );

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

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


process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', function(chunk) {

var inputs = chunk.toString().trim().split('\n').map(Number);

    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('utf-8');
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]);
}

});


function main(tmp) {
    var i=0;
    while(tmp[i]!=0){
        console.log("Case " + (i+1) + ": " + tmp[i]);
        i = i + 1;
    }
}
var lines = [];
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
reader.on('line', function (line) {
  lines += line;
  if(line==0){
  	main(lines);
  	lines='';
  }
});
process.stdin.on('end', function () {
});


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var sp = input.split("\n").map(Number);
for( var i = 0; sp[i] !== 0; i++ ) {
  console.log("Case " + ( i + 1 ) + ": " + sp[i] );
}


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

process.stdin.on('data', function (chunk) {
    const n = chunk.toString().split("\n");
    n.forEach((x, i) => {
        if (x != 0) {
            console.log(`Case ${i + 1}: ${x}`);
        }
    });
});


'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 0') {
            break;
        }
        var input = inputs[i].split(' ')
        .map(Number).sort(function(a,b) {
            return a - b;
        })
        .join(' ');
console.log (input);

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

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


process.stdin.resume();
process.stdin.setEncoding('utf8');
// ???????????????????¨??????§
// Let's ?????£??¬????????????
process.stdin.on('data', function (chunk) {
    var datas = chunk.split(/\n/);

    for (var i = 0; i < datas.length; i++) {
        var data = datas[i].split(' ').map(Number);

        if (data[0] === 0 && data[1] === 0) { break; }

        console.log(Math.min(data[0], data[1]) + " " + Math.max(data[0], data[1]));
    }
});


function main(input){
    let lines = input.split("\n");
    let i=0;
    while(lines[i]!=="0 0"){
        let nums = lines[i].split(" ");
        let put="";
        if(parseInt(nums[0])>parseInt(nums[1])){
            put=nums[1]+" "+nums[0];
        }else{
            put=nums[0]+" "+nums[1];
        }
        console.log(put);
        i++;

    }

}

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


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");
  i = 0
  while (input[i] != 0) {
    arr = input[i].split(" ");
    sum = 0;
    arr[0] = Number(arr[0]);
    arr[1] = Number(arr[1]);
    arr[2] = Number(arr[2]);

    for (j = arr[0]; j < arr[1]; j++) {
      if (arr[2] % j == 0) {
        sum++
      }
    }
    console.log(sum);
    i++;
  }
});

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


'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]).toFixed(6));
  //main

  //display
  console.log(d, l, 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]).toFixed(4));
  //main

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


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

  //declare variable
  var inputs = stdin.toString().trim().split('\n');
  var a = inputs[0].split(' ')[0];
  var b = inputs[0].split(' ')[1];
  var d = parseInt(a / b);
  var r = a % b;
  var f = a * 100000000 / b;
  //main
  console.log(d, r, f / 100000000);
  //display
  //console.log(inputs);
})(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input) {
    var data = input.split(' ');
    var a = parseInt(data[0]);
    var b = parseInt(data[1]);
    var d = Math.floor(a / b);
    var r = a % b;
    var f = (a / b).toFixed(5);
    var output = [d, r, ,f].join(' ');
    console.log(output);
}

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


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

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

var a = array[0];
var b = array[1];
var d = Math.floor( a / b);
var r = a % b;
var f = ( a / b ).toFixed(5);

console.log(d + " " + r + " " + f);


'use strict';
(function(stdin) {
  var lines  = stdin.toString().split('\n');
  var result = (function(r) {
  	return [
  		Number(Math.PI * r * r).toFixed(6)
  		,Number(Math.PI * 2 * r).toFixed(6)
  	].join(' ');
  }(parseInt(lines[0].trim(),10)
  ));
  console.log(result);
}(require('fs').readFileSync('/dev/stdin', 'utf8')));

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.toFixed(6));
})


function Main(input){
  const r = Number(input);
  let S, L;
  S = (r * r * Math.PI).toFixed(6);
  L = (r * 2 * Math.PI).toFixed(6);
  console.log(S + " " + L);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const input = require('fs').readFileSync('/dev/stdin', 'utf8');
const r = Number(input);
const pi = 3.141;
const area = (Math.pow(r, 2) * Math.PI).toFixed(6);
const len = ((r*2) * Math.PI).toFixed(6);

console.log(area + ' ' + len);


(function(input) {
    var lines = input.split('\n');
    for (var i = 0; i < lines.length; i++) {
        var l = lines[i];
        if (l.match(/\?/)) {
            break;
        }
        var r = Math.round(eval(l));
        console.log(r);
    }
})(require('fs').readFileSync('/dev/stdin', 'utf8'));

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';
process.stdin.on('data', function(chunk) {
    var inputs = chunk.toString().trim();
    var expressions = inputs.split('\n');

    for (var i = 0; i < expressions.length; i++) {
        if (expressions[i] === '0 ? 0') {
            break;
        }
        var expression = expressions[i].split(' ');
        var left = parseFloat(expression[0]);
        var right = parseFloat(expression[2]);
        var op = expression[1];

        switch (op) {
            case '+':
                console.log(left + right);
                break;
            case '-':
                console.log(left - right);
                break;
            case '*':
                console.log(left * right);
                break;
            case '/':
                console.log(Math.floor(left / right));
                break;
        }

    }

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


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var Arr=input.split("\n");
var str="";
for(var i=0;i<Arr.length;i++){
var arr=Arr[i].split(" ").map(Number);
var h=arr[0];
var w=arr[1];
if(h===0 && w===0)break;
if(i!==0)str+="\n";
var W=Array(w+1).join("#")+"\n";
str+=Array(h+1).join(W);
}
console.log(str);

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

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

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

##
##


(function() {
    'use strict';

    var fs = require('fs');
    var contents = fs.readFileSync('/dev/stdin', 'utf-8');

    var printRec = function(contents) {
        var lines = contents.trim().split("\n");
        for (var i = 0; i < lines.length; i++) {
            var b = lines[i].split(" ");
            var H = parseInt(b[0]);
            var W = parseInt(b[1]);

            if (H === 0 && W === 0) {
                break;
            }
            for (var h = 0; h < H; h++) {
                for (var w = 0; w < W; w++) {
                    process.stdout.write("#");
                }
                process.stdout.write("\n");
            }
            process.stdout.write("\n");
        }
    }
    printRec(contents);
})();


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

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

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

###
#.#
###


'use strict';
(function(stdin) {
  //declare function
  function square(array) {
    var h = array[0];
    var w = array[1];
    var outLine = [];
    for (var i = 0; i < w; i++) {
      outLine.push('#');
    }
    outLine = outLine.join('');
    var inLine = [];
    for (var j = 0; j < w - 2; j++) {
      inLine.push('.');
    }
    inLine.push('#');
    inLine.unshift('#');
    inLine = inLine.join('');
    var result = [];
    for (var k = 0; k < h - 2; k++) {
      result.push(inLine);
    }
    result.push(outLine);
    result.unshift(outLine);
    return result.join('\n');
  }

  //declare variable
  var inputs = stdin.toString().trim().split('\n');
  var line = inputs.slice(0, inputs.indexOf('0 0'));
  line = line.map(function(v) {
    return v.split(' ').map(Number);
  });
  //main
  var all = line.map(square).join('\n\n');
  //display
  console.log(all + '\n');
})(require('fs').readFileSync('/dev/stdin', 'utf8'));


var line, even, odd, i, res, hw;

// even : #.#.
// odd  : .#.#

even = {1: '#', 2: '#.'};
odd = {1: '.', 2: '.#'};

line = require('fs').readFileSync('/dev/stdin', 'ascii').split("\n");
line.length = line.lastIndexOf('0 0');

res = [];
for (i in line) {
	hw = line[i].split(' ').map(Number);
	res.push(get_area(hw[0], hw[1]));
	res.push("");
}
console.log(res.join('\n'));

function get_area(h, w) {
	var top, bottom;
	if (h >= 3) {
		top = Math.floor(h / 2);
		if (top % 2 === 1) top++;
		bottom = h - top;
		return get_area(top, w) + '\n' + get_area(bottom, w);
	} else if (h == 1) {
		return get_even(w);
	} else if (h == 2) {
		return get_even(w) + '\n' + get_odd(w);
	}
}

function get_even(n) {
	var i, smaller;
	if (n in even) return even[n];
	if (n % 2 === 0) {
		i = n / 2;
		smaller = get_even(i);
		return smaller + ((i % 2 === 0) ? smaller : get_odd(i));
	}
	return get_even(n - 1) + '#';
}

function get_odd(n) {
	var i, smaller;
	if (n in odd) return odd[n];
	if (n % 2 === 0) {
		i = n / 2;
		smaller = get_odd(i);
		return smaller + ((i % 2 === 0) ? smaller : get_even(i));
	}
	return get_odd(n - 1) + '.';
}

Print a Chessboard

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

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

Note that the top left corner should be drawn by '#'.

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 chessboard made of '#' and '.'.

Print a blank line after each dataset.

Constraints

1 ≤ H ≤ 300

1 ≤ W ≤ 300

Sample Input

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

Sample Output

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

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

#.#
.#.
#.#

#.
.#

#


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

process.stdin.on('data', function (chunk) {
    const n = chunk.toString()
        .split("\n")
        .filter(x => x !== "0 0" && x !== "")
        .map(x => x.split(" ")); // [[3, 4], [5, 6], [3, 3] ...]

    const ans = n.map(x => makeOneAns(Number(x[0]), Number(x[1])));
    ans.forEach(x => {
        x.forEach((y, i) => {
            console.log(y)

        });
    });
});

function makeOneAns(height, width) {
    let ans = []
    for (let i = 0; i < height; i++) {
        if (i % 2 === 0) {
            ans.push(makeEvenLine(width));
        } else {
            ans.push(makeOddLine(width));
        }
    }
    ans.push("")
    return ans
}

function makeOddLine(num) {
    let ans = "";
    for (let i = 0; i < num; i++) {
        if (i % 2 === 0) {
            ans = ans + "."
        } else {
            ans = ans + "#"
        }
    }
    return ans;
}

function makeEvenLine(num) {
    let ans = "";
    for (let i = 0; i < num; i++) {
        if (i % 2 !== 0) {
            ans = ans + "."
        } else {
            ans = ans + "#"
        }
    }
    return ans;
}


function main(input){
    let lines = input.split("\n");
    let length = parseInt(lines[0]);
    let nums = lines[1].split(" ").map(item=>parseInt(item));
    let answer = [];
    for(let i=0;i<length;i++){
        answer.push(nums.pop());
    }
    console.log(answer.join(" "));

}

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

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(input) {
    var a = parse(input, ',');
    var cards = makeCards();
    for (var i = 1; i < a.length; i++) {
        var c = a[i][0];
        delete cards[c];
    }
    console.log(Object.keys(cards).join('\n'));
})(require('fs').readFileSync('/dev/stdin', 'utf8'));

function parse(str, sep, ter) {
    sep = sep || ' ';
    ter = ter || '\n';
    str = str.replace(/\n$/, '');
    var a = str.split(ter);
    for (var i = 0; i < a.length; i++) {
        a[i] = a[i].split(sep);
    }
    return a;
}

function makeCards() {
    var ts = ['S', 'H', 'C', 'D'];
    var a = [];
    for (var i = 0; i < ts.length; i++) {
        var t = ts[i];
        for (var j = 1; j <= 12; j++) {
            a[t + ' ' + j] = 1;
        }
    }
    return a;
}

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

      解説


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

process.stdin.on('end', function() {
  arr = [];
  for (i = 0; i < 52; i++) {
    switch (Math.floor(i / 13)) {
      case 0:
        arr.push("S " + (i + 1));
        break;
      case 1:
        arr.push("H " + (i % 13 + 1));
        break;
      case 2:
        arr.push("C " + (i % 13 + 1));
        break;
      case 3:
        arr.push("D " + (i % 13 + 1));
        break;
    }
  }

  input = input.split("\n");
  i = 1
  while (input[i] != 0) {
    for (j = 0; j < arr.length; j++) {
      if (arr[j] == input[i]) {
        arr.splice(j, 1);
      }
    }
    i++;
  }
  console.log(arr.join("\n"));
});


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var Arr=(input.trim()).split("\n");
Arr.shift();

var bfr=[];
for(var i=0;i<4;i++){
   bfr.push([]);
   for(var j=0;j<3;j++){
      bfr[i].push([]);
      for(var k=0;k<10;k++)bfr[i][j].push(0);
   }
}

for(var i=0;i<Arr.length;i++){
   var arr=Arr[i].split(" ").map(Number);
   var b=arr[0]-1;
   var f=arr[1]-1;
   var r=arr[2]-1;
   var v=arr[3];
   bfr[b][f][r]=bfr[b][f][r]+v;
   if(bfr[b][f][r]>9)bfr[b][f][r]=9;
   if(bfr[b][f][r]<0)bfr[b][f][r]=0;
}
for(var i=0;i<4;i++){
for(var j=0;j<3;j++){
console.log(" "+bfr[i][j].join(" "));
}
if(i!==3)console.log("####################");
}

Official House

You manage 4 buildings, each of which has 3 floors, each of which consists of 10 rooms. Write a program which reads a sequence of tenant/leaver notices, and reports the number of tenants for each room.

For each notice, you are given four integers b, f, r and v which represent that v persons entered to room r of fth floor at building b. If v is negative, it means that −v persons left.

Assume that initially no person lives in the building.

Input

In the first line, the number of notices n is given. In the following n lines, a set of four integers b, f, r and v which represents ith notice is given in a line.

Output

For each building, print the information of 1st, 2nd and 3rd floor in this order. For each floor information, print the number of tenants of 1st, 2nd, .. and 10th room in this order. Print a single space character before the number of tenants. Print "####################" (20 '#') between buildings.

Constraints

No incorrect building, floor and room numbers are given.

0 ≤ the number of tenants during the management ≤ 9

Sample Input

3
1 1 3 8
3 2 2 7
4 3 8 1

Sample Output

0 0 8 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
####################
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
####################
0 0 0 0 0 0 0 0 0 0
0 7 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
####################
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0


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

readable.on( 'end', function() {
  var oh = new Array(4);
  for( var i=0; i<4; i++ ) {
    oh[i] = new Array(3);
    for( var j=0; j<3; j++ ) {
      oh[i][j] = new Array(10);
      for( var k=0; k<10; k++ ) {
        oh[i][j][k] = 0;
      }
    }
  }
  var data = input.replace( '\n', '' ).split( '\n' );
  for( var i=1; i<data.length; i++ ) {
    var p = data[i].split( ' ' );
    var b = parseInt( p[0] );
    b--;
    var f = parseInt( p[1] );
    f--;
    var r = parseInt( p[2] );
    r--;
    var v = parseInt( p[3] );
    for( var s=0; s<4; s++ ) {
      for( var j=0; j<3; j++ ) {
        for( var k=0; k<10; k++ ) {
          if( s == b && j == f && k == r ) {
            oh[b][f][r] += v;
          }
        }
      }
    }
  }
  var output = [];
  for( var i=0; i<4; i++ ) {
    for( var j=0; j<3; j++ ) {
      for( var k=0; k<10; k++ ) {
        output.push( ' '+oh[i][j][k] );
      }
       if( i != 2 ) { output.push( '\n' ); }
    }
    if( i != 3 ) { output.push( '####################\n' ); }
  }
  console.log( output.join( '' ) );
});


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

var lines = (input.trim()).split(/\n/g);
var n = +lines[0].split(' ')[0];
var m = +lines[0].split(' ')[1];

var A = lines.slice(1, n + 1);
var b = lines.slice(n + 1, n + m + 1);

var ans;
for (var i = 0; i < n; i++) {
    ans = 0;
    for (var j = 0; j < m; j++) {
        ans += A[i].split(' ')[j] * b[j];
    }
    console.log(ans);
}

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

Matrix Vector Multiplication

Write a program which reads a $ n \times m$ matrix $A$ and a $m \times 1$ vector $b$, and prints their product $Ab$.

A column vector with m elements is represented by the following equation.

\[
b = \left(
\begin{array}{c}
b_1 \\
b_2 \\
: \\
b_m \\
\end{array}
\right)
\]

A $n \times m$ matrix with $m$ column vectors, each of which consists of $n$ elements, is represented by the following equation.

\[
A = \left(
\begin{array}{cccc}
a_{11} & a_{12} & ... & a_{1m} \\
a_{21} & a_{22} & ... & a_{2m} \\
: & : & : & : \\
a_{n1} & a_{n2} & ... & a_{nm} \\
\end{array}
\right)
\]

$i$-th element of a $m \times 1$ column vector $b$ is represented by $b_i$ ($i = 1, 2, ..., m$), and the element in $i$-th row and $j$-th column of a matrix $A$ is represented by $a_{ij}$ ($i = 1, 2, ..., n,$ $j = 1, 2, ..., m$).

The product of a $n \times m$ matrix $A$ and a $m \times 1$ column vector $b$ is a $n \times 1$ column vector $c$, and $c_i$ is obtained by the following formula:

\[
c_i = \sum_{j=1}^m a_{ij}b_j = a_{i1}b_1 + a_{i2}b_2 + ... + a_{im}b_m
\]

Input

In the first line, two integers $n$ and $m$ are given. In the following $n$ lines, $a_{ij}$ are given separated by a single space character. In the next $m$ lines, $b_i$ is given in a line.

Output

The output consists of $n$ lines. Print $c_i$ in a line.

Constraints

$1 \leq n, m \leq 100$

$0 \leq b_i, a_{ij} \leq 1000$

Sample Input

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

Sample Output

5
6
9


function Main(input) {
	let [nm, ...others] = input.split('\n');
	nm = nm.split(' ');
	let n = Number(nm[0]);
	let m = Number(nm[1]);

	let arryA = [];
	for (let i = 0; i < n + m; i++){
		arryA.push([]);
	}

	for (let i = 0; i < n + m; i++){
		arryA[i] = others[i].split(' ').map(Number);
	}

	for (let i = 0; i < n; i++){
		let result = 0;
		for (let j = 0; j < m; j++){
			result += arryA[i][j] * arryA[n + j][0];
		}
		console.log(result);
	}
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


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 rc = data[0].split( " " ).map( Number );
  var r = rc[0];
  var c = rc[1];
  var t = Array( c+1 );
  for( var i=0; i<c+1; i++ ) { t[i] = 0; }
  var output = [];
  for( var index=1; index<r+1; index++ ) {
    var nums = data[index].split( ' ' ).map( Number );
    var sum = 0;
    for( var j=0; j<c; j++ ) {
      sum += nums[j];
      t[j] += nums[j];
    }
    t[c] += sum;
    nums.push( sum );
    output.push( nums.join( " " ) );
  }
  output.push( t.join( " " ) );
  console.log( output.join( "\n" ) );
});

Spreadsheet

Your task is to perform a simple table calculation.

Write a program which reads the number of rows r, columns c and a table of r × c elements, and prints a new table, which includes the total sum for each row and column.

Input

In the first line, two integers r and c are given. Next, the table is given by r lines, each of which consists of c integers separated by space characters.

Output

Print the new table of (r+1) × (c+1) elements. Put a single space character between adjacent elements. For each row, print the sum of it's elements in the last column. For each column, print the sum of it's elements in the last row. Print the total sum of the elements at the bottom right corner of the table.

Constraints

1 ≤ r, c ≤ 100

0 ≤ an element of the table ≤ 100

Sample Input

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

Sample Output

1 1 3 4 5 14
2 2 2 4 5 15
3 3 0 1 1 8
2 3 4 4 6 19
8 9 9 13 17 56


"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);
});
/* 入力は
 */

const ca = 'a'.charCodeAt(0);
const cz = 'z'.charCodeAt(0);
const chars = [...Array(cz - ca +1).keys()].map(x=>String.fromCharCode(x+ca));

reader.on('close', () => {
    var txt = lines.join('\n')

    var h = aux(txt)

    for (var c of chars) {
	console.log(c + ' : ' + h[c]);
    }
});

function aux(txt)
{
    var re=/[a-z]/;
    var h={};
    for (var c of chars) {
	h[c]=0;
    }

    for (var i=0; i<txt.length; i++) {
	var c = txt[i].toLowerCase()
	if (re.test(c)) {
	    h[c] += 1
	}
    }

    return(h);
}

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


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 n = data[0];
  var tscore = 0;
  var hscore = 0;
  for( var i=1; i<data.length-1; i++ ) {
    var taha = data[i].split( ' ' );
    if( taha[0] < taha[1] ) {
      hscore += 3;
    } else if( taha[1] < taha[0] ) {
      tscore += 3;
    } else {
      hscore += 1;
      tscore += 1;
    }
  }
  console.log( tscore+' '+hscore );
});

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


const main = (input) => {
    let lengthList = input.split(' ');
    let divide=[];
    let  num= parseInt(lengthList[0]);
    for(let i=2;i<num;i++){
       if(num%i==0){
          divide.push(i);
          num=num/i;
       }
    }
    console.log(num+":");
    for(let div of divide){
       console.log(" "+div);
    }
}

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

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 n = +input;

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

var primes = [];

while (n % 2 == 0) {
    primes.push(2);
    n /= 2;
}
while (n % 3 == 0) {
    primes.push(3);
    n /= 3;
}
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;
    }
}

process.stdout.write(primes.join(' ')+"\n");


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);
	});
}
var mod = 1000000007;
function rec(m,n){
	if(n <= 3){
		return Math.pow(m,n) % mod;
	}
	if(n % 2 == 0){
		return Math.pow(rec(m,n/2),2) % mod;
	}else{
		return (Math.pow(rec(m,(n-1)/2),2) * m) % mod;
	}
}
function main(lines){
  var k = lines[0];
  var j = k.split(" ").map(function(e){return Number(e);});
  log(rec(j[0],j[1]));
}

Power

For given integers m and n, compute mn (mod 1,000,000,007). Here, A (mod M) is the remainder when A is divided by M.

Input

m n

Two integers m and n are given in a line.

Output

Print mn (mod 1,000,000,007) in a line.

Constraints

1 ≤ m ≤ 100

1 ≤ n ≤ 109

Sample Input 1

2 3

Sample Output 1

8

Sample Input 2

5 8

Sample Output 2

390625


(async () => {
    let input = '';
    for await (const chunk of process.stdin) input += chunk;
    const k = +input;
    console.log('ACL'.repeat(k));
})()

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


class UnionFind {
  constructor(n) {
    this.p = new Array(n).fill(null).map((_, i) => i)
    this.height = new Array(n).fill(0)
    this.size = new Array(n).fill(1)
  }

  unite(a, b) {
    this.link(this.findSet(a), this.findSet(b))
  }

  link(a, b) {
    if (a === b) return null

    if (this.height[a] > this.height[b]) {
      this.p[b] = a
      this.size[a] += this.size[b]
    } else {
      this.p[a] = b
      this.size[b] += this.size[a]

      if (this.height[a] === this.height[b]) this.height[b]++
    }
  }

  findSet(x) {
    if (this.p[x] === x) return x
    return this.findSet(this.p[x])
  }
}

const main = (input) => {
  const [t, ...q] = input.trim().split('\n')
  const [n,] = t.split(' ').map(Number)

  const uf = new UnionFind(n)

  for (let i=0; i<q.length; i++) {
    const [a, b] = q[i].split(' ').map(Number)
    uf.unite(a-1, b-1)
  }

  const ans = {}
  for (let i=0; i<n; i++) {
    ans[uf.findSet(i)] = 1
  }

  return console.log(Object.keys(ans).length - 1)
  // return console.log(Array.from(new Set(uf.p)).length - 1)
}

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

Score : 300 points

Problem Statement

There are N cities numbered 1 through N, and M bidirectional roads numbered 1 through M.
Road i connects City A_i and City B_i.

Snuke can perform the following operation zero or more times:

Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities.

After he finishes the operations, it must be possible to travel from any city to any other cities by following roads (possibly multiple times).

What is the minimum number of roads he must build to achieve the goal?

Constraints

2 \leq N \leq 100,000

1 \leq M \leq 100,000

1 \leq A_i < B_i \leq N

No two roads connect the same pair of cities.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

Print the answer.

Sample Input 1

3 1
1 2

Sample Output 1

1

Initially, there are three cities, and there is a road between City 1 and City 2.

Snuke can achieve the goal by building one new road, for example, between City 1 and City 3.
After that,

We can travel between 1 and 2 directly.

We can travel between 1 and 3 directly.

We can travel between 2 and 3 by following both roads (2 - 1 - 3).


function Main(input) {
    // 最後の文字を取得
    const last = input.split("\n")[0].slice(-1) ;
    const sufix = last === "s" ? "es" : "s";
	//出力
	console.log(`${input}${sufix}`);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
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


// inputに入力データ全体が入る
function Main(input) {
  lines = input.split("\n");
  totalThrow = parseInt(lines[0], 10);
  count = 0;
  for (i=1; i<=totalThrow; i++){
    splitpernum = lines[i].split(" ");
    //console.log(splitpernum);
    if (count == 3){

    } else if (count < 3){
    	if (splitpernum[0] == splitpernum[1]){
        count ++;
        } else {
        count = 0;
        }
    }

  }
  	//出力
      if (count < 3){
      console.log("No");
    } else if (count == 3){
          console.log("Yes");
    }

}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
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


//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n↑入力 ↓出力');
  Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var list = new Array(N);
  for(var i = 0; i < N; i++){
    list[i] = nextIntArray();
  }
  for(var i = 0; i < N - 2; i++){
    var c1 = list[i][0] == list[i][1];
    var c2 = list[i + 1][0] == list[i + 1][1];
    var c3 = list[i + 2][0] == list[i + 2][1];
    if(c1 && c2 && c3){
      myout("Yes");
      return;
    }
  }
  myout("No");
}


function main(input) {
    var N= Number(input.trim());
    var count = 0
    for (var C = 1; C <N ; C++){
        var X = N-C;
        count = count + Count(X)
    }
    console.log(count);
}

function Count(X){
    var result = 1;
    var array = pf(X);
    for ( var k in array){
        if (k !== "1") result = result * (array[k]+1)
    }
    return result;
}

function pf(n) {
    var result = {};

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

    var init = 2;

    while (n !== 1) {
        var i = init;
        while (i < Number.MAX_SAFE_INTEGER) {
            if (n % i === 0) {
                n /= i;
                if (!(result[i] > 0)) {
                    result[i] = 0;
                }
                result[i]++;
                break;
            }
            i++;
        }
        init = i;
    }
    return result;
}

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

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


function Main(input) {
    input = input.trim();
    const n = parseInt(input, 10);

    // nからc引いた数の約数の数を調べればいいんじゃね!?

    let count = 0;
    for(let c = 1; c < n; c++) {
       const subNum = n - c;

       count += toDivisor(subNum);
    }

    console.log(count);
}

// 約数の数を求める関数
function toDivisor(num) {
    let count = 0;
    let double = 0;
    for(let i = 1; i**2 <= num; i++) {
        if(num % i != 0) continue;
        if(i**2 === num) double++;
        count++;
    }

    return count * 2 - double;
}

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


function main(lines) {
  const N = n();

  let cnt = 0;
  for (let c = 1; c < N; c++) {
    const _N = N-c;
    const max = Math.sqrt(_N);
    for (let a = 1; a <= max; a++) {
      if (_N % a == 0) {
        if (_N / a == a) cnt++;
        else cnt += 2;
      }
    }
  }

  return cnt;
}

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

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

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


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

const lines = input.split('\n')
const [N, K] = lines[0].split(' ').map(Number)
const k = []

for (let i = 1; i <= K; i++) {
    const [L, R] = lines[i].split(' ').map(Number)
    k.push([L, R])
}
const ksum = Array(K).fill(0)

const mod = 998244353
const map = Array(N).fill(0)
map[0] = 1

for (let i = 1; i < map.length; i++) {
    let c = 0
    for (let j = 0; j < k.length; j++) {
        ksum[j] = ksum[j] + (map[i - k[j][0]] || 0) - (map[i - k[j][1] -1 ] || 0)
    }
    map[i] = ksum.reduce((a, b) => a + b) % mod
}

console.log(map.pop())

Score : 400 points

Problem Statement

There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.

Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.

You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K].
Let S be the union of these K segments.
Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.

When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.

To help Tak, find the number of ways to go to Cell N, modulo 998244353.

Constraints

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

1 \leq K \leq \min(N, 10)

1 \leq L_i \leq R_i \leq N

[L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
L_1 R_1
L_2 R_2
:
L_K R_K

Output

Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.

Sample Input 1

5 2
1 1
3 4

Sample Output 1

4

The set S is the union of the segment [1, 1] and the segment [3, 4], therefore S = \{ 1, 3, 4 \} holds.

There are 4 possible ways to get to Cell 5:

1 \to 2 \to 3 \to 4 \to 5,

1 \to 2 \to 5,

1 \to 4 \to 5 and

1 \to 5.

Sample Input 2

5 2
3 3
5 5

Sample Output 2

0

Because S = \{ 3, 5 \} holds, you cannot reach to Cell 5.
Print 0.

Sample Input 3

5 1
1 2

Sample Output 3

5

Sample Input 4

60 3
5 8
1 3
10 15

Sample Output 4

221823067

Note that you have to print the answer modulo 998244353.


function main(input) {
  const x = parseInt(input);
  // この下の行から
  if(x==0){console.log("1");}else if(x==1){
    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


"use strict"

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


((input) => {
  let [a,b,c,d] = input.split(' ').map(BigInt);
  let arr = [a*c,a*d,b*c,b*d];
  let max = arr.reduce((acc, curr) => {
    return acc > curr ? acc : curr;
  });

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

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


"use strict"

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

  let product_matrix = [];
  for ( let x = a; x <= b; x++ ) {
    for (  let y = c; y <= d; y++ ) {
      product_matrix.push(x * y);
    }
  }
  product_matrix.sort(function(a, b) {
    return b - a;
  });

  console.log(product_matrix[0]);

  return;
}

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


'use script';

{
function Main(input) {
 	const N = input;
	const b = BigInt(1000000000+7);

	function x(m){

		let d = BigInt(1);

		for(i=0; i<N; i++){
				d *= BigInt(m);
				d %= b;
		}

	return(d)
	}

	let ans = (x(10)-x(9))+(x(10)-x(9))-(x(10)-x(8))%b;
  	console.log(ans.toString());

	}

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

}

Score : 300 points

Problem Statement

How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?

0 \leq A_i \leq 9

There exists some i such that A_i=0 holds.

There exists some i such that A_i=9 holds.

The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^9 + 7.

Sample Input 1

2

Sample Output 1

2

Two sequences \{0,9\} and \{9,0\} satisfy all conditions.

Sample Input 2

1

Sample Output 2

0

Sample Input 3

869121

Sample Output 3

2511445


const main = (input) => {
  input = input.split("\n")
  var N=Number(input[0]);
  let point=[];
  for (var i=1; i<=N;i++){
    point[i]=input[i].split(" ").map(n=>Number(n));
  }

  let memo = 0;
  for (var i=1; i<=N;i++){
    for (var j=i+1; j<=N;j++){
      dist = Math.abs(point[i][0]-point[j][0])+Math.abs(point[i][1]-point[j][1]);
      if (dist>memo){memo = dist;}
    }
  }
  console.log(input);
  console.log(point);
  console.log(memo);
  };

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

Score : 500 points

Problem Statement

There are N points on the 2D plane, i-th of which is located on (x_i, y_i).
There can be multiple points that share the same coordinate.
What is the maximum possible Manhattan distance between two distinct points?

Here, the Manhattan distance between two points (x_i, y_i) and (x_j, y_j) is defined by |x_i-x_j| + |y_i-y_j|.

Constraints

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

1 \leq x_i,y_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the answer.

Sample Input 1

3
1 1
2 4
3 2

Sample Output 1

4

The Manhattan distance between the first point and the second point is |1-2|+|1-4|=4, which is maximum possible.

Sample Input 2

2
1 1
1 1

Sample Output 2

0