'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');
    main();
});

function readline() {
    return inputString[currentLine++];
}

// main funtion .. code start ..... ///

function main() {

//var input = readline()

var ar = readline().split(' ').map(x => parseInt(x));
var a = ar[0]
var s = readline().split(' ');
var str = s[0];

console.log(a < 3200 ? 'red' : 'pink');
}

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

Score : 100 points

Problem Statement

You will be given an integer a and a string s consisting of lowercase English letters as input.

Write a program that prints s if a is not less than 3200 and prints red if a is less than 3200.

Constraints

2800 \leq a < 5000

s is a string of length between 1 and 10 (inclusive).

Each character of s is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

a
s

Output

If a is not less than 3200, print s; if a is less than 3200, print red.

Sample Input 1

3200
pink

Sample Output 1

pink

a = 3200 is not less than 3200, so we print s = pink.

Sample Input 2

3199
pink

Sample Output 2

red

a = 3199 is less than 3200, so we print red.

Sample Input 3

4049
red

Sample Output 3

red

a = 4049 is not less than 3200, so we print s = red.

Submitted source-code file size, in bytes.

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

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


function main(input) {
  const inputArray = input.split(/\n/);
  console.log(inputArray[0] >= 3200 ? inputArray[1] : 'red');
}
 main(require('fs').readFileSync('/dev/stdin', 'utf8'));


var lines = [];
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
reader.on('line', function (line) {
  lines.push(line);
});
process.stdin.on('end', function () {
  const number = lines[0];
  const str = lines[1];
  if (number >= 3200) {
    console.log(str);
  } else {
    console.log('red');
  }
});


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

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


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

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


const RedorNot = ()=>{
  const a ;
  const s ;

  if(a >= 3200){
    console.log(s);
  }else{
    console.log('red');
  }
}
RedorNot(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
    input = input.split(" ");
    var a = parseInt(input[0]);
    var s=input[1];
    if(a>=3200){
        console.log(s);
    }else {
        console.log('red');
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
  const args = input.split("\n");
  const a = args[0];
  const b = args[1];
  const ans = a >= 3200 ? b : "red";
  console.log(ans);
}

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


const a = 3200;
const s = 'pink';

if(a >= 3200){
  console.log(s);
}else{
  console.log('red');
}


function Main(input) {
    input = input.split("\n")
    var a = input[0];
    var s = input[1];
    if(a >= 3200){
        console.log(s)
    }else{
        console.log("red")
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
    const args = input.split('\n');
    const a = parseInt(args[0], 10);
    const s = args[1];

    var res = (a >= 3200) ? s : "red";

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


'use strict';
console.log(function(args){
  const tmp = args.trim().split('\n').map( r=>r.split(' ').map(v=>v|0) );
  const N = tmp[0][0], Q = tmp[0][1];
  const ki = Array(N+1).fill(0).map(_=>[]);
  for ( let i = 0; i < N-1; i++ ) {
    const a = tmp[i+1][0];
    const b = tmp[i+1][1];
    ki[a].push(b);
    ki[b].push(a);
  }
  const counter = Array(N+1).fill(0);
  for ( let j = 0; j < Q; j++ ) {
    const p = tmp[j+N][0];
    const x = tmp[j+N][1];
    counter[p] += x;
  }
  const queue = [1], done = Array(N).fill(false);
  let i = 0;
  done[1] = true;
  do {
    let q = queue[i++];
    for ( let child of ki[q] ) {
      if ( done[child] ) continue;
      counter[child] += counter[q];
      queue.push(child);
      done[child] = true;
    };
  } while( i < N );
  return counter.slice(1).join(' ');
}(require('fs').readFileSync('/dev/stdin', 'utf8')));

Score : 400 points

Problem Statement

Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

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

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

1 \leq a_i < b_i \leq N

1 \leq p_j \leq N

1 \leq x_j \leq 10^4

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

Sample Input 1

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

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.

Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.

Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

Sample Input 2

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

Sample Output 2

20 20 20 20 20 20


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

  bfs(0);

  function bfs(index){
    var queue = [[index, list[index]["counter"]]];
    while(queue.length > 0){
      var tmp = queue.shift();
      //myerr(tmp);
      list[tmp[0]]["sum"] += tmp[1];
      var children = list[tmp[0]]["child"];
      for(var i = 0; i < children.length; i++){
        queue.push([children[i], tmp[1] + list[children[i]]["counter"]]);
      }
    }
  }
  for(var i = 0; i < N; i++){
    output[i] = list[i]["sum"];
  }
  myout(myconv(output,8));
}


input = require('fs').readFileSync('/dev/stdin', 'utf8')
lines = input.split('\n')
line = lines.shift().split(' ')
N = line[0] * 1
Q = line[1] * 1
t = {}
n = []
a = []

for (i=1; i <= N; i++) {
    t[i] = []
    n[i] = 0
    a.push(0)
}

for (i=0; i < N-1; i++) {
    line = lines[i].split(' ')
    t[line[0]].push(line[1])
}

for (i=N-1; i < N + Q; i++) {
    line = lines[i].split(' ')
    n[line[0]] += line[1] * 1
}

h = []
for (i=1; i<N; i++) {
    h.push(i)
    while(h.length) {
        j = h.pop()
        for (k=0; k<t[j].length; k++) {
            h.push(t[j][k])
        }
        a[j-1] += n[i]
    }
}

console.log(a.join(' '))


module.exports=function(t){var r={};function e(n){if(r[n])return r[n].exports;var i=r[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,e),i.l=!0,i.exports}return e.m=t,e.c=r,e.d=function(t,r,n){e.o(t,r)||Object.defineProperty(t,r,{enumerable:!0,get:n})},e.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},e.t=function(t,r){if(1&r&&(t=e(t)),8&r)return t;if(4&r&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(e.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&r&&"string"!=typeof t)for(var i in t)e.d(n,i,function(r){return t[r]}.bind(null,i));return n},e.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(r,"a",r),r},e.o=function(t,r){return Object.prototype.hasOwnProperty.call(t,r)},e.p="",e(e.s=0)}([function(t,r,e){e(1)(e(3).readFileSync("/dev/stdin","UTF-8"))},function(t,r,e){function n(t,r){return function(t){if(Array.isArray(t))return t}(t)||function(t,r){var e=[],n=!0,i=!1,o=void 0;try{for(var u,s=t[Symbol.iterator]();!(n=(u=s.next()).done)&&(e.push(u.value),!r||e.length!==r);n=!0);}catch(t){i=!0,o=t}finally{try{n||null==s.return||s.return()}finally{if(i)throw o}}return e}(t,r)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}var i=e(2);t.exports=function(t){for(var r=t.split("\n"),e=n(r[0].split(" ").map(function(t){return Number(t)}),2),o=e[0],u=e[1],s=new Array(o),a=0;a<o-1;a++){var l=n(r[a+1].split(" ").map(function(t){return Number(t)-1}),2),f=l[0],c=l[1];s[f]||(s[f]=[]),s[c]||(s[c]=[]),s[f].push(c),s[c].push(f)}for(var p=new Array(o).fill(0),d=0;d<u;d++){var v=n(r[d+o].split(" ").map(function(t){return Number(t)}),2),y=v[0],h=v[1];p[y-1]+=h}var m=new i,b=new Array(o).fill(0);for(m.enq(0);m.size>0;){var x=m.deq();b[x]=1;var g=!0,w=!1,j=void 0;try{for(var S,O=s[x][Symbol.iterator]();!(g=(S=O.next()).done);g=!0){var q=S.value;1!=b[q]&&(p[q]+=p[x],m.enq(q))}}catch(t){w=!0,j=t}finally{try{g||null==O.return||O.return()}finally{if(w)throw j}}}console.log(p.join(" "))}},function(t,r,e){"use strict";t.exports=class{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;this.size=0,this.items=[],this.ind=0,this.maxGap=t}enq(t){this.size+=1,this.items.push(t),this.items.size-this.ind>this.maxGap&&(this.items=this.items.slice(this.ind))}deq(){var t=this.items[this.ind];return this.size-=1,this.ind+=1,t}}},function(t,r){t.exports=require("fs")}]);


module.exports=function(r){var e={};function t(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return r[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=r,t.c=e,t.d=function(r,e,n){t.o(r,e)||Object.defineProperty(r,e,{enumerable:!0,get:n})},t.r=function(r){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},t.t=function(r,e){if(1&e&&(r=t(r)),8&e)return r;if(4&e&&"object"==typeof r&&r&&r.__esModule)return r;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:r}),2&e&&"string"!=typeof r)for(var o in r)t.d(n,o,function(e){return r[e]}.bind(null,o));return n},t.n=function(r){var e=r&&r.__esModule?function(){return r.default}:function(){return r};return t.d(e,"a",e),e},t.o=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},t.p="",t(t.s=0)}([function(r,e,t){t(1)(t(2).readFileSync("/dev/stdin","UTF-8"))},function(r,e){function t(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,e){var t=[],n=!0,o=!1,u=void 0;try{for(var i,l=r[Symbol.iterator]();!(n=(i=l.next()).done)&&(t.push(i.value),!e||t.length!==e);n=!0);}catch(r){o=!0,u=r}finally{try{n||null==l.return||l.return()}finally{if(o)throw u}}return t}(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}r.exports=function(r){for(var e=r.split("\n"),n=t(e[0].split(" ").map(function(r){return Number(r)}),2),o=n[0],u=n[1],i=new Array(o),l=0;l<o-1;l++){var a=t(e[l+1].split(" ").map(function(r){return Number(r)-1}),2),f=a[0],c=a[1];i[f]||(i[f]=[]),i[c]||(i[c]=[]),i[f].push(c),i[c].push(f)}for(var p=new Array(o).fill(0),y=0;y<u;y++){var s=t(e[y+o].split(" ").map(function(r){return Number(r)}),2),d=s[0],v=s[1];p[d-1]+=v}for(var b=[0],m=new Array(o).fill(0),h=0;h<b.length;){var x=b[h];h+=1,m[x]=1;var g=!0,j=!1,w=void 0;try{for(var S,O=i[x][Symbol.iterator]();!(g=(S=O.next()).done);g=!0){var _=S.value;1!=m[_]&&(p[_]+=p[x],b.push(_))}}catch(r){j=!0,w=r}finally{try{g||null==O.return||O.return()}finally{if(j)throw w}}}console.log(p.join(" "))}},function(r,e){r.exports=require("fs")}]);


function Main(input) {
  const inputs = input.split("\n");
  const a = inputs[0].split(" ").map(num => parseInt(num, 10));
  const N = a[0];
  const Q = a[1];
  var hash = {};
  var results = new Array(N).fill(0);
  inputs.slice(1, N).forEach(list => {
    const nodes = list.split(" ").map(num => parseInt(num, 10));
    const node = nodes[0];
    const nextNode = nodes[1];
    if (!hash[node]) {
      hash[node] = [nextNode];
    } else {
      hash[node].push(nextNode);
    }
    Object.keys(hash).filter((key) => hash[key].indexOf(node) !== -1).forEach((key) => {
      hash[key].push(nextNode);
    })
  });
  console.log(hash);
  inputs.slice(N).forEach(list => {
    const nodeAndNum = list.split(" ").map(num => parseInt(num, 10));
    const node = nodeAndNum[0];
    const num = nodeAndNum[1];
    results[node - 1] += num;
    (hash[node] || []).forEach(n => {
      results[n - 1] += num;
    });
  });
  console.log(results.join(" "));
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
  const inputs = input.split("\n");
  const a = inputs[0].split(" ").map(num => parseInt(num, 10));
  const N = a[0];
  const Q = a[1];
  var hash = {};
  var results = new Array(N).fill(0);
  inputs.slice(1, N).forEach(list => {
    const nodes = list.split(" ").map(num => parseInt(num, 10));
    const node = nodes[0];
    const nextNode = nodes[1];
    if (!hash[node]) {
      hash[node] = [nextNode];
    } else {
      hash[node].push(nextNode);
    }
  });
  function addResult(nodeNum, nodeList, num) {
    results[nodeNum - 1] += num;
    if (nodeList) {
      nodeList.forEach(n => {
        if (nodeNum !== n) {
          addResult(n, hash[n], num);
        }
      });
    }
  };
  inputs.slice(N).forEach(list => {
    const nodeAndNum = list.split(" ").map(num => parseInt(num, 10));
    const node = nodeAndNum[0];
    const num = nodeAndNum[1];
    addResult(node, hash[node], num);
  });
  console.log(results.join(" "));
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function add(node, value) {
	node.val += value;
	for(var i = 0; i < node.children.length; i++) add(node.children[i], value);
}
// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	var count = input[0].split(" ");
	var nodeCount = count[0]-0;
	var dataCount = count[1]-0;
	var i;
	var nodes = [{ val:0, children:[] }];

	for(i = 1; i < nodeCount; i++) {
		var data = input[i].split(" ");
		var parent = nodes[data[0]-1];
		var childIdx = data[1]-1;
		nodes[childIdx] = { val:0, children:[] };
		parent.children[parent.children.length] = nodes[childIdx];
	}
	for(i = nodeCount; i < nodeCount + dataCount; i++) {
		var data = input[i].split(" ");
		add(nodes[data[0]-1], data[1]-0);
	}

	var ret = "" + nodes[0].val;
	for(var i = 1; i < nodeCount; i++) ret += " " + nodes[i].val;
	console.log(ret);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict"
class Node{
    constructor(number, value){
        this.number = number
        this.value = value
        this.nextNodeList = []
    }
    addNextNode(nextNode){
        this.nextNodeList.push(nextNode)
    }
    addValue(value){
        this.value += value
        for(var node=0; node < this.nextNodeList.length; node++)
        {
            this.nextNodeList[node].addValue(value)
        }
    }
}

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

    var a = []
    var b = []
    for(var i=0; i<N-1; i++)
    {
        var tmp2 = input[1+i].split(" ")
        a.push(Number(tmp2[0]))
        b.push(Number(tmp2[1]))
    }

    var p = []
    var x = []
    for(var i=0; i<Q; i++)
    {
        var tmp2 = input[N+i].split(" ")
        p.push(Number(tmp2[0]))
        x.push(Number(tmp2[1]))
    }

    // 木をつくる
    var nodelist = []
    for(var i=1; i<=N; i++)
    {
        nodelist.push(new Node(i,0))
    }
    // console.log(nodelist)

    // 辺を結ぶ
    for(var i=0; i<N-1; i++)
    {
        nodelist[a[i]-1].addNextNode(nodelist[b[i]-1])
    }
    // console.log(nodelist)

    // 値を足す
    for(var i=0; i<Q; i++)
    {
        nodelist[p[i]-1].addValue(x[i])
    }

    // console.log(nodelist)
    for(var node in nodelist)
    {
        process.stdout.write(nodelist[node].value + " ")
    }

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


function Main(input) {
  lines = input.split("\n");
  lines.pop();
  l = lines.shift();
  N = l.split(" ")[0] * 1;
  Q = l.split(" ")[1] * 1;
  t = {};
  len = lines.length - Q;
  for (i = 0; i < len; i++) {
    l = lines.shift().split(" ");
    if (!t[l[0]]) {
      t[l[0]] = [];
    }
    t[l[0]].push(l[1]);
  }
//   console.log(t);
  //   console.log(lines)
  s = lines
    .map(function(a) {
      return a.split(" ").map(function(b) {
        return b * 1;
      });
    })
    .sort(function(a, b) {
      return a[0] - b[0];
    });
//   console.log(s);
  a = s[0][0];
  b = s[0][1];
  sum = b;
  ans = [0];
  for (i = 1; i < s.length; i++) {
    // console.log(s[i]);
    if (a != s[i][0]) {
      k = a - 1;
      if (ans[k] == undefined) {
        ans[k] = 0;
      }
      ans[k] += sum;
      a = s[i][0];
      sum = s[i][1];
    } else {
      sum += s[i][1];
    }
  }

  k = a - 1;
  if (ans[k] == undefined) {
    ans[k] = 0;
  }
  ans[k] += sum;

//   console.log("1", ans);

  keys = Object.keys(t);
  while (a = keys.shift())  {
      if (t[a] && t[a].length > 0) {
        t[a].map(function(b) {
          if (ans[b - 1] == undefined) {
            ans[b - 1] = ans[a - 1];
          } else {
              ans[b - 1] += ans[a - 1];
          }
        });
      }
  }

  console.log(ans.join(" "));
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


var input = require('fs').readFileSync('/dev/stdin', 'utf8')
  .split("\n").map((s)=>{return s.split(" ").map((i)=>{return i - 0;});});

var N = input[0][0];
//var E = input[0][1];
var P = input[0][2];
input.shift();

var data = {};
for (var i = 1; i <= N; i++) { data[i] = []; }
input.forEach((i)=>{
	data[i[0]].push([i[1],i[2]]);
});

var ans = -1;

(() => {

var route = [1];
var gain = [0];
var pathStack = [Array.from(data[1])];
var paths = pathStack.pop();

do {
  var path = paths.pop();
  var p = path[0];
  //console.log("> " +  route + " - " + p);
  if (p == N) {
	  // one goal
    var g = path[1];
	  ans = Math.max(gain.reduce((p,i)=>{return p+i;},0) + g, ans);
  }
  if (route.indexOf(p) == -1) {
    if (data[p].length > 0) {
      pathStack.push(paths);
      paths = Array.from(data[p]);
      route.push(p);
	    gain.push(path[1]);
	    continue;
    }
  } else {
    console.log("loop detected");
  }

  while (paths.length == 0) {
    route.pop();
	  gain.pop();
    if (pathStack.length > 0) {
      paths = pathStack.pop();
    } else {
      //console.log("bye");
      return;
    }
  }
} while (true)

})();

console.log(ans);

Score : 500 points

Problem Statement

There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.

We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

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

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.


//↓見なくていいよ！ここから--------------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error("\n");
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return 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){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(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;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var N = nextInt();
	var list = nextIntArray();
	for(var i = N - 1; i > 0; i--){
		if(list[i - 1] > list[i]){
			list[i - 1]--;
			if(list[i - 1] > list[i]){
				myout("No");
				return;
			}
		}
	}
	myout("Yes");
}

Score : 300 points

Problem Statement

There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i.

For each square, you will perform either of the following operations once:

Decrease the height of the square by 1.

Do nothing.

Determine if it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq H_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

If it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right, print Yes; otherwise, print No.

Sample Input 1

5
1 2 1 1 3

Sample Output 1

Yes

You can achieve the objective by decreasing the height of only the second square from the left by 1.

Sample Input 2

4
1 3 2 1

Sample Output 2

No

Sample Input 3

5
1 2 3 4 5

Sample Output 3

Yes

Sample Input 4

1
1000000000

Sample Output 4

Yes


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  var H = input[1].split(" ").map(i => parseInt(i));
  var H1=0;
  var ans="Yes";
  var max=0;
  for(var i=1;i<N;i++){
    if(H[i-1]-H[i]>=2){
      ans="No";
      break;
    }else if(H[i-1]-H[i]==1){
      if(H[i-1]-1>=max){
        max=H[i-1]-1;
      }else{
        ans="No";
        break;
      }
    }
  }

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

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


function Main(input){
  var N = input.split("\n")[0].trim();
  var H = input.split("\n")[1].split(" ");
  N = parseInt(N,10);
  if(H.length==1){
    console.log("Yes");
  }else{
  for(i=0;i<=(N-1);i++){
    H[i] = parseInt(H[i],10);
  }
  var a;
  var x = [];
  for(j=0;j<=(N-2);j++){
    a = H[j] <= H[j+1];
    x[j] = 1;
    if(a==false){
      H[j] = H[j] - 1;
      a =H[j] <= H[j+1];
      x[j] = 0;
      if(a==false){
        console.log("No");
        break;
      }
    }
  }
  //2週目
  var b;
  if(a==true){
    for(j=0;j<=(N-2);j++){
      b = H[j] <= H[j+1];
      if(b==false&&x[j]==1){
        H[j] = H[j] - 1;
        b =H[j] <= H[j+1];
        if(b==false){
          console.log("No");
          break;
        }
      }else if(b==false&&x[j]==0){
        console.log("No");
        break;
      }
    }
  }
  //確かめもOKならYES
  if(b==true){
    console.log("Yes");
  }
}
}
  Main(require('fs').readFileSync('/dev/stdin','utf8'));


function Main(args){

  const firstRow = args.split("\n")[0];
  const row = args.split("\n")[1].split(" ");

  for(var i = row.length -1; i > 0; i-- ){

    if( row[i-1] > row[i] ){
      row[i-1] -= 1;
    }
    if( row[i-1] > row[i] ){
      return console.log("No");
    }
  }

  console.log("Yes");
}

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


function Main(args){

  const firstRow = args.split("\n")[0];
  const row = args.split("\n")[1].split(" ");

  for(var i = row.length -1; i > 0; i-- ){

    if( row[i-1] <= row[i] ){
      continue;
    }
    // console.log( row[i-1] + "," + row[i] + ":" + String(row[i-1] > row[i]) );
    //
    console.log(row[i-1]);
    if( row[i-1] > row[i] ){
      row[i-1] -= 1;
    }
    console.log(row[i-1]);
    if( row[i-1] > row[i] ){
      return console.log("No");
    }
  }

  for(var i = 0; i < row.length; i++ ){
    if( row[i] > row[i+1] ){
      return console.log("No");
    }
  }
  console.log("Yes");
}

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


function Main(args){

  const firstRow = args.split("\n")[0];
  const row = args.split("\n")[1].split(" ");

  for(var i = row.length -2; i >= 0; i--){
    console.log(row[i]);
    if(row[i] > row[i+1]) {
      row[i] = row[i] - 1;
    }
  }

  for(var i = 0; i < row.length -1  ;i++){
    if( row[i+1] < row[i] ){
      return console.log("No");
    }
  }

  console.log("Yes");

}

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


function Main(args){

  const firstRow = args.split("\n")[0];
  const secondRow = args.split("\n")[1].split(" ");

  // console.log(firstRow);
  // console.log(secondRow);
  for(var i = 0; i < secondRow.length -1  ;i++){
    if( secondRow[i+1] - secondRow[i] < -1 ){
      return console.log("No");
    };
    if( secondRow[i+1] < secondRow[i] ){
      if( secondRow[i-1] > secondRow[i] -1){

      }else{
        secondRow[i] = secondRow[i] -1;
      }
    };
    // if( secondRow[i+1] - secondRow[i] === -1 ){
    //   secondRow[i] = secondRow[i] -1;
    //   if( secondRow[i-1] > secondRow[i]){
    //     return console.log("No");
    //   }
    // };
  }

  for(var i = 0; i < secondRow.length -1  ;i++){
    if( secondRow[i+1] < secondRow[i] ){
      return console.log("No");
    }
  }

  console.log("Yes");

}

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


'use strict';
const main = x => {
  const n = parseInt(x[0], 10);
  const h = x[1].split(' ').map(val => parseInt(val, 10));
  // console.log(n, h);
  let count = 0;
  let ans = 1;
  for(let i=0; i<n-1; i++) {
    if (h[i]-h[i+1]>2) ans = 0;
    else if (h[i]-h[i+1]==1) {
      if (count == 1) ans = 0;
      else count++;
    }
  }
  console.log(ans?'Yes':'No');

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


function Main(input) {
	var idata = input.split(/\s|\n/);
	var yousosuu = parseInt(idata[0]);
	var ndata = [];
	for(k=1;k<idata.length;k++){
		ndata.push(parseInt(idata[k]));
	}
	//左から順番に比較していって、もし左＞右なら左を一個下げる
	for(let i=1;i<ndata.length;i++){
		if(ndata[i-1]>ndata[i]){
			ndata[i-1]=ndata[i-1]-1;
		}
	}
	//新しいものが本当に改善しているか確かめる
	for(let j=1;j<ndata.length;j++){
		if(ndata[j-1]>ndata[j]){
			return "No";
		}
	}
	return "Yes";
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
    const args = input.split('\n');
    const N = args[0];
    const H = args[1].split(' ');
    var flag = 'Yes';
    var jadge = false;
    var array = [];

    for (var k=0; k < N ; k++) {
        array.push(parseInt(H[k], 10));
    }

    if(array[0] > 0) {
        array[0] = array[0] - 1;
    }

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

        if( array[i-1] < array[i] ){
            flag = 'Yes';
            array[i] = array[i] - 1;
        } else if (array[i-1] === array[i]) {
            flag = 'Yes';
        } else {
            if(array[i-1] - array[i] === 1) {
                flag = 'Yes';
            } else {
                flag = 'No';
            }
        }
        if (flag === 'No' ) break;
    }

    array.map((res) => {
        console.log(res);
    });

    console.log(flag);
}

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


'use strict'
function main(input) {
  input = input
    .trim()
    .split(/\s|\n/)
    .map(v => ~~v)
  const n = input.slice(0, 1)[0]
  const nums = input.slice(1)
  if (n === 1) {
    console.log('Yes')
    return
  }
  for (let i = 0; i < n - 1; i++) {
    const sub = nums[i + 1] - nums[i]
    if (sub >= 1) {
      nums[i + 1] -= 1
    } else if (sub === 0) {
      //
    } else {
      console.log('No')
      return
    }
  }
  console.log('Yes')
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'))


const lineList = require('fs').readFileSync('/dev/stdin','utf8').trim().split('\n')
const n = parseInt(lineList[0])
const hList = lineList[1].split(' ').map(e => parseInt(e))

var answer = 'Yes'
var mi = 0 // index of max value
for(var i in hList) {
  if(hList[mi] <= hList[i]) {
    mi = i
  }

  if(hList[mi] - hList[i] >= 2) {
    answer = 'No'
  }
}

console.log(answer)


'use strict';

function main(input) {
  const lines = input.split('\n');
  lines.pop();
    const n = parseInt(lines[0], 10);
    const array = lines[1];
    console.log(fn(n, array));
}

function fn(n, array) {
  const a = array.split(' ').map(v => parseInt(v, 10));
  let c = 0;
  let prev = -999999;
  while (c < n -1) {
    if (c > 0) {
      prev = a[c-1];
    }
    const current = a[c];
    if (current >= prev - 1) {
      return 'No';
    }
    c++;
  }
  return 'Yes';
}

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


"use strict"
function main(arg) {
    //最大は1000000
    var masuNum = parseInt(arg.trim().split("\n")[0]);
    var list = arg.trim().split("\n")[1].split(" ");

    var kotae = "Yes";

    if(masuNum != 1){
        for(var i = 0; i < masuNum ; i++){
            if(i + 1 != masuNum && i != 0){
            if(list[i-1] <= list[i] && list[i] <= list[i +1]){
                //なにもしない
            }else{
                list[i]--;
                if(list[i] < list[i +1] || list[i] == list[i +1]){
                    if(list[i-1] < list[i] || list[i-1] == list[i]){
                    }else{
                        kotae = "No";
                    }
                }else{
                    kotae = "No";
                }
            }
            }
            if(i == 0){
                list[i]--;
            }
        }
    }
    console.log(kotae);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input) {
    const args = input.split('\n');
    const N = args[0];
    const H = args[1].split(' ');
    var flag = 'NO';
    for(var i = 1; i < H.length ; i++) {
        var Hi = parseInt(H[i], 10);
        var Him = parseInt(H[i-1], 10);

        if( Him <= Hi ){
            flag = 'Yes'
        } else {
            if(Him - Hi === -1) {
                flag = 'Yes';
            } else {
                flag = 'No';
            }
        }
             if(flag === 'No') break;
    }

    console.log(flag);
}

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


"use strict"
function main(arg) {
    //最大は1000000
    var masuNum = parseInt(arg.trim().split("\n")[0]);
    var list = arg.trim().split("\n")[1].split(" ");

    var kotae = "Yes";

    if(masuNum != 1){
        for(var i = 0; i < masuNum ; i++){
            if(i + 1 != masuNum){
            if(list[i] < list[i +1] || list[i] == list[i +1]){
                //なにもしない
            }else{
                list[i]--;
                if(list[i] < list[i +1] || list[i] == list[i +1]){
                    if(list[i-1] < list[i] || list[i-1] == list[i]){
                    }else{
                        kotae = "No";
                    }
                }else{
                    kotae = "No";
                }
            }
            }
        }
    }
    console.log(kotae);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


var input = require("fs").readFileSync("/dev/stdin", "utf8").split("\n");
var total = parseInt(input[0], 10);
var nums = input[1].split(" ").map(function(num) {
  return parseInt(num, 10);
});

var can = true;

var prev = Math.MAX_VALUE;
for (var i = 0; i < total; i++) {
  console.log(prev, nums[i] - 1);
  if (prev < (nums[i] - 1)) {
    can = false;
    break;
  }
  prev = nums[i];
}

console.log(can ? 'Yes' : 'No');


function Main(input) {
  input = input.split('\n')
  var N = parseInt(input[0])
  var H = input[1].split(' ').map(str => parseInt(str))
  var Max = 0
  var flag = false

  for (var i = 0; i < N; i++) {
    if (H[i] > H[i + 1]) {
      H[i]--
      if (Max < H[i]) {
        flag = true
        break
      }
    }
    Max = H[i]
  }

  console.log(flag ? 'No' : 'Yes')
}

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


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
    input = input.split("\n");
    // 数値の配列を作る
    const numList0 = input[0].split(' ').map(x => parseInt(x, 10));
    const N = numList0[0];
    const HList = input[1].split(' ').map(x => parseInt(x, 10));

    var current = HList[0];
    var min = 0;
    var flag = true;
    for (var i = 1; i < N; i++) {
        var next = HList[i];
        if (current <= next) {
            min = current;
	        current = next;
        } else {
            var temp = current - 1;
            if (temp === next && min <= temp) {
                current = temp;
                min = current;
            } else {
                flag = false;
                break;
            }
        }
    }

    if (flag) {
        console.log('Yes');
    } else {
        console.log('No');
    }
}

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


var input = require("fs").readFileSync("/dev/stdin", "utf8").split("\n");
var total = parseInt(input[0], 10);
var nums = input[1].split(" ").map(function(num) { return parseInt(num, 10); });

let can = true;

let prev = Math.MAX_VALUE;
for (var i = 0; i < total; i++) {
  if ((prev + 1) < nums[i]) {
    can = false;
    break;
  }
  prev = nums[i];
}

console.log(can ? 'Yes' : 'No');


function Main(input) {
	input = input.split("\n");
	const N = parseInt(input[0])
	const Hs = input[1].split(" ").map(x => parseInt(x))

	var isPossible = true

	for(i=0; i < N; i++){
		if(i == 0){
			Hs[i] = Hs[i] - 1
		}else if(Hs[i] >= Hs[i+1]){
			if(Hs[i] - Hs[i+1] >= 2){
				isPossible = false
				break
			}else if(Hs[i-1] == Hs[i]){
				if(Hs[i] - Hs[i+1] == 1){
					isPossible = false
					break
				}
			}else{
				Hs[i] = Hs[i] - 1
			}
		}
	}

	if(isPossible){
		console.log("Yes")
	}else{
		console.log("No")
	}
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict';
function main(input) {
  const args = input.split(' '),
        L = parseInt(args[0]),
        R = parseInt(args[1]);
  let min = 2019;
  for (let i = L; i <= R-1 && i <= L+2018-1; ++i) {
    if (i % 2019 === 0 || (i+1) % 2019 === 0) {
      min = 0;
      break;
    } else {
      for (let j = i+1; j <= R && j <= L+2018; ++j) {
        let tmp = i*j % 2019;
        if (tmp < min) {
          min = tmp;
        }
      }
    }
  }
  console.log(min);
}

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

Score : 300 points

Problem Statement

You are given two non-negative integers L and R.
We will choose two integers i and j such that L \leq i < j \leq R.
Find the minimum possible value of (i \times j) \mbox{ mod } 2019.

Constraints

All values in input are integers.

0 \leq L < R \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

L R

Output

Print the minimum possible value of (i \times j) \mbox{ mod } 2019 when i and j are chosen under the given condition.

Sample Input 1

2020 2040

Sample Output 1

2

When (i, j) = (2020, 2021), (i \times j) \mbox{ mod } 2019 = 2.

Sample Input 2

4 5

Sample Output 2

20

We have only one choice: (i, j) = (4, 5).


var input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
var obj = {
  "list" : input,
  "index" : 0,
  "max" : input.length,
  "next" : function(){
    if(!this.hasNext()){throw "NoSuchElementException:次に要素は無いよ";}
    var returnObj = this.list[this.index];
    this.index++;
    return returnObj;
  },
  "hasNext" : function(){return (this.index < this.max);}
}
Main();
function next(){return obj.next();}
function hasNext(){return obj.hasNext();}
function myout(t){console.log(t);}//standard output
function myerr(t){console.error(t);}//standard error
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す　1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main(){
  var one = myconv(next(),4);
  var L = one[0];
  var R = one[1];
  L %= 2019;
  R %= 2019;
  var output = 2020;
  for(var i = L; i < R; i++){
    for(var j = i + 1; j <= R; j++){
      var tmp = (i * j) % 2019;
      output = Math.min(output, tmp);
    }
  }
  myout(output);
}


const main = (L,R) => {
    var result = Math.pow(10,9)

    if(R - L >= 2019) {
        return 0
    }else{
        const ll = L%2019
        const rr = R%2019
        if(ll>rr) {
            return 0
        }else{
            for(var i = L;i<R+1;i++) {
                for(var j = i+1;j<R+1;j++) {
                    result = Math.min(result,i*j% 2019)
                }
            }
            return result
        }
    }
}

const input = require('fs').readFileSync('/dev/stdin','utf8').split("\n")[0]
const LR = input.split(" ").map(i => Number(i))
console.log(main(LR[0],LR[1]))


"use strict";
const main = input => {
  input = input[0].split(' ').map(val => parseInt(val, 10));
  const l = input[0], r = input[1];
  // console.log(l, r);
  const ll = l%2019, rr = r%2019;
  let num = 2018;
  for(let i=ll; i<rr; i++) {
    for(let j=i+1; j<=rr; j++) {
      num = Math.min(num, (i*j)%2019);
    }
  }
  console.log(num);

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


"use strict";
const main = input => {
  input = input[0].split(' ').map(val => parseInt(val, 10));
  const l = input[0], r = input[1];
  // console.log(l, r);
  let num = 0;
  if (r > 2019) {
    if (l < 2019) {
      num = 2019*2020;
    } else {
      num = l*(l+1);
    }
    num = num%2019;
  } else {
    num = l*(l+1);
  }
  console.log(num);

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


'use strict'
function main(i) {
  i = i.trim().split(' ')
  const Y = 2019
  const R = Number(i[1])
  const L = Number(i[0])
  const diff = R - L

  const hasDivisible = diff - (R % Y)
  if (hasDivisible >= 0) {
    console.log(0)
  } else {
    let ans = -1
    for (let i = L; i < R; i++) {
      let n = (i * (i + 1)) % Y
      if (ans === -1 || n < ans) ans = n
    }
    console.log(ans)
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input){
  input = input.split("\n");
  inputStr = input[0].split(" ");
  const L = Number.parseInt(inputStr[0]);
  const R = Number.parseInt(inputStr[1]);

  var min = 2018;
  if ( L * R > 2019){
    if ( R - L < 2019) {
      const L2 = L % 2019;
      const R2 = R % 2019;

      for(var i1 = L; i1 < R; i1++){
        for(var i2 = i1+1 ; i2 < R+1 ; i2++){
          min = Math.min(min,i1 * i2 % 2019);
          if(min === 0) { break; }
        }
        if(min === 0) { break; }
      }
	  console.log(min);
    } else {
      console.log(0);
    }
  } else {
    //LとRの積が2019を超えないなら計算する必要がない
    console.log(L * (L+1));
  }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const L = parseInt(arg[0].split(" ")[0]);
    const R = parseInt(arg[0].split(" ")[1]);

    if(R - L + 1 >= 2019) {
        // 2つの数の差が2019以上のとき、必ず2019の倍数が存在するので0
        console.log(0);
    } else {
        const Lmod = L % 2019;
        const Rmod = R % 2019;

        let min = Infinity;

        for(let i=Lmod; i<Rmod; i++) {
            for(let k=parseInt(i)+1; k<=Rmod; k++) {
                min = Math.min((i * k) % 2019, min);
            }
        }

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


function Main(input) {
  var L = parseInt(input.split(" ")[0]);
  var R = parseInt(input.split(" ")[1]);
  var min = 2019;
  if((R - L) >= 2019){
    // console.log(0);
    //	return;
     }
  L = L % 2019;
  R = R % 2019;
  for(var i = L; i < R; i++){
    if(i % 2019 == 0){
       console.log(0);
    	return;
    }
    for(var j = i + 1; j <= R; j++){
      if(j % 2019 == 0){
         console.log(0);
    	return;
         }
      var cal = (i * j) % 2019;
      if(min > cal){
         min = cal;
        if(min == 0){
           console.log(min);
          return;
           }
      }
    }
  }
  console.log(min);
}

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


function main(input) {
  const inputList = input.split(/\s/).map(inp => formatNum(inp));
  const A = inputList[0];
  const B = inputList[1];
  const SET_NUM = 2019;
  const thresholdValue = Math.ceil(Math.sqrt(SET_NUM));
  var result = 0;
  if ((Math.floor(A % SET_NUM) === 0) || (Math.floor(A / SET_NUM) < Math.floor(B / SET_NUM))) {
    result = 0;
  } else if (A <= thresholdValue && thresholdValue < B) {
    const C = (thresholdValue * (thresholdValue + 1)) % SET_NUM;
    const D = (A * (A + 1)) % SET_NUM;
    if (C < D) {
      result = C;
    } else {
      result = D
    }
  } else {
    result = (A * (A + 1)) % SET_NUM;
  }
  console.log(result);
};

// 文字列を数値に変換
function formatNum(str) {
  return Number(str);
};

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


function main(input) {
  const inputList = input.split(/\s/).map(inp => formatNum(inp));
  const A = inputList[0];
  const B = inputList[1];
  const SET_NUM = 2019;
  const thresholdValue = Math.ceil(Math.sqrt(SET_NUM));
  var result;
  if ((Math.floor(A % SET_NUM) === 0) || (Math.floor(A / SET_NUM) < Math.floor(B / SET_NUM))) {
    result = 0;
  } else if (A <= thresholdValue && thresholdValue < B) {
    result = (thresholdValue * (thresholdValue + 1)) % SET_NUM;
  } else {
    result = (A * (A + 1)) % SET_NUM;
  }
  console.log(result);
};

// 文字列を数値に変換
function formatNum(str) {
  return Number(str);
};

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


'use strict'
function main(input) {
    const tmp = input.split(' ');
    const L = parseInt(tmp[0], 10);
    const R = parseInt(tmp[1], 10);

    const modNum = 2019;
    if (R - L + 1 >= modNum) {
        console.log(0);
    } else {
        const Lmod = L % modNum;
        const Rmod = R % modNum;

        let minimum = Infinity;
        for (let i = Lmod; i < Rmod; i++) {
            for (let k = i + 1; k <= Rmod; k++) {
                minimum = Math.min((i * k) % modNum, minimum);

            }
        }
        console.log(minimum);

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


function Main(input) {
  var tmp = input.split(' ')
  var L = tmp[0]
  var R = tmp[1]

  var result = 2019
  var temp = 0

  for (var i = 0; i < R - L; i++) {
    for (var j = 1; j < R - L - i + 2; j++) {
      var num1 = parseInt(L) + i
      var num2 = parseInt(L) + i + j
      temp = num1 * num2
      if (temp % 2019 < result) {
        result = temp % 2019
      }
    }
  }

  console.log('%d', result)
}

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


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

	if((L-R)>=2019){
		console.log('%d',0);
	}
	else{
		var ans = Infinity;
		var endFlag = False;
		for(var i=L; i<R; i++){
			var iTmp = i%2019;
			if(iTmp === 0){
				ans=0;
				endFlag=True;
			}
			for(var j=i+1; j<=L; j++){
				var jTmp = j%2019;
				if(jTmp === 0){
					ans=0;
					endFlag=True;
				}
				var rTmp = (iTmp*jTmp)%2019;
				if(rTmp<ans) ans=rTmp;
			}
			if(endFlag === True) break;
		}
		//出力
		console.log('%d',ans);
	}
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict'
function main(input) {
    const tmp = input.split(' ');
    const L = parseInt(tmp[0], 10);
    const R = parseInt(tmp[1], 10);

    if (R - L + 1 >= 2019) {
        console.log(0);
    } else {
        const Lmod = L % 2019;
        const Rmod = R % 2019;
        if (Lmod > Rmod) {
            console.log(0);
        } else {
            console.log(Lmod * (Lmod + 1));

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


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

    if(R-L >= 2019)
    {
        console.log(0)
        return
    }
    L2 = L % 2019
    R2 = R % 2019

    ans = 2019
    if(L2 >= R2){
        console.log(0)
        return
    }
    for(i=L2; i < R2; i++)
    {
        for(j=i+1; j <= R2; j++)
        {
            ans = Math.min(ans, (i * j) % 2019)
        }
    }
    console.log(ans)
}
  //*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
// Main("2018 2021\n");


"use strict";

const main = arg => {

  let L = arg.split(" ")[0] % 2019,
      R = arg.split(" ")[1] % 2019;
  let min = 2019;
  for(let i = L; i <= R; i++){
    for(let j = L; j <= R; j++){
      let num = (i*j) % 2019;
      if(num < min && i < j){
      	min = num;
      }
  	}
  }

  console.log(min);
}

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


function Main(input) {
  var L = parseInt(input.split(" ")[0]);
  var R = parseInt(input.split(" ")[1]);
  var min = 2020;

  for(var i = L; i < R; i++){
    if(i % 2019 == 0){
       console.log("0");
    	return;
    }
    for(var j = i + 1; j <= R; j++){
      if(j % 2019 == 0){
         console.log("0");
    	return;
         }
      var cal = (i * j) % 2019;
      if(min > cal){
         min = cal;
      }
    }
  }
  console.log(min);
}

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


const main = (inputs) => {
  var TW = 2019;
  var L = inputs[0].split(" ")[0]-0;
  var R = inputs[0].split(" ")[1]-0;
  var mods = [];
  for(var i=L;i<=R;i++){
    var val = i%TW;
    mods.push(i);
    if(val == 0){
      console.log(0);
      return;
    }
  }
  var ans = TW;
  for(var i=0;i<mods.length;i++)
  for(var j=i+1;j<mods.length;j++){
    ans = Math.min(ans, ((mods[i]%TW)*(mods[j]%TW)));
  }
  console.log(ans);

}

main(require('fs').readFileSync('/dev/stdin', 'UTF-8').trim().split("\n"));


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const L = parseInt(arg[0].split(" ")[0]);
    const R = parseInt(arg[0].split(" ")[1]);

    let answer = L;

    for(let i=L; i<=R; i++) {
        // ぴったりならそこ
        if(i % 2019 === 0) {
            answer = i;
            break;
        }
    }

    console.log((answer * (answer + 1)) % 2019);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


((input) => {
  const data = input.split('\n');
  const line1 = data[0].split(' ');
  const L = +line1[0];
  const R = +line1[1];
  console.log((L % 2019) * (R % 2019) % 2019);
})(
  require("fs").readFileSync("/dev/stdin", "utf8")
);


const main = (inputs) => {
  var TW = 2019;
  var L = inputs[0].split(" ")[0]-0;
  var R = inputs[0].split(" ")[1]-0;
  var lmod = L%TW;
  var rmod = R%TW;
  var mods = [];
  for(var i=L;i<=R;i++){
    var val = i%2019;
    mods.push(val);
    if(val == 0) break;
  }
  mods.sort((a,b)=>a-b);
  console.log(mods[0]*mods[1]);
}

main(require('fs').readFileSync('/dev/stdin', 'UTF-8').trim().split("\n"));


function Main(input) {
	var output = 0;
  if(input.length <= 2){
     console.log(output);
    return;
     }
  while(true){
        var breakFlag = true;
  for(var i = 0; i < input.length; i++){
    var a = input.slice(i , i + 1);
    var b = input.slice(i + 1, i + 2);
    var c = input.slice(i + 2, i + 3);
    if(a == "A" && b == "B" && c == "C"){
       output++;
       i = i + 2;
       breakFlag = false;
    }
  }
    if(breakFlag){
       break;
       }else{
         //console.log(output);
        input = input.replace(/ABC/g,"BCA");
       }
  }
  console.log(output);
}

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

Score : 600 points

Problem Statement

You are given a string s consisting of A, B and C.

Snuke wants to perform the following operation on s as many times as possible:

Choose a contiguous substring of s that reads ABC and replace it with BCA.

Find the maximum possible number of operations.

Constraints

1 \leq |s| \leq 200000

Each character of s is A, B and C.

Input

Input is given from Standard Input in the following format:

s

Output

Find the maximum possible number of operations.

Sample Input 1

ABCABC

Sample Output 1

3

You can perform the operations three times as follows: ABCABC → BCAABC → BCABCA → BCBCAA. This is the maximum result.

Sample Input 2

C

Sample Output 2

0

Sample Input 3

ABCACCBABCBCAABCB

Sample Output 3

6


function Main(stdin) {
  stdin = stdin.split('\n')
  const input = stdin[0].split('')
  let isChange = true
  const start = 0
  let count = 0
  while (isChange) {
    isChange = false
    for (let i = start; i < input.length; i++) {
      if (input[i] === 'A' && input[i + 1] === 'B' && input[i + 2]) {
        swap(input, i)
        count = count + 1
        isChange = true
        i = i + 1
      }
    }
  }
  console.log(count)
}

function swap(input, start) {
  input[start] = 'B'
  input[start + 1] = 'C'
  input[start + 2] = 'A'
}

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


var main = standardInput => {
  var s = standardInput;
  var count = 0;

  while (s.indexOf("ABC") !== -1) {
    var i = s.indexOf("ABC");
    var before = s.substr(0,i)
    var after = s.substr(i+3) || ""
    s = before + "BCA" + after;
    count += 1;
    // console.log(s)
  }
  console.log(count);
};

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


function main (input) {
  let count = 0;
  while(input.indexOf('ABC')>=0){
    let index = input.indexOf('ABC');
    let a = input.replace('ABC','BCA');
    count++;
    console.log(a,a.slice(index))
    input = a.slice(index);
  }
  console.log(count);
}
main(require('fs').readFileSync('/dev/stdin','utf8'));


var lines = [];
var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

rl.on('line', function (x) {
    lines.push(x);
});

rl.on('close', function () {
    var S = lines[0].split("");
    var ans = 0;

    for (var i = 0; i < S.length; i++) {
        if (S[i] === "A" && S[i + 1] === "B" && S[i + 2] === "C") {
            S[i] = "B"; S[i + 1] = "C"; S[i + 2] = "A"
            ans++; i += 2;
        }
    }
    var before = ans;

    for (var i = 0; i < S.length; i++) {
        if (S[i] === "A" && S[i + 1] === "B" && S[i + 2] === "C") {
            S[i] = "B"; S[i + 1] = "C"; S[i + 2] = "A"
            ans++; i += 2
        }
    }
    if (before === ans) { console.log(ans); return (0); }

    for (var i = 0; i < S.length; i++) {
        if (S[i] === "A" && S[i + 1] === "B" && S[i + 2] === "C") { ans++; }
    }

    console.log(ans);
});


function Main(input) {
    const S = input[0];

    var currentA = 0;
    var sum = 0;
    var prevB = false;

    for (var index = 0; index < S.length; index++) {
        var element = S.charAt(index);
        if(element === "A") {
            if(prevB) {
                currentA = 0;
            }
            currentA++;
        }else if(element === "B") {
            if(prevB) {
                currentA = 0;
            }
        } else {
            if(prevB) {
                sum += currentA;
            } else {
                currentA = 0;
            }
        }
        prevB = element === "B";
    }

    console.log(sum);

}

// 1行入力の場合
// Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());

// 改行で分割
// Main(require("fs").readFileSync("/dev/stdin", "utf8").trim().split(/\n/));

// 改行・空白で分割
Main(require("fs").readFileSync("/dev/stdin", "utf8").trim().split(/\n|\s/));


Score : 300 points

Problem Statement

You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

We will repeatedly perform the following operation until all the squares are black:

Every white square that shares a side with a black square, becomes black.

Find the number of operations that will be performed.
The initial grid has at least one black square.

Constraints

1 \leq H,W \leq 1000

A_{ij} is # or ..

The given grid has at least one black square.

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the number of operations that will be performed.

Sample Input 1

3 3
...
.#.
...

Sample Output 1

2

After one operation, all but the corners of the grid will be black. After one more operation, all the squares will be black.

Sample Input 2

6 6
..#..#
......
#..#..
......
.#....
....#.

Sample Output 2

3


'use strict';
class Queue {
    constructor(size) {
        this.arr = new Array(size);
        this.head = this.tail = 0;
    }
    is_full() {
        return this.head == (this.tail + 1) % this.arr.length;
    }
    push(v) {
        if (this.is_full()) {
            this.arr.length *= 2;
        }
        this.arr[this.tail] = v;
        this.tail = (this.tail + 1) % this.arr.length;
    }
    is_empty() {
        return this.head == this.tail;
    }
    pop() {
        if (this.is_empty()) {
            throw -1;
        }
        let v = this.arr[this.head];
        this.head = (this.head + 1) % this.arr.length;
        return v;
    }
    maxsize() {
        return this.arr.length;
    }
}
function main(input) {
    let lines = input.split('\n');
    let v = lines[0].split(' ').map((n) => parseInt(n));
    let h = v[0];
    let w = v[1];
    let c = [];
    let d = [];
    for (let i = 1; i < h + 1; i++) {
        c.push(lines[i]);
        d.push([]);
    }
    let q = new Queue(1000000000);
    for (let i = 0; i < h; i++) {
        for (let j = 0; j < w; j++) {
            if (c[i][j] == '#') {
                q.push([i, j]);
                d[i][j] = 0;
            }
            else {
                d[i][j] = -1;
            }
        }
    }
    let p = q.pop();
    let max = 0;
    const dx = [1, 0, -1, 0];
    const dy = [0, 1, 0, -1];
    while (true) {
        const xx = p[0];
        const yy = p[1];
        for (let i = 0; i < 4; i++) {
            let x = xx + dx[i];
            let y = yy + dy[i];
            if (x < 0 || x > h - 1 || y < 0 || w - 1 < y || d[x][y] >= 0) {
                continue;
            }
            if (c[x][y] == '.') {
                q.push([x, y]);
                let count = d[xx][yy] + 1;
                if (max < count) {
                    max = count;
                }
                d[x][y] = count;
            }
        }
        if (q.is_empty()) {
            break;
        }
        p = q.pop();
    }
    console.log(max);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


'use strict';
class Queue {
  constructor(size) {
    this.arr = new Array(size);
    this.head = this.tail = 0;
  }

  is_full() {
    return this.head == (this.tail + 1) % this.arr.length;
  }

  push(v) {
    if (this.is_full()) {
      this.arr.length *= 2;
    }
    this.arr[this.tail] = v;
    this.tail = (this.tail + 1) % this.arr.length;
  }

  is_empty() {
    return this.head == this.tail;
  }

  pop() {
    if (this.is_empty()) {
      throw -1;
    }
    let v = this.arr[this.head];
    this.head = (this.head + 1) % this.arr.length;
    return v;
  }

  maxsize() {
    return this.arr.length;
  }
}

function main(input) {
  let lines = input.split('\n')
  let v = lines[0].split(' ').map((n) => parseInt(n));
  let h = v[0];
  let w = v[1];
  let c = [];
  let d = [];
  for (let i = 1; i < h + 1; i++) {
    c.push(lines[i]);
    d.push([]);
  }
  let q = new Queue(1000000000);
  for (let i = 0; i < h; i++) {
    for (let j = 0; j < w; j++) {
      if (c[i][j] == '#') {
        q.push([i, j]);
        d[i][j] = 0;
      } else {
        d[i][j] = -1;
      }
    }
  }
  let p = q.pop();
  let max = 0;
  const dx = [1, 0, -1, 0];
  const dy = [0, 1, 0, -1];
  while (true) {
    const xx = p[0];
    const yy = p[1];
    for (let i =0; i < 4; i++) {
      let x = xx + dx[i];
      let y = yy + dy[i];
      if (x < 0 || x > h - 1 || y < 0 || w - 1 < y || d[x][y] >= 0) {
        continue;
      }
      if (c[x][y] == '.') {
        q.push([x, y]);
        let count = d[xx][yy] + 1;
        if (max < count) {
          max = count;
        }
        d[x][y] = count;
      }
    }
    if (q.is_empty()) {
      break;
    }
    p = q.pop();
  }
  console.log(max);
}

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


'use strict';
class Queue {
  constructor(size = 10000000) {
    this.arr = new Array(size);
    this.head = this.tail = 0;
  }

  is_full() {
    return this.head == (this.tail + 1) % this.arr.length;
  }

  push(v) {
    if (this.is_full()) {
      this.arr.length *= 2;
    }
    this.arr[this.tail] = v;
    this.tail = (this.tail + 1) % this.arr.length;
  }

  is_empty() {
    return this.head == this.tail;
  }

  pop() {
    if (this.is_empty()) {
      throw -1;
    }
    let v = this.arr[this.head];
    this.head = (this.head + 1) % this.arr.length;
    return v;
  }

  maxsize() {
    return this.arr.length;
  }
}

function main(input) {
  let lines = input.split('\n')
  let v = lines[0].split(' ').map((n) => parseInt(n));
  let h = v[0];
  let w = v[1];
  let c = [];
  let d = [];
  for (let i = 1; i < h + 1; i++) {
    c.push(lines[i]);
    d.push([]);
  }
  let q = new Queue;
  for (let i = 0; i < h; i++) {
    for (let j = 0; j < w; j++) {
      if (c[i][j] == '#') {
        q.push([i, j]);
        d[i][j] = 0;
      } else {
        d[i][j] = -1;
      }
    }
  }
  let p = q.pop();
  let max = 0;
  const dx = [1, 0, -1, 0];
  const dy = [0, 1, 0, -1];
  while (true) {
    const xx = p[0];
    const yy = p[1];
    for (let i =0; i < 4; i++) {
      let x = xx + dx[i];
      let y = yy + dy[i];
      if (x < 0 || x > h - 1 || y < 0 || w - 1 < y || d[x][y] >= 0) {
        continue;
      }
      if (c[x][y] == '.') {
        q.push([x, y]);
        const count = d[xx][yy] + 1;
        if (max < count) {
          max = count;
        }
        d[x][y] = count;
      }
    }
    if (q.is_empty()) {
      break;
    }
    p = q.pop();
  }
  console.log(max);
}

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


function returnNextStr(input, index, L, W) {
  var result = input.slice();
  if (index - 1 > -1) {
    result[index - 1] = '#';
  }
  if (index + 1 < L) {
    result[index + 1] = '#';
  }
  if (index - W > -1) {
    result[index - W] = '#';
  }
  if (index + W < L) {
    result[index + W] = '#';
  }

  return result;
}

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

  var result = 0;

  var tmp = input[0].split(" ");
  var H = parseInt(tmp[0], 10);
  var W = parseInt(tmp[1], 10);
  var L = H * W;
  var resltStr = '';
  for (var i = 0; i < H; i++) {
    resltStr += input[i + 1];
  }
  var resltArr = resltStr.split('');
  var tmpArr = resltArr.slice();
  while (resltArr.indexOf('.') != -1 && resltArr.indexOf('#') != -1) {
    for (var i = 0; i < L; i++) {
      if (resltArr[i] == '#') {
        tmpArr = returnNextStr(tmpArr, i, L, W);
      }
    }
    resltArr = tmpArr.slice();
    result++;
  }

  //出力
  console.log(result);
}


function returnNextStr(input, index, L, W) {
  let result = input.slice();
  if (index - 1 > -1) {
    result[index - 1] = '#';
  }
  console.log(result);
  if (index + 1 < L) {
    result[index + 1] = '#';
  }
  console.log(result);
  if (index - W > -1) {
    result[index - W] = '#';
  }
  console.log(result);
  if (index + W < L) {
    result[index + W] = '#';
  }

  return result;
}

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

  let result = 0;

  let tmp = input[0].split(" ");
  let H = parseInt(tmp[0], 10);
  let W = parseInt(tmp[1], 10);
  let L = H * W;
  let resltStr = '';
  for (let i = 0; i < H; i++) {
    resltStr += input[i + 1];
  }
  let resltArr = resltStr.split('');
  let tmpArr = resltArr.slice();
  while (resltArr.indexOf('.') != -1 && resltArr.indexOf('#') != -1) {
    for (let i = 0; i < L; i++) {
      if (resltArr[i] == '#') {
        tmpArr = returnNextStr(tmpArr, i, L, W);
      }
    }
    resltArr = tmpArr.slice();
    result++;
  }

  //出力
  console.log(result);
}


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

    var H = Number(lines[0].split(" ")[0]);
    var W = Number(lines[0].split(" ")[1]);

    lines.shift();

    var q = []

    for (var i = 0; i < H; i++) {
        for (var j = 0; j < W; j++) {
            if (lines[i][j] === "#") { q.push([i, j, 0]); }
        }
    }

    var max = 0; var count = 0;
    var m = Array(H).fill(-1).map(i => i = Array(W).fill(-1));

    while (q.length) {
        var a = q.shift();
        var y = a[0], x = a[1];
        count = a[2];

        if (m[y][x] !== -1) { continue; }

        m[y][x] = count;
        max = Math.max(max, count);

        if (y + 1 < H && lines[y + 1][x] === ".") { q.push([y + 1, x, count + 1]); }
        if (0 <= y - 1 && lines[y - 1][x] === ".") { q.push([y - 1, x, count + 1]); }
        if (x + 1 < W && lines[y][x + 1] === ".") { q.push([y, x + 1, count + 1]); }
        if (0 <= x - 1 && lines[y][x - 1] === ".") { q.push([y, x - 1, count + 1]); }
    }
    console.log(max);
}

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


function is_dark(A){
  var darks = [];
  for(var i=0;i<A.length;i++){
    line_set = new Set(A[i])
    if(line_set.size==1 && A[i][0]=='#'){continue;}
    if(line_set.size==2 || line_set.size==1 && A[i][0]=='.'){return false;}
  }
  return true;
}

function main(input){
  const lines = input.split('\n');
  const H = lines[0].split(' ').map(x => parseInt(x))[0];
  const W = lines[0].split(' ').map(x => parseInt(x))[1];
  var A=[];
  for(var i=0;i<H;i++){
    var line = lines[1+i].split('');
    A.push(line);
  }

//  console.log([H,W,A]);

  var result = 0;

  // get black
  var blacks = [];
  for(var i=0;i<A.length;i++){
    for(var j=0;j<A[0].length;j++){
      if(A[i][j]=='#'){blacks.push([i,j])}
    }
  }

  while(true){

    var darken_blacks=[]
    for(var i=0;i<blacks.length;i++){
      var c_black = blacks[i];
      x = c_black[1];
      y = c_black[0];

      if((y>0 && A[y-1][x]=='#')&&(x>0 && A[y][x-1]=='#')&&(x<A[0].length-1 && A[y][x+1]=='#')&&(y<A.length-1 && A[y+1][x]=='#')){continue;}

      if(y>0                            && A[y-1][x]=='.'){
        darken_blacks.push([y-1, x]);
        A[y-1][x]='#';
      }
      if(x>0                            && A[y][x-1]=='.'){
        darken_blacks.push([y, x-1]);
        A[y][x-1]='#';
      }
      if(x<A[0].length-1 && A[y][x+1]=='.'){
        darken_blacks.push([y, x+1]);
        A[y][x+1]='#';
      }
      if(y<A.length-1       && A[y+1][x]=='.'){
        darken_blacks.push([y+1, x]);
        A[y+1][x]='#';
      }
    }
    blacks = darken_blacks;

    if(blacks.length==0){break;}
//    console.log('==');
//    console.log(blacks);
//    console.log(blacks.length);
//    console.log(A);
    result++;
  }

  console.log(result);
}

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


function is_dark(A){
  var darks = [];
  for(var i=0;i<A.length;i++){
    line_set = new Set(A[i])
    if(line_set.size==1 && A[i][0]=='#'){continue;}
    if(line_set.size==2 || line_set.size==1 && A[i][0]=='.'){return false;}
  }
  return true;
}

function get_darken_blacks(A, blacks){
  var darken_blacks=[]
  for(var i=0;i<blacks.length;i++){
    var c_black = blacks[i];
    x = c_black[1];
    y = c_black[0];

    if((y>0 && A[y-1][x]=='#')&&(x>0 && A[y][x-1]=='#')&&(x<A[0].length-1 && A[y][x+1]=='#')&&(y<A.length-1 && A[y+1][x]=='#')){continue;}

    if(y>0                            && A[y-1][x]=='.'){
      darken_blacks.push([y-1, x]);
      A[y-1][x]='#';
    }
    if(x>0                            && A[y][x-1]=='.'){
      darken_blacks.push([y, x-1]);
      A[y][x-1]='#';
    }
    if(x<A[0].length-1 && A[y][x+1]=='.'){
      darken_blacks.push([y, x+1]);
      A[y][x+1]='#';
    }
    if(y<A.length-1       && A[y+1][x]=='.'){
      darken_blacks.push([y+1, x]);
      A[y+1][x]='#';
    }
  }
  return darken_blacks;
}

function get_blacks(A){
  blacks = [];
  for(var i=0;i<A.length;i++){
    for(var j=0;j<A[0].length;j++){
      if(A[i][j]=='#'){blacks.push([i,j])}
    }
  }
  return blacks;
}

function main(input){
  const lines = input.split('\n');
  const H = lines[0].split(' ').map(x => parseInt(x))[0];
  const W = lines[0].split(' ').map(x => parseInt(x))[1];
  var A=[];
  for(var i=0;i<H;i++){
    var line = lines[1+i].split('');
    A.push(line);
  }

//  console.log([H,W,A]);

  var result = 0;

  var blacks = get_blacks(A);

  if(A.length*A[0].length>500000){
    hoge;
  }else{return};

  if(blacks.length==1){
    var black = blacks[0];
    long_x = 0;
    long_y = 0;
    if(black[0] > H-1-black[0]){long_y = black[0]}else{long_y=H-1-black[0]}
    if(black[1] > W-1-black[1]){long_x = black[1]}else{long_x=W-1-black[1]}
  console.log(long_x+long_y);

    return;
  }

  while(!is_dark(A)){
    blacks = get_darken_blacks(A, blacks)
    //A=darken(A, blacks);
    //console.log('==');
    //console.log(blacks);
    //console.log(A);
    result+=1;
  }

  console.log(result);
}

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


function is_dark(A){
  var darks = [];
  for(var i=0;i<A.length;i++){
    line_set = new Set(A[i])
    if(line_set.size==1 && A[i][0]=='#'){continue;}
    if(line_set.size==2 || line_set.size==1 && A[i][0]=='.'){return false;}
  }
  return true;
}

function get_darken_blacks(A, blacks){
  var darken_blacks=[]
  for(var i=0;i<blacks.length;i++){
    var c_black = blacks[i];
    x = c_black[1];
    y = c_black[0];

    if((y>0 && A[y-1][x]=='#')&&(x>0 && A[y][x-1]=='#')&&(x<A[0].length-1 && A[y][x+1]=='#')&&(y<A.length-1 && A[y+1][x]=='#')){continue;}

    if(y>0                            && A[y-1][x]=='.'){
      darken_blacks.push([y-1, x]);
      A[y-1][x]='#';
    }
    if(x>0                            && A[y][x-1]=='.'){
      darken_blacks.push([y, x-1]);
      A[y][x-1]='#';
    }
    if(x<A[0].length-1 && A[y][x+1]=='.'){
      darken_blacks.push([y, x+1]);
      A[y][x+1]='#';
    }
    if(y<A.length-1       && A[y+1][x]=='.'){
      darken_blacks.push([y+1, x]);
      A[y+1][x]='#';
    }
  }
  return darken_blacks;
}

function get_blacks(A){
  blacks = [];
  for(var i=0;i<A.length;i++){
    for(var j=0;j<A[0].length;j++){
      if(A[i][j]=='#'){blacks.push([i,j])}
    }
  }
  return blacks;
}

function main(input){
  const lines = input.split('\n');
  const H = lines[0].split(' ').map(x => parseInt(x))[0];
  const W = lines[0].split(' ').map(x => parseInt(x))[1];
  var A=[];
  for(var i=0;i<H;i++){
    var line = lines[1+i].split('');
    A.push(line);
  }

//  console.log([H,W,A]);

  var result = 0;

  var blacks = get_blacks(A);

  if(blacks.length<100){
    hoge;
  }

  if(blacks.length==1){
    var black = blacks[0];
    long_x = 0;
    long_y = 0;
    if(black[0] > H-1-black[0]){long_y = black[0]}else{long_y=H-1-black[0]}
    if(black[1] > W-1-black[1]){long_x = black[1]}else{long_x=W-1-black[1]}
  console.log(long_x+long_y);

    return;
  }

  while(!is_dark(A)){
    blacks = get_darken_blacks(A, blacks)
    //A=darken(A, blacks);
    //console.log('==');
    //console.log(blacks);
    //console.log(A);
    result+=1;
  }

  console.log(result);
}

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


"use strict"

function main(arg) {
    arg = arg.trim().split("\n")
    arg.shift()
    var H = arg.length
    var W = arg[0].length
    var m1 = []
    for (var i = 0; i < arg.length; i++) {
        m1.push(arg[i].split(''))
    }
    var i = 0
    var slist = []
    for (var y = 0; y < H; y++) for (var x = 0; x < W; x++) {
        if (m1[y][x] === '#') {
            slist.push([y, x])
        }
    }
    var tmp = []
    for (var y = 0; y < H; y++) for (var x = 0; x < W; x++) {
        if (m1[y][x] === '.') {
            var minD = Number.MAX_SAFE_INTEGER
            for (var i = 0; i < slist.length; i++) {
                var _y = slist[i][0]
                var _x = slist[i][1]
                var d = Math.abs(_y - y) + Math.abs(_x - x)
                if (d < minD) {
                    minD = d
                }
            }
            tmp.push(minD)
        }
    }
    console.log(Math.max(...tmp))
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict";

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

var g_input = '';
process.stdin.on('data', function(chunk) {
    g_input += chunk;
});

process.stdin.on('end', function() {
    Main(g_input.split(/\r?\n/));
});

function Main(input) {

    const tokens = input[0].split(' ').map(function(value) { return parseInt(value, 10); });
    const h = tokens[0];
    const w = tokens[1];

    let a = new Array(h);
    for (let i = 0; i < h; i++) {
        a[i] = input[i + 1].split('');
    }

    let distanceMap = new Array(h);
    let blackCells = [];
    for (let i = 0; i < h; i++) {
        distanceMap[i] = new Array(w);
        for (let j = 0; j < w; j++) {
            if (a[i][j] === "#") {
                distanceMap[i][j] = 0;
                blackCells.push({x: i, y: j, distance: 0});
            } else {
                distanceMap[i][j] = Number.MAX_SAFE_INTEGER;
            }
        }
    }

    while (blackCells.length > 0) {
        const blackCell = blackCells.shift();
        const i = blackCell.x;
        const j = blackCell.y;
        const distance = blackCell.distance;
        if (i - 1 >= 0 && distanceMap[i - 1][j] > distance + 1) {
            distanceMap[i - 1][j] = distance + 1;
            blackCells.push({x: i - 1, y: j, distance: distance + 1});
        }

        if (i + 1 < h && distanceMap[i + 1][j] > distance + 1) {
            distanceMap[i + 1][j] = distance + 1;
            blackCells.push({x: i + 1, y: j, distance: distance + 1});
        }

        if (j - 1 >= 0 && distanceMap[i][j - 1] > distance + 1) {
            distanceMap[i][j - 1] = distance + 1;
            blackCells.push({x: i, y: j - 1, distance: distance + 1});
        }

        if (j + 1 < w && distanceMap[i][j + 1] > distance + 1) {
            distanceMap[i][j + 1] = distance + 1;
            blackCells.push({x: i, y: j + 1, distance: distance + 1});
        }
    }

    let ans = 0;
    for (let i = 0; i < h; i++) {
        for (let j = 0; j < w; j++) {
            if (ans < distanceMap[i][j]) {
                ans = distanceMap[i][j];
            }
        }
    }

    console.log(ans);

    return 0;
}


function Main(input) {
  input = input.split("\n");
  var H = parseInt(input[0].split(" ")[0]);
  var W = parseInt(input[0].split(" ")[1]);
  var A = new Array(H+2);
  var C = new Array();
  var C1=new Array(W+2).fill(".");
  A[0]=C1;
  for(var i=0;i<H;i++){
    var tmp=input[i+1].split("");
    for(var j=0;j<W;j++){
      if(tmp[j]=="."){
        C.push([i+1,j+1]);
      }
    }
    tmp.splice(0,0,".");
    tmp.push(".");
    A[i+1]=tmp;
  }
  A[H+1]=C1;

  var ans=0;
  var queue=new Array();
  while(C.length>0){
    ans++;
    for(var i=C.length-1;i>=0;i--){
      if(A[C[i][0]+1][C[i][1]]=="#"||A[C[i][0]-1][C[i][1]]=="#"||A[C[i][0]][C[i][1]+1]=="#"||A[C[i][0]][C[i][1]-1]=="#"){
        queue.push(C[i]);
        C.splice(i,1);
      }
    }
    for(var i=queue.length-1;i>=0;i--){
      A[queue[i][0]][queue[i][1]]="#";
      queue.splice(i,1);
    }
  }

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

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


function is_dark(A){
  var darks = [];
  for(var i=0;i<A.length;i++){
    line_set = new Set(A[i])
    darks.push
    if(line_set.size==2 || line_set.size==1 && A[i][0]=='.'){return false;}
  }
  return true;
}

function get_darken_blacks(A, blacks){
  var darken_blacks=[]
  for(var i=0;i<blacks.length;i++){
    var c_black = blacks[i];
    x = c_black[1];
    y = c_black[0];

    if(y>0                            && A[y-1][x]=='.'){darken_blacks.push([y-1, x])}
    if(x>0                            && A[y][x-1]=='.'){darken_blacks.push([y, x-1])}
    if(x<A[0].length-1 && A[y][x+1]=='.'){darken_blacks.push([y, x+1])}
    if(y<A.length-1       && A[y+1][x]=='.'){darken_blacks.push([y+1, x])}
  }
  return darken_blacks;
}

function darken(A, blacks){

  for(var i=0;i<blacks.length;i++){
    var c_black = blacks[i];
    x = c_black[1];
    y = c_black[0];
    A[y][x]='#';
  }
  return A;
}

function get_blacks(A){
  blacks = [];
  for(var i=0;i<A.length;i++){
    for(var j=0;j<A[0].length;j++){
      if(A[i][j]=='#'){blacks.push([i,j])}
    }
  }
  return blacks;
}

function main(input){
  const lines = input.split('\n');
  const H = lines[0].split(' ').map(x => parseInt(x))[0];
  const W = lines[0].split(' ').map(x => parseInt(x))[1];
  var A=[];
  for(var i=0;i<H;i++){
    var line = lines[1+i].split('');
    A.push(line);
  }

//  console.log([H,W,A]);

  var result = 0;

  var blacks = get_blacks(A);
  while(!is_dark(A)){
    blacks = get_darken_blacks(A, blacks)
    A=darken(A, blacks);
    //console.log('==');
    //console.log(blacks);
    //console.log(A);
    result++;
  }

  console.log(result);
}

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


// inputに入力データ全体が入る
function Main(input) {
    // 1行目がinput[0], 2行目がinput[1], …に入る
    input = input.split("\n");
    // 数値の配列を作る
    const numList0 = input[0].split(' ').map(x => parseInt(x, 10));
    const N = numList0[0];
    const aList = input[1].split(' ').map(x => parseInt(x, 10));

    const gcd = function(a, b) {
        if ( ! b) {
            return a;
        }

        return gcd(b, a % b);
    };

    const lList = [0];
    const rList = [0];
    var newL = 0;
    var newR = 0;
    for (var i = 0; i < N; i++) {
        newL = gcd(newL, aList[i]);
        lList.push(newL);
        newR = gcd(newR, aList[N - i - 1]);
        rList.unshift(newR);
    }

    var max = 0;
    for (var i = 0; i < N; i++) {
        var result = gcd(lList[i], rList[i + 1]);
        max = Math.max(max, result);
    }

    console.log(max);
}

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

Score : 300 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on the blackboard.

You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.

Find the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Output

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Sample Input 1

3
7 6 8

Sample Output 1

2

If we replace 7 with 4, the greatest common divisor of the three integers on the blackboard will be 2, which is the maximum possible value.

Sample Input 2

3
12 15 18

Sample Output 2

6

Sample Input 3

2
1000000000 1000000000

Sample Output 3

1000000000

We can replace an integer with itself.


function Main(input) {
	var inputArr = input.split("\n");
	var n = parseInt(inputArr[0]);
	var a = inputArr[1].split(" ");
    var max = 0;

    var b = a.filter(function (x, i, self) {
            return self.indexOf(x) === i;
        });
	for (var i = 0; i < n ; i++) {
      var ai = b.concat();
      ai.splice(i, 1);
      var g = gcd(ai);
      if (g > max) {
        max = g;
      }
    }
    console.log(max) ;
}
function gcd() {
  	var arg = arguments[0];
    var f = (a, b) => b ? f(b, a % b) : a;
    var ans = arg[0];
    for (var i = 1; i < arg.length; i++) {
        ans = f(ans, arg[i]);
    }
    return ans
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
	var inputArr = input.split("\n");
	var n = parseInt(inputArr[0]);
	var a = inputArr[1].split(" ");
    var max = 0;

    var b = a.filter(function (x, i, self) {
            return self.indexOf(x) === i;
        });
    var c = a.filter(function (x, i, self) {
            return self.indexOf(x) !== self.lastIndexOf(x);
        });
	for (var i = 0; i < n ; i++) {
      var ai = b.concat();
      ai.splice(i, 1);
      var g = gcd(ai);
      if (g > max) {
        max = g;
      }
    }
    console.log(max) ;
}
function gcd() {
  	var arg = arguments[0];
    var f = (a, b) => b ? f(b, a % b) : a;
    var ans = arg[0];
    for (var i = 1; i < arg.length; i++) {
        ans = f(ans, arg[i]);
    }
    return ans
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


//パラメータ値の最大公約数を求める式
function gcd(a, b) {
    if (b === 0){
        return a
    }
    return gcd(b, a % b)
}
//主処理
function Main(input){
  input = input.split("\n");
  inputStr = input[0].split(" ");
  var N = Number.parseInt(inputStr[0]);
  var A = input[1].split(" ");
　var i = 1;
  var modsum1 = Number.parseInt(A[0]);
  //最大公約数を求める
  for (i=1; i<N ; i++){
    modsum1 = gcd(modsum1, Number.parseInt(A[i]));
  }
  var modsum2 = 0;
  var modsum3 = 0;
  var i2 = 0;
  //特定の1文字を加えないで最大公約数を求め、その最大を記録する
  for (i=0; i<N ; i++){
    //console.log('-');
    for ( i2 = 0; i2 <N ; i2++) {
      if ( i <> i2 ) {
        if (modsum2 === 0){
          modsum2 = Number.parseInt(A[i2]);
        }
		modsum2 = gcd(modsum2, Number.parseInt(A[i2]));
        //console.log(modsum2);
      }
    }
    modsum3 = Math.max(modsum2,modsum3);
    modsum2 = 0;
  }
  //console.log("------");
  console.log(Math.max(modsum1,modsum3));
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


//パラメータ値の最大公約数を求める式
function gcd(a, b) {
    if (b === 0){
        return a
    }
    return gcd(b, a % b)
}
//主処理
function Main(input){
  input = input.split("\n");
  inputStr = input[0].split(" ");
  var N = Number.parseInt(inputStr[0]);
  var A = input[1].split(" ");
　var i = 1;
  var min = Number.parseInt(A[0]);
  var modsum1 = Number.parseInt(A[0]);
  //最大公約数を求める
  for (i=1; i<N ; i++){
    modsum1 = gcd(modsum1, Number.parseInt(A[i]));
    if (min > Number.parseInt(A[i])) {
      min = Number.parseInt(A[i]);
    }
  }
  var modsum2 = 0;
  var modsum3 = 0;
  var i2 = 0;
  //特定の1文字を加えないで最大公約数を求め、その最大を記録する
  for (i=0; i<N ; i++){
    //console.log('-');
	for ( i2 = 0; i2 <N ; i2++) {
      if ( i === i2 ) {
      } else {
        if (modsum2 === 0){
          modsum2 = Number.parseInt(A[i2]);
        }
		modsum2 = gcd(modsum2, Number.parseInt(A[i2]));
        //console.log(modsum2);
      }
    }
    modsum3 = Math.max(modsum2,modsum3);
    modsum2 = 0;
  }
  //console.log("------");
  console.log(Math.max(modsum1,modsum3));
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";

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

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

const gcd = (a, b) => (b ? gcd(b, a % b) : a);

if (N === 2) {
  console.log(Math.max(A[0], A[1]));
  return;
}

let sumFromL = [];
let sumFromR = [];

sumFromL[0] = A[0];
for (let i = 1; i < N; i++) {
  sumFromL[i] = gcd(sumFromL[i - 1], A[i]);
}

sumFromR[N - 1] = A[N - 1];
for (let i = N - 2; i >= 0; i--) {
  sumFromR[i] = gcd(sumFromR[i + 1], A[i]);
}

let gcds = [];
for (let i = 0; i < N; i++) {
  gcds[i] = gcd(sumFromL[i - 1] || 0, sumFromR[i + 1] || 0);
}

console.log(Math.max(...gcds));


function commonDiv (num1,num2) {
    "use strict";
  if(num1 < num2){
      let tmp = num1;
        num1 = num2;
        num2 = tmp;
  }
  let num3 = num1 % num2;
  if(num3 === 0) {
      return num2;
  } else {
      return commonDiv(num2, num3);
  }

}

function Main(input) {
    "use strict";
    const els = input.split('\n');
    const number = els[0];
    const values = els[1].split(' ');
    let output;
    let results = [];

    for (let i = 0; i < number-1 ; i++) {
        results.push(commonDiv(parseInt(values[i],10), parseInt(values[i+1],10)));
    }
    results.push(commonDiv(parseInt(values[0],10), parseInt(values[number-1],10)));

    let min = Math.min.apply(null, results);
    const newResults = results.filter(n => n != min);

    if(values.length === 2){
        output = commonDiv(parseInt(values[0],10), parseInt(values[1],10));
        console.log(output);
        return;
    }

    if(newResults.length === 0){
        output = min;
        console.log(output);
        return;
    }

    output = Math.min.apply(null,newResults);

    console.log(output);
}

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


"use strict";

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

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

let min = [0, 0];

const gcd = (a, b) => (b ? gcd(b, a % b) : a);

if (N === 2) {
  console.log(Math.max(A[0], A[1]));
  return;
}

const zeroOne = (gcd(A[0], A[1]));
const zeroTwo = (gcd(A[0], A[2]));
const oneTwo = (gcd(A[1], A[2]));

if (N === 3) {
  console.log(Math.max(zeroOne, zeroTwo, oneTwo));
  return;
}

min = [zeroOne, zeroTwo, oneTwo];
min.sort((a, b) => b - a);

for (let i = 4; i < N; i++) {
  const v = (gcd(min[0], A[i]));

  if (v < min[1]) {
    min[0] = min[1];
    min[1] = v;
  } else if (v < min[0]) {
    min[0] = v;
  }
}

console.log(min[0]);


// inputに入力データ全体が入る
function Main(input) {
  lines = input.split("\n")
  n = lines[0] * 1
  a = lines[1].split(' ').map(Number)
  ans = 0
  max = 0
  if (n == 2) {
    ans = Math.max(a[0], a[1])
  } else {
    for(var i = 0; i < a.length; i++) {
      if (i == 0) {
        g = a[1]
      } else {
        g = a[0]
      }
      for(var j = 0; j < a.length; j++) {
        if (g <= max) {
          break;
        }
        if (j == i) continue;
        g = gcd(a[j], g)
      }
      if (g > max) {
        max = g
      }
    }
  }
  if (max) {
    ans = max
  }
  console.log(ans);
}

function gcd(a, b) {
  if (b == 0) {
    return a;
  }
  return gcd(b, a % b)
}

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


'use strict'

function Main(input) {
    input = input.split("\n")
    let N = parseInt(input[0])
    let numbers = input[1].split(' ').map(str => parseInt(str, 10))

    const gcd = (x, y) => {
      while(y) {
        var t = y;
        y = x % y;
        x = t;
      }
      return x;
    }

    let max = 1
    for(let i = 0; i < N; i++) {
      let g = numbers[i+1] || numbers[i-1]

      for(let j = 0; j < N; j++) {
        if(j === i) {
          continue;
        }
        g = gcd(g, numbers[j])

        if(g <= max) {
          break;
        }
      }
       max = Math.max(max, g)
    }

    console.log(max)
}

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


"use strict";

var _constants = require("constants");

var hasN = true; // has N *only* line
var type = "b";
// a: 2D split
// b: space split
// c: line split
// z: other (only source)
function main(N, p, s) {
  // N, processed data, source
  var div = [];
  for (var i = 0; i < p.length; i++) {
    div.push(divisor(p[i]));
  }
  var a = new Set();
  div.forEach(function (e) {
    return e.forEach(function (z) {
      return a.add(z);
    });
  });
  var x = Array.from(a).sort(function (c, d) {
    return c - d;
  });
  var m = 1;
  for (var _i = x.length - 1; _i >= 0; _i--) {
    var count = 0;
    for (var j = 0; j < div.length; j++) {
      if (div[j].indexOf(x[_i]) >= 0) count++;
      if (j - count > 1) break;
    }
    if (count >= div.length - 1) {
      m = x[_i];
      break;
    }
  }
  console.log(m);
}
function common(a) {
  var line = a.split('\n').slice(0, a.split('\n').length - 1);
  if (hasN) var N = Number(line.shift());
  switch (type) {
    case "a":
      main(N, line.map(function (e) {
        return e.split(' ').map(function (ee) {
          return Number(ee);
        });
      }), a);
      break;
    case "b":
      main(N, line[0].split(' ').map(function (e) {
        return Number(e);
      }), a);
      break;
    case "c":
      main(N, line, a);
      break;
    case "z":
      main(N, null, a);
  }
}
function divisor(num) {
  var results = [];
  for (var i = 2; i <= num; i++) {
    if (num % i == 0) {
      results.push(i);
    }
  }
  return results;
}
common(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  var args = input.split('\n');
  var n = args.shift();
  var a = args.shift().split(' ').map(m => parseInt(m)).sort((a, b) => a - b);
  var minimum = a.shift();
  var a1 = a.map(m => euclid(minimum, m)).sort((a, b) => a - b)[a.length === 1 ? 0 : 1];
  minimum = a.shift();
  var a2 = 0;
  if (a.length > 0) {
    a2 = a.map(m => euclid(minimum, m)).sort((a, b) => a - b)[0];
  }
  console.log(a1 > a2 ? a1 : a2);
}

function euclid(u, v) {
  var r = 0;
  while (0 !== v) {
    r = u % v;
    u = v ;
    v = r;
  }
  return u;
}

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


function setUp(input) {
  input = input.split("\n");
  N = Number(input[0].split(" ")[0]);
  AList = input[1].split(" ").map(function (d, i) {
    return Number(d);
  });
  main();
}
function main() {
  lawList = [];
  numList = [];
  AList.forEach(function (d, index) {
    var tmp = [];
    var value = d;
    for (var i = 2; i <= value;) {
      if (value % i === 0) {
        tmp.push(i);
        value = value / i;
        if (numList.indexOf(i) < 0) {
          numList.push(i);
        }
      } else {
        i++;
      }
    }
    lawList.push(tmp);
  });
  numList.sort(function (a, b) {
    return a - b;
  })

  var commonList = [];
  var numLen = numList.length;
  for (var numI = 0; numI < numLen;) {
    var num = numList[numI];
    var count = 0;
    lawList.forEach(function (arr, i) {
      if (arr.indexOf(num) >= 0) {
        count++;
      }
    });
    if (count === N) {
      commonList.push(num);
      lawList.forEach(function (arr, i) {
        arr.splice(arr.indexOf(num), 1);
      });
    } else {
      numI++;
    }
  }
  var len = N - 1;
  var max = 1;
  for (var j = 0; j <= len; j++) {
    var tmpMax = 1;
    var pointerArray = [];
    for (var numI = 0; numI < numLen;) {
      var num = numList[numI];
      var count = 0;
      lawList.forEach(function (arr, i) {
        if (i !== j) {
          var pointer = arr.indexOf(num);
          if (pointer >= 0) {
            var currentPointer = pointerArray[i];
            if (currentPointer === undefined || pointer > currentPointer) {
              count++;
            }
          }
        }
      });
      if (count === len) {
        tmpMax = tmpMax * num;
        lawList.forEach(function (arr, i) {
          pointerArray[i] = arr.indexOf(num);
        });
      } else {
        numI++;
      }
    }
    if (max < tmpMax) {
      max = tmpMax;
    }
  }
  commonList.forEach(function (d, i) {
    max = max * d;
  })
  console.log(max);
}

setUp(require("fs").readFileSync("/dev/stdin", "utf8"));
// setUp('2\n1000000000 1000000000')
// setUp('3\n12 15 18')


function setUp(input) {
  input = input.split("\n");
  N = Number(input[0].split(" ")[0]);
  AList = input[1].split(" ").map(function (d, i) {
    return Number(d);
  });
  main();
}
function main() {
  lawList = [];
  numList = [];
  AList.forEach(function (d, index) {
    var tmp = [];
    var value = d;
    for (var i = 2; i <= value;) {
      if (value % i === 0) {
        tmp.push(i);
        value = value / i;
        if (numList.indexOf(i) < 0) {
          numList.push(i);
        }
      } else {
        i++;
      }
    }
    lawList.push(tmp);
  });
  var originLaw = JSON.stringify(lawList);
  var originNum = JSON.stringify(numList);
  var len = N - 1;
  var max = 1;
  for (var j = 0; j <= len; j++) {
    lawList = JSON.parse(originLaw);
    lawList.splice(j, 1);
    numList = JSON.parse(originNum);
    var list = [];
    while (numList.length) {
      var num = numList[0];
      var count = 0;
      lawList.forEach(function (arr, i) {
        if (arr.indexOf(num) >= 0) {
          count++;
        }
      });
      if (count === len) {
        list.push(num);
        lawList.forEach(function (arr, i) {
          arr.splice(arr.indexOf(num), 1);
        });
      } else {
        numList.shift();
      }
    }
    var num = 1;
    list.forEach(function (d, i) {
      num = num * d;
    });
    if (max < num) {
      max = num;
    }
  }

  console.log(max);
}

setUp(require("fs").readFileSync("/dev/stdin", "utf8"));
// setUp('2\n1000000000 1000000000')
// setUp('3\n12 15 18')


var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}
function gcd(a,b){return b?gcd(b,a%b):a;}

console.log(main());
function main(){
  var n = o.a();
  var a = o.l();
  var gcd0 = gcd(a[0],a[1]);
  var gcd1 = new Set([a[0],a[1]]);
  for(var i = 2; i < n; i++){
    var s = new Set();
    if(1 < gcd0){
      s.add(gcd0);
      gcd0 = gcd(gcd0, a[i]);
    }
    for(var j of gcd1){
      var t = gcd(j,a[i]);
      if(1 < t)s.add(t);
    }
    gcd1 = s;
  }
  var ans = 1;
  for(var i of gcd1)if(ans < i)ans = i;
  return ans;
}


"use strict";
function gcd(a) {
    var f = (a, b) => b ? f(b, a % b) : a;
    var ans = a[0];
    for (var i = 1; i < a.length; i++) {
        if (a[i] > 0) ans = f(ans, a[i]);
    }
    return ans;
}
function Main(input) {
    let cin = new Inputer(input);
    let N = cin.getInt();
    let A = cin.getIntArray(N);
    let max = 0;
    for (let n = 0; n < N; n++) {
        let c = A[n]; A[n] = 0;
        let w = gcd(A);
        if (max < w) max = w;
        A[n] = c;
    }
    console.log(max);
}
class Inputer{constructor(t){if(typeof t=='undefined')throw new Error('引数（stdin）を省略できません！');this.cnt=0,this.items=t.split(/\n|\s/)}getInt(){return this.items[this.cnt++]-0}getIntArray(t){if(typeof t=='undefined')throw new Error('引数（1以上）を省略できません！');let r=new Array(t);for(let e=0;e<t;e++)r[e]=this.getInt();return r}getStr(){return this.items[this.cnt++]}getStrArray(t){if(typeof t=='undefined')throw new Error('引数（1以上）を省略できません！');let r=new Array(t);for(let e=0;e<t;e++)r[e]=this.getStr();return r}}
if (typeof window == "undefined") Main(require("fs").readFileSync("/dev/stdin", "utf8"));