"use strict";
var bigInt = function (undefined) { "use strict"; var BASE = 1e7, LOG_BASE = 7, MAX_INT = 9007199254740992, MAX_INT_ARR = smallToArray(MAX_INT), LOG_MAX_INT = Math.log(MAX_INT); function Integer(v, radix) { if (typeof v === "undefined") return Integer[0]; if (typeof radix !== "undefined") return +radix === 10 ? parseValue(v) : parseBase(v, radix); return parseValue(v) } function BigInteger(value, sign) { this.value = value; this.sign = sign; this.isSmall = false } BigInteger.prototype = Object.create(Integer.prototype); function SmallInteger(value) { this.value = value; this.sign = value < 0; this.isSmall = true } SmallInteger.prototype = Object.create(Integer.prototype); function isPrecise(n) { return -MAX_INT < n && n < MAX_INT } function smallToArray(n) { if (n < 1e7) return [n]; if (n < 1e14) return [n % 1e7, Math.floor(n / 1e7)]; return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)] } function arrayToSmall(arr) { trim(arr); var length = arr.length; if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { switch (length) { case 0: return 0; case 1: return arr[0]; case 2: return arr[0] + arr[1] * BASE; default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE } } return arr } function trim(v) { var i = v.length; while (v[--i] === 0); v.length = i + 1 } function createArray(length) { var x = new Array(length); var i = -1; while (++i < length) { x[i] = 0 } return x } function truncate(n) { if (n > 0) return Math.floor(n); return Math.ceil(n) } function add(a, b) { var l_a = a.length, l_b = b.length, r = new Array(l_a), carry = 0, base = BASE, sum, i; for (i = 0; i < l_b; i++) { sum = a[i] + b[i] + carry; carry = sum >= base ? 1 : 0; r[i] = sum - carry * base } while (i < l_a) { sum = a[i] + carry; carry = sum === base ? 1 : 0; r[i++] = sum - carry * base } if (carry > 0) r.push(carry); return r } function addAny(a, b) { if (a.length >= b.length) return add(a, b); return add(b, a) } function addSmall(a, carry) { var l = a.length, r = new Array(l), base = BASE, sum, i; for (i = 0; i < l; i++) { sum = a[i] - base + carry; carry = Math.floor(sum / base); r[i] = sum - carry * base; carry += 1 } while (carry > 0) { r[i++] = carry % base; carry = Math.floor(carry / base) } return r } BigInteger.prototype.add = function (v) { var n = parseValue(v); if (this.sign !== n.sign) { return this.subtract(n.negate()) } var a = this.value, b = n.value; if (n.isSmall) { return new BigInteger(addSmall(a, Math.abs(b)), this.sign) } return new BigInteger(addAny(a, b), this.sign) }; BigInteger.prototype.plus = BigInteger.prototype.add; SmallInteger.prototype.add = function (v) { var n = parseValue(v); var a = this.value; if (a < 0 !== n.sign) { return this.subtract(n.negate()) } var b = n.value; if (n.isSmall) { if (isPrecise(a + b)) return new SmallInteger(a + b); b = smallToArray(Math.abs(b)) } return new BigInteger(addSmall(b, Math.abs(a)), a < 0) }; SmallInteger.prototype.plus = SmallInteger.prototype.add; function subtract(a, b) { var a_l = a.length, b_l = b.length, r = new Array(a_l), borrow = 0, base = BASE, i, difference; for (i = 0; i < b_l; i++) { difference = a[i] - borrow - b[i]; if (difference < 0) { difference += base; borrow = 1 } else borrow = 0; r[i] = difference } for (i = b_l; i < a_l; i++) { difference = a[i] - borrow; if (difference < 0) difference += base; else { r[i++] = difference; break } r[i] = difference } for (; i < a_l; i++) { r[i] = a[i] } trim(r); return r } function subtractAny(a, b, sign) { var value; if (compareAbs(a, b) >= 0) { value = subtract(a, b) } else { value = subtract(b, a); sign = !sign } value = arrayToSmall(value); if (typeof value === "number") { if (sign) value = -value; return new SmallInteger(value) } return new BigInteger(value, sign) } function subtractSmall(a, b, sign) { var l = a.length, r = new Array(l), carry = -b, base = BASE, i, difference; for (i = 0; i < l; i++) { difference = a[i] + carry; carry = Math.floor(difference / base); difference %= base; r[i] = difference < 0 ? difference + base : difference } r = arrayToSmall(r); if (typeof r === "number") { if (sign) r = -r; return new SmallInteger(r) } return new BigInteger(r, sign) } BigInteger.prototype.subtract = function (v) { var n = parseValue(v); if (this.sign !== n.sign) { return this.add(n.negate()) } var a = this.value, b = n.value; if (n.isSmall) return subtractSmall(a, Math.abs(b), this.sign); return subtractAny(a, b, this.sign) }; BigInteger.prototype.minus = BigInteger.prototype.subtract; SmallInteger.prototype.subtract = function (v) { var n = parseValue(v); var a = this.value; if (a < 0 !== n.sign) { return this.add(n.negate()) } var b = n.value; if (n.isSmall) { return new SmallInteger(a - b) } return subtractSmall(b, Math.abs(a), a >= 0) }; SmallInteger.prototype.minus = SmallInteger.prototype.subtract; BigInteger.prototype.negate = function () { return new BigInteger(this.value, !this.sign) }; SmallInteger.prototype.negate = function () { var sign = this.sign; var small = new SmallInteger(-this.value); small.sign = !sign; return small }; BigInteger.prototype.abs = function () { return new BigInteger(this.value, false) }; SmallInteger.prototype.abs = function () { return new SmallInteger(Math.abs(this.value)) }; function multiplyLong(a, b) { var a_l = a.length, b_l = b.length, l = a_l + b_l, r = createArray(l), base = BASE, product, carry, i, a_i, b_j; for (i = 0; i < a_l; ++i) { a_i = a[i]; for (var j = 0; j < b_l; ++j) { b_j = b[j]; product = a_i * b_j + r[i + j]; carry = Math.floor(product / base); r[i + j] = product - carry * base; r[i + j + 1] += carry } } trim(r); return r } function multiplySmall(a, b) { var l = a.length, r = new Array(l), base = BASE, carry = 0, product, i; for (i = 0; i < l; i++) { product = a[i] * b + carry; carry = Math.floor(product / base); r[i] = product - carry * base } while (carry > 0) { r[i++] = carry % base; carry = Math.floor(carry / base) } return r } function shiftLeft(x, n) { var r = []; while (n-- > 0) r.push(0); return r.concat(x) } function multiplyKaratsuba(x, y) { var n = Math.max(x.length, y.length); if (n <= 30) return multiplyLong(x, y); n = Math.ceil(n / 2); var b = x.slice(n), a = x.slice(0, n), d = y.slice(n), c = y.slice(0, n); var ac = multiplyKaratsuba(a, c), bd = multiplyKaratsuba(b, d), abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); trim(product); return product } function useKaratsuba(l1, l2) { return -.012 * l1 - .012 * l2 + 15e-6 * l1 * l2 > 0 } BigInteger.prototype.multiply = function (v) { var n = parseValue(v), a = this.value, b = n.value, sign = this.sign !== n.sign, abs; if (n.isSmall) { if (b === 0) return Integer[0]; if (b === 1) return this; if (b === -1) return this.negate(); abs = Math.abs(b); if (abs < BASE) { return new BigInteger(multiplySmall(a, abs), sign) } b = smallToArray(abs) } if (useKaratsuba(a.length, b.length)) return new BigInteger(multiplyKaratsuba(a, b), sign); return new BigInteger(multiplyLong(a, b), sign) }; BigInteger.prototype.times = BigInteger.prototype.multiply; function multiplySmallAndArray(a, b, sign) { if (a < BASE) { return new BigInteger(multiplySmall(b, a), sign) } return new BigInteger(multiplyLong(b, smallToArray(a)), sign) } SmallInteger.prototype._multiplyBySmall = function (a) { if (isPrecise(a.value * this.value)) { return new SmallInteger(a.value * this.value) } return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign) }; BigInteger.prototype._multiplyBySmall = function (a) { if (a.value === 0) return Integer[0]; if (a.value === 1) return this; if (a.value === -1) return this.negate(); return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign) }; SmallInteger.prototype.multiply = function (v) { return parseValue(v)._multiplyBySmall(this) }; SmallInteger.prototype.times = SmallInteger.prototype.multiply; function square(a) { var l = a.length, r = createArray(l + l), base = BASE, product, carry, i, a_i, a_j; for (i = 0; i < l; i++) { a_i = a[i]; carry = 0 - a_i * a_i; for (var j = i; j < l; j++) { a_j = a[j]; product = 2 * (a_i * a_j) + r[i + j] + carry; carry = Math.floor(product / base); r[i + j] = product - carry * base } r[i + l] = carry } trim(r); return r } BigInteger.prototype.square = function () { return new BigInteger(square(this.value), false) }; SmallInteger.prototype.square = function () { var value = this.value * this.value; if (isPrecise(value)) return new SmallInteger(value); return new BigInteger(square(smallToArray(Math.abs(this.value))), false) }; function divMod1(a, b) { var a_l = a.length, b_l = b.length, base = BASE, result = createArray(b.length), divisorMostSignificantDigit = b[b_l - 1], lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), remainder = multiplySmall(a, lambda), divisor = multiplySmall(b, lambda), quotientDigit, shift, carry, borrow, i, l, q; if (remainder.length <= a_l) remainder.push(0); divisor.push(0); divisorMostSignificantDigit = divisor[b_l - 1]; for (shift = a_l - b_l; shift >= 0; shift--) { quotientDigit = base - 1; if (remainder[shift + b_l] !== divisorMostSignificantDigit) { quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit) } carry = 0; borrow = 0; l = divisor.length; for (i = 0; i < l; i++) { carry += quotientDigit * divisor[i]; q = Math.floor(carry / base); borrow += remainder[shift + i] - (carry - q * base); carry = q; if (borrow < 0) { remainder[shift + i] = borrow + base; borrow = -1 } else { remainder[shift + i] = borrow; borrow = 0 } } while (borrow !== 0) { quotientDigit -= 1; carry = 0; for (i = 0; i < l; i++) { carry += remainder[shift + i] - base + divisor[i]; if (carry < 0) { remainder[shift + i] = carry + base; carry = 0 } else { remainder[shift + i] = carry; carry = 1 } } borrow += carry } result[shift] = quotientDigit } remainder = divModSmall(remainder, lambda)[0]; return [arrayToSmall(result), arrayToSmall(remainder)] } function divMod2(a, b) { var a_l = a.length, b_l = b.length, result = [], part = [], base = BASE, guess, xlen, highx, highy, check; while (a_l) { part.unshift(a[--a_l]); trim(part); if (compareAbs(part, b) < 0) { result.push(0); continue } xlen = part.length; highx = part[xlen - 1] * base + part[xlen - 2]; highy = b[b_l - 1] * base + b[b_l - 2]; if (xlen > b_l) { highx = (highx + 1) * base } guess = Math.ceil(highx / highy); do { check = multiplySmall(b, guess); if (compareAbs(check, part) <= 0) break; guess-- } while (guess); result.push(guess); part = subtract(part, check) } result.reverse(); return [arrayToSmall(result), arrayToSmall(part)] } function divModSmall(value, lambda) { var length = value.length, quotient = createArray(length), base = BASE, i, q, remainder, divisor; remainder = 0; for (i = length - 1; i >= 0; --i) { divisor = remainder * base + value[i]; q = truncate(divisor / lambda); remainder = divisor - q * lambda; quotient[i] = q | 0 } return [quotient, remainder | 0] } function divModAny(self, v) { var value, n = parseValue(v); var a = self.value, b = n.value; var quotient; if (b === 0) throw new Error("Cannot divide by zero"); if (self.isSmall) { if (n.isSmall) { return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)] } return [Integer[0], self] } if (n.isSmall) { if (b === 1) return [self, Integer[0]]; if (b == -1) return [self.negate(), Integer[0]]; var abs = Math.abs(b); if (abs < BASE) { value = divModSmall(a, abs); quotient = arrayToSmall(value[0]); var remainder = value[1]; if (self.sign) remainder = -remainder; if (typeof quotient === "number") { if (self.sign !== n.sign) quotient = -quotient; return [new SmallInteger(quotient), new SmallInteger(remainder)] } return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)] } b = smallToArray(abs) } var comparison = compareAbs(a, b); if (comparison === -1) return [Integer[0], self]; if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; if (a.length + b.length <= 200) value = divMod1(a, b); else value = divMod2(a, b); quotient = value[0]; var qSign = self.sign !== n.sign, mod = value[1], mSign = self.sign; if (typeof quotient === "number") { if (qSign) quotient = -quotient; quotient = new SmallInteger(quotient) } else quotient = new BigInteger(quotient, qSign); if (typeof mod === "number") { if (mSign) mod = -mod; mod = new SmallInteger(mod) } else mod = new BigInteger(mod, mSign); return [quotient, mod] } BigInteger.prototype.divmod = function (v) { var result = divModAny(this, v); return { quotient: result[0], remainder: result[1] } }; SmallInteger.prototype.divmod = BigInteger.prototype.divmod; BigInteger.prototype.divide = function (v) { return divModAny(this, v)[0] }; SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; BigInteger.prototype.mod = function (v) { return divModAny(this, v)[1] }; SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; BigInteger.prototype.pow = function (v) { var n = parseValue(v), a = this.value, b = n.value, value, x, y; if (b === 0) return Integer[1]; if (a === 0) return Integer[0]; if (a === 1) return Integer[1]; if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; if (n.sign) { return Integer[0] } if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); if (this.isSmall) { if (isPrecise(value = Math.pow(a, b))) return new SmallInteger(truncate(value)) } x = this; y = Integer[1]; while (true) { if (b & 1 === 1) { y = y.times(x); --b } if (b === 0) break; b /= 2; x = x.square() } return y }; SmallInteger.prototype.pow = BigInteger.prototype.pow; BigInteger.prototype.modPow = function (exp, mod) { exp = parseValue(exp); mod = parseValue(mod); if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); var r = Integer[1], base = this.mod(mod); while (exp.isPositive()) { if (base.isZero()) return Integer[0]; if (exp.isOdd()) r = r.multiply(base).mod(mod); exp = exp.divide(2); base = base.square().mod(mod) } return r }; SmallInteger.prototype.modPow = BigInteger.prototype.modPow; function compareAbs(a, b) { if (a.length !== b.length) { return a.length > b.length ? 1 : -1 } for (var i = a.length - 1; i >= 0; i--) { if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1 } return 0 } BigInteger.prototype.compareAbs = function (v) { var n = parseValue(v), a = this.value, b = n.value; if (n.isSmall) return 1; return compareAbs(a, b) }; SmallInteger.prototype.compareAbs = function (v) { var n = parseValue(v), a = Math.abs(this.value), b = n.value; if (n.isSmall) { b = Math.abs(b); return a === b ? 0 : a > b ? 1 : -1 } return -1 }; BigInteger.prototype.compare = function (v) { if (v === Infinity) { return -1 } if (v === -Infinity) { return 1 } var n = parseValue(v), a = this.value, b = n.value; if (this.sign !== n.sign) { return n.sign ? 1 : -1 } if (n.isSmall) { return this.sign ? -1 : 1 } return compareAbs(a, b) * (this.sign ? -1 : 1) }; BigInteger.prototype.compareTo = BigInteger.prototype.compare; SmallInteger.prototype.compare = function (v) { if (v === Infinity) { return -1 } if (v === -Infinity) { return 1 } var n = parseValue(v), a = this.value, b = n.value; if (n.isSmall) { return a == b ? 0 : a > b ? 1 : -1 } if (a < 0 !== n.sign) { return a < 0 ? -1 : 1 } return a < 0 ? 1 : -1 }; SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; BigInteger.prototype.equals = function (v) { return this.compare(v) === 0 }; SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; BigInteger.prototype.notEquals = function (v) { return this.compare(v) !== 0 }; SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; BigInteger.prototype.greater = function (v) { return this.compare(v) > 0 }; SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; BigInteger.prototype.lesser = function (v) { return this.compare(v) < 0 }; SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; BigInteger.prototype.greaterOrEquals = function (v) { return this.compare(v) >= 0 }; SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; BigInteger.prototype.lesserOrEquals = function (v) { return this.compare(v) <= 0 }; SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; BigInteger.prototype.isEven = function () { return (this.value[0] & 1) === 0 }; SmallInteger.prototype.isEven = function () { return (this.value & 1) === 0 }; BigInteger.prototype.isOdd = function () { return (this.value[0] & 1) === 1 }; SmallInteger.prototype.isOdd = function () { return (this.value & 1) === 1 }; BigInteger.prototype.isPositive = function () { return !this.sign }; SmallInteger.prototype.isPositive = function () { return this.value > 0 }; BigInteger.prototype.isNegative = function () { return this.sign }; SmallInteger.prototype.isNegative = function () { return this.value < 0 }; BigInteger.prototype.isUnit = function () { return false }; SmallInteger.prototype.isUnit = function () { return Math.abs(this.value) === 1 }; BigInteger.prototype.isZero = function () { return false }; SmallInteger.prototype.isZero = function () { return this.value === 0 }; BigInteger.prototype.isDivisibleBy = function (v) { var n = parseValue(v); var value = n.value; if (value === 0) return false; if (value === 1) return true; if (value === 2) return this.isEven(); return this.mod(n).equals(Integer[0]) }; SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; function isBasicPrime(v) { var n = v.abs(); if (n.isUnit()) return false; if (n.equals(2) || n.equals(3) || n.equals(5)) return true; if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; if (n.lesser(25)) return true } BigInteger.prototype.isPrime = function () { var isPrime = isBasicPrime(this); if (isPrime !== undefined) return isPrime; var n = this.abs(), nPrev = n.prev(); var a = [2, 3, 5, 7, 11, 13, 17, 19], b = nPrev, d, t, i, x; while (b.isEven()) b = b.divide(2); for (i = 0; i < a.length; i++) { x = bigInt(a[i]).modPow(b, n); if (x.equals(Integer[1]) || x.equals(nPrev)) continue; for (t = true, d = b; t && d.lesser(nPrev); d = d.multiply(2)) { x = x.square().mod(n); if (x.equals(nPrev)) t = false } if (t) return false } return true }; SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; BigInteger.prototype.isProbablePrime = function (iterations) { var isPrime = isBasicPrime(this); if (isPrime !== undefined) return isPrime; var n = this.abs(); var t = iterations === undefined ? 5 : iterations; for (var i = 0; i < t; i++) { var a = bigInt.randBetween(2, n.minus(2)); if (!a.modPow(n.prev(), n).isUnit()) return false } return true }; SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; BigInteger.prototype.modInv = function (n) { var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; while (!newR.equals(bigInt.zero)) { q = r.divide(newR); lastT = t; lastR = r; t = newT; r = newR; newT = lastT.subtract(q.multiply(newT)); newR = lastR.subtract(q.multiply(newR)) } if (!r.equals(1)) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); if (t.compare(0) === -1) { t = t.add(n) } if (this.isNegative()) { return t.negate() } return t }; SmallInteger.prototype.modInv = BigInteger.prototype.modInv; BigInteger.prototype.next = function () { var value = this.value; if (this.sign) { return subtractSmall(value, 1, this.sign) } return new BigInteger(addSmall(value, 1), this.sign) }; SmallInteger.prototype.next = function () { var value = this.value; if (value + 1 < MAX_INT) return new SmallInteger(value + 1); return new BigInteger(MAX_INT_ARR, false) }; BigInteger.prototype.prev = function () { var value = this.value; if (this.sign) { return new BigInteger(addSmall(value, 1), true) } return subtractSmall(value, 1, this.sign) }; SmallInteger.prototype.prev = function () { var value = this.value; if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); return new BigInteger(MAX_INT_ARR, true) }; var powersOfTwo = [1]; while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; function shift_isSmall(n) { return (typeof n === "number" || typeof n === "string") && +Math.abs(n) <= BASE || n instanceof BigInteger && n.value.length <= 1 } BigInteger.prototype.shiftLeft = function (n) { if (!shift_isSmall(n)) { throw new Error(String(n) + " is too large for shifting.") } n = +n; if (n < 0) return this.shiftRight(-n); var result = this; if (result.isZero()) return result; while (n >= powers2Length) { result = result.multiply(highestPower2); n -= powers2Length - 1 } return result.multiply(powersOfTwo[n]) }; SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; BigInteger.prototype.shiftRight = function (n) { var remQuo; if (!shift_isSmall(n)) { throw new Error(String(n) + " is too large for shifting.") } n = +n; if (n < 0) return this.shiftLeft(-n); var result = this; while (n >= powers2Length) { if (result.isZero() || result.isNegative() && result.isUnit()) return result; remQuo = divModAny(result, highestPower2); result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; n -= powers2Length - 1 } remQuo = divModAny(result, powersOfTwo[n]); return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0] }; SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; function bitwise(x, y, fn) { y = parseValue(y); var xSign = x.isNegative(), ySign = y.isNegative(); var xRem = xSign ? x.not() : x, yRem = ySign ? y.not() : y; var xDigit = 0, yDigit = 0; var xDivMod = null, yDivMod = null; var result = []; while (!xRem.isZero() || !yRem.isZero()) { xDivMod = divModAny(xRem, highestPower2); xDigit = xDivMod[1].toJSNumber(); if (xSign) { xDigit = highestPower2 - 1 - xDigit } yDivMod = divModAny(yRem, highestPower2); yDigit = yDivMod[1].toJSNumber(); if (ySign) { yDigit = highestPower2 - 1 - yDigit } xRem = xDivMod[0]; yRem = yDivMod[0]; result.push(fn(xDigit, yDigit)) } var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); for (var i = result.length - 1; i >= 0; i -= 1) { sum = sum.multiply(highestPower2).add(bigInt(result[i])) } return sum } BigInteger.prototype.not = function () { return this.negate().prev() }; SmallInteger.prototype.not = BigInteger.prototype.not; BigInteger.prototype.and = function (n) { return bitwise(this, n, function (a, b) { return a & b }) }; SmallInteger.prototype.and = BigInteger.prototype.and; BigInteger.prototype.or = function (n) { return bitwise(this, n, function (a, b) { return a | b }) }; SmallInteger.prototype.or = BigInteger.prototype.or; BigInteger.prototype.xor = function (n) { return bitwise(this, n, function (a, b) { return a ^ b }) }; SmallInteger.prototype.xor = BigInteger.prototype.xor; var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; function roughLOB(n) { var v = n.value, x = typeof v === "number" ? v | LOBMASK_I : v[0] + v[1] * BASE | LOBMASK_BI; return x & -x } function integerLogarithm(value, base) { if (base.compareTo(value) <= 0) { var tmp = integerLogarithm(value, base.square(base)); var p = tmp.p; var e = tmp.e; var t = p.multiply(base); return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 } } return { p: bigInt(1), e: 0 } } BigInteger.prototype.bitLength = function () { var n = this; if (n.compareTo(bigInt(0)) < 0) { n = n.negate().subtract(bigInt(1)) } if (n.compareTo(bigInt(0)) === 0) { return bigInt(0) } return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)) }; SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; function max(a, b) { a = parseValue(a); b = parseValue(b); return a.greater(b) ? a : b } function min(a, b) { a = parseValue(a); b = parseValue(b); return a.lesser(b) ? a : b } function gcd(a, b) { a = parseValue(a).abs(); b = parseValue(b).abs(); if (a.equals(b)) return a; if (a.isZero()) return b; if (b.isZero()) return a; var c = Integer[1], d, t; while (a.isEven() && b.isEven()) { d = Math.min(roughLOB(a), roughLOB(b)); a = a.divide(d); b = b.divide(d); c = c.multiply(d) } while (a.isEven()) { a = a.divide(roughLOB(a)) } do { while (b.isEven()) { b = b.divide(roughLOB(b)) } if (a.greater(b)) { t = b; b = a; a = t } b = b.subtract(a) } while (!b.isZero()); return c.isUnit() ? a : a.multiply(c) } function lcm(a, b) { a = parseValue(a).abs(); b = parseValue(b).abs(); return a.divide(gcd(a, b)).multiply(b) } function randBetween(a, b) { a = parseValue(a); b = parseValue(b); var low = min(a, b), high = max(a, b); var range = high.subtract(low).add(1); if (range.isSmall) return low.add(Math.floor(Math.random() * range)); var length = range.value.length - 1; var result = [], restricted = true; for (var i = length; i >= 0; i--) { var top = restricted ? range.value[i] : BASE; var digit = truncate(Math.random() * top); result.unshift(digit); if (digit < top) restricted = false } result = arrayToSmall(result); return low.add(typeof result === "number" ? new SmallInteger(result) : new BigInteger(result, false)) } var parseBase = function (text, base) { var length = text.length; var i; var absBase = Math.abs(base); for (var i = 0; i < length; i++) { var c = text[i].toLowerCase(); if (c === "-") continue; if (/[a-z0-9]/.test(c)) { if (/[0-9]/.test(c) && +c >= absBase) { if (c === "1" && absBase === 1) continue; throw new Error(c + " is not a valid digit in base " + base + ".") } else if (c.charCodeAt(0) - 87 >= absBase) { throw new Error(c + " is not a valid digit in base " + base + ".") } } } if (2 <= base && base <= 36) { if (length <= LOG_MAX_INT / Math.log(base)) { var result = parseInt(text, base); if (isNaN(result)) { throw new Error(c + " is not a valid digit in base " + base + ".") } return new SmallInteger(parseInt(text, base)) } } base = parseValue(base); var digits = []; var isNegative = text[0] === "-"; for (i = isNegative ? 1 : 0; i < text.length; i++) { var c = text[i].toLowerCase(), charCode = c.charCodeAt(0); if (48 <= charCode && charCode <= 57) digits.push(parseValue(c)); else if (97 <= charCode && charCode <= 122) digits.push(parseValue(c.charCodeAt(0) - 87)); else if (c === "<") { var start = i; do { i++ } while (text[i] !== ">"); digits.push(parseValue(text.slice(start + 1, i))) } else throw new Error(c + " is not a valid character") } return parseBaseFromArray(digits, base, isNegative) }; function parseBaseFromArray(digits, base, isNegative) { var val = Integer[0], pow = Integer[1], i; for (i = digits.length - 1; i >= 0; i--) { val = val.add(digits[i].times(pow)); pow = pow.times(base) } return isNegative ? val.negate() : val } function stringify(digit) { if (digit <= 35) { return "0123456789abcdefghijklmnopqrstuvwxyz".charAt(digit) } return "<" + digit + ">" } function toBase(n, base) { base = bigInt(base); if (base.isZero()) { if (n.isZero()) return { value: [0], isNegative: false }; throw new Error("Cannot convert nonzero numbers to base 0.") } if (base.equals(-1)) { if (n.isZero()) return { value: [0], isNegative: false }; if (n.isNegative()) return { value: [].concat.apply([], Array.apply(null, Array(-n)).map(Array.prototype.valueOf, [1, 0])), isNegative: false }; var arr = Array.apply(null, Array(+n - 1)).map(Array.prototype.valueOf, [0, 1]); arr.unshift([1]); return { value: [].concat.apply([], arr), isNegative: false } } var neg = false; if (n.isNegative() && base.isPositive()) { neg = true; n = n.abs() } if (base.equals(1)) { if (n.isZero()) return { value: [0], isNegative: false }; return { value: Array.apply(null, Array(+n)).map(Number.prototype.valueOf, 1), isNegative: neg } } var out = []; var left = n, divmod; while (left.isNegative() || left.compareAbs(base) >= 0) { divmod = left.divmod(base); left = divmod.quotient; var digit = divmod.remainder; if (digit.isNegative()) { digit = base.minus(digit).abs(); left = left.next() } out.push(digit.toJSNumber()) } out.push(left.toJSNumber()); return { value: out.reverse(), isNegative: neg } } function toBaseString(n, base) { var arr = toBase(n, base); return (arr.isNegative ? "-" : "") + arr.value.map(stringify).join("") } BigInteger.prototype.toArray = function (radix) { return toBase(this, radix) }; SmallInteger.prototype.toArray = function (radix) { return toBase(this, radix) }; BigInteger.prototype.toString = function (radix) { if (radix === undefined) radix = 10; if (radix !== 10) return toBaseString(this, radix); var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; while (--l >= 0) { digit = String(v[l]); str += zeros.slice(digit.length) + digit } var sign = this.sign ? "-" : ""; return sign + str }; SmallInteger.prototype.toString = function (radix) { if (radix === undefined) radix = 10; if (radix != 10) return toBaseString(this, radix); return String(this.value) }; BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString() }; BigInteger.prototype.valueOf = function () { return parseInt(this.toString(), 10) }; BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; SmallInteger.prototype.valueOf = function () { return this.value }; SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; function parseStringValue(v) { if (isPrecise(+v)) { var x = +v; if (x === truncate(x)) return new SmallInteger(x); throw new Error("Invalid integer: " + v) } var sign = v[0] === "-"; if (sign) v = v.slice(1); var split = v.split(/e/i); if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); if (split.length === 2) { var exp = split[1]; if (exp[0] === "+") exp = exp.slice(1); exp = +exp; if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); var text = split[0]; var decimalPlace = text.indexOf("."); if (decimalPlace >= 0) { exp -= text.length - decimalPlace - 1; text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1) } if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); text += new Array(exp + 1).join("0"); v = text } var isValid = /^([0-9][0-9]*)$/.test(v); if (!isValid) throw new Error("Invalid integer: " + v); var r = [], max = v.length, l = LOG_BASE, min = max - l; while (max > 0) { r.push(+v.slice(min, max)); min -= l; if (min < 0) min = 0; max -= l } trim(r); return new BigInteger(r, sign) } function parseNumberValue(v) { if (isPrecise(v)) { if (v !== truncate(v)) throw new Error(v + " is not an integer."); return new SmallInteger(v) } return parseStringValue(v.toString()) } function parseValue(v) { if (typeof v === "number") { return parseNumberValue(v) } if (typeof v === "string") { return parseStringValue(v) } return v } for (var i = 0; i < 1e3; i++) { Integer[i] = new SmallInteger(i); if (i > 0) Integer[-i] = new SmallInteger(-i) } Integer.one = Integer[1]; Integer.zero = Integer[0]; Integer.minusOne = Integer[-1]; Integer.max = max; Integer.min = min; Integer.gcd = gcd; Integer.lcm = lcm; Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger }; Integer.randBetween = randBetween; Integer.fromArray = function (digits, base, isNegative) { return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative) }; return Integer }();
"use strict";
function main(input) {
    const X = bigInt(input.replace("\n", ""));
    let cur = bigInt(100);
    let ans = 0;
    while (cur < X) {
        ans++;
        cur = cur.add(cur.divide(100));
    }
    console.log(ans);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 200 points

Problem Statement

Takahashi has a deposit of 100 yen (the currency of Japan) in AtCoder Bank.

The bank pays an annual interest rate of 1 % compounded annually. (A fraction of less than one yen is discarded.)

Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach X yen or above for the first time?

Constraints

101 \le X \le 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X

Output

Print the number of years it takes for Takahashi's balance to reach X yen or above for the first time.

Sample Input 1

103

Sample Output 1

3

The balance after one year is 101 yen.

The balance after two years is 102 yen.

The balance after three years is 103 yen.

Thus, it takes three years for the balance to reach 103 yen or above.

Sample Input 2

1000000000000000000

Sample Output 2

3760

Sample Input 3

1333333333

Sample Output 3

1706


function main(input) {
  let x = parseInt(input[0]);
  let money = 100;

  let i;
  for(i=0;money<x;i++){
    money = Math.floor(money + money/100);
  }
  console.log(i);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"));

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

Submitted source-code file size, in bytes.

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

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


function Main(input){
  input = input.split(' ').map(x=>BigInt(x));
  var a = input[0];
  var b = input[1];
  var n = input[2];
  if (b==1){
    var max = a*n
  }else if (n<b){
    var max = a*n/b - a*(n/b);
  }else{
    var border = (n+1n)/b;
    var t = 1n;
    var max = 0n;
    for (let t = 1n;t<=border;t++){
      var now = a*(b*t-1n)/b - a*((b*t-1n)/b);
      if (now > max){
        max = now;
      }
    }
  }
  console.log(max.toString())
}

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

Score : 400 points

Problem Statement

Given are integers A, B, and N.

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

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

Constraints

1 ≤ A ≤ 10^{6}

1 ≤ B ≤ 10^{12}

1 ≤ N ≤ 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B N

Output

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

Sample Input 1

5 7 4

Sample Output 1

2

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

Sample Input 2

11 10 9

Sample Output 2

9


"use strict";

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

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

    let answer = 0;
    let prev = 0;

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

        if(prev > temp) {
            break;
        }

        answer = Math.max(answer, temp);
        prev = temp;
    }

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

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

    //         answer = Math.max(answer, temp);

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

    //         answer = Math.max(answer, temp);

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

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


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

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

Score : 500 points

Problem Statement

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

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

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

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

Constraints

1 \leq M

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

Input

Input is given from Standard Input in the following format:

N M

Output

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

a_1 b_1
a_2 b_2
:
a_M b_M

Sample Input 1

4 1

Sample Output 1

2 3

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

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

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

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

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

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

Sample Input 2

7 3

Sample Output 2

1 6
2 5
3 4


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

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


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

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

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

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

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

}

function Main(sc) {

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

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

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

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

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

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

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

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

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

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

Score : 600 points

Problem Statement

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

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

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

Constraints

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

1 \leq a_i \leq 10^9

1 \leq u_i , v_i \leq N

u_i \neq v_i

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

1
2
3
3
4
4
5
2
2
3

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


function Main(input) {
	var str = input;
	str = str.split("\n")[0];
    str = str.split(' ');
    s = Number(str[0]);
    w = Number(str[1]);
	if(s<=w){
  		console.log("unsafe");
	}else{
		console.log("safe");
	}
}
 //*おまじない
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

There are S sheep and W wolves.

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

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

Constraints

1 \leq S \leq 100

1 \leq W \leq 100

Input

Input is given from Standard Input in the following format:

S W

Output

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

Sample Input 1

4 5

Sample Output 1

unsafe

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

Sample Input 2

100 2

Sample Output 2

safe

Many a sheep drive away two wolves.

Sample Input 3

10 10

Sample Output 3

unsafe


function Main(input) {
	input = input.split(" ");
	var tHP = parseInt(input[0], 10);
	var tAT = parseInt(input[1], 10);
	var aHP = parseInt(input[2], 10);
	var aAT = parseInt(input[3], 10);

while(true){
aHP =  aHP  -  tAT
if ( aHP <= 0 ){console.log('yes'); return}
tHP =  tHP  -  aAT
if ( tHP <= 0 ){console.log('No'); return}

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


function main(input) {
    input = input.trim().split("\n").slice(1);
    var arr = new Set(input);
    console.log(arr.size);
}

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

Score : 300 points

Problem Statement

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

How many kinds of items did you get?

Constraints

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

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

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

Print the number of kinds of items you got.

Sample Input 1

3
apple
orange
apple

Sample Output 1

2

You got two kinds of items: apple and orange.

Sample Input 2

5
grape
grape
grape
grape
grape

Sample Output 2

1

Sample Input 3

4
aaaa
a
aaa
aa

Sample Output 3

4


process.stdin.resume();
process.stdin.setEncoding('utf8');
var lines = [];
var reader = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});
reader.on('line', (line) => {
    lines.push(line);
});
reader.on('close', () => {
    lines.shift();
    const set = new Set();
    lines.forEach(e => set.add(e));
    console.log(set.size);
});


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

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

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

reader.on('close', () => {
 var tmp = lines[0].split(' ');
 var n = Number(tmp[0]);
 var m = Number(tmp[1]);
 var day = lines[1].split(' ');
 for(i=0; i<m; i++){
   n -= Number(day[i]);
 }

 if(n < 0){
   n = -1;
 }

 console.log(n);
});

Score : 200 points

Problem Statement

Takahashi has N days of summer vacation.

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

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

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

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

Constraints

1 \leq N \leq 10^6

1 \leq M \leq 10^4

1 \leq A_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 ... A_M

Output

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

Sample Input 1

41 2
5 6

Sample Output 1

30

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

Sample Input 2

10 2
5 6

Sample Output 2

-1

He cannot finish his assignments.

Sample Input 3

11 2
5 6

Sample Output 3

0

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

Sample Input 4

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

Sample Output 4

9


const Main = input => {
  const sp = input.split('\n');
  const M = sp.shift().split(' ').map(e => Number(e));
  const N = M.shift();
  const A_list = sp[0].split(' ').map(e => Number(e));

  let sum = 0;
  for(let A of A_list) sum += A;
  const rest = N - sum;
  const result = rest > -1 ? rest : -1;
  console.log(result);
};

Main(require('fs').readFileSync('/dev/stdin'. 'utf8'));
/*Main(`41 2
5 6`)
Main(`10 2
5 6`)
Main(`11 2
5 6`)
Main(`314 15
9 26 5 35 8 9 79 3 23 8 46 2 6 43 3`)*/


const main = (input) => {
  const args = input.split(' ').map(v => Number(v))
  const n = args[0] + 1
  const k = args[1]
  const max = n - k + 1
  let sum = 0
  for (let i = 0; i < max; i++) {
    sum += (max - i) * (max - i + 1) / 2
  }
  console.log(sum % (10 ** 9 + 7))
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'))


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

}
Main()

Score : 200 points

Problem Statement

Let us define the FizzBuzz sequence a_1,a_2,... as follows:

If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}.

If the above does not hold but 3 divides i, a_i=\mbox{Fizz}.

If none of the above holds but 5 divides i, a_i=\mbox{Buzz}.

If none of the above holds, a_i=i.

Find the sum of all numbers among the first N terms of the FizzBuzz sequence.

Constraints

1 \leq N \leq 10^6

Input

Input is given from Standard Input in the following format:

N

Output

Print the sum of all numbers among the first N terms of the FizzBuzz sequence.

Sample Input 1

15

Sample Output 1

60

The first 15 terms of the FizzBuzz sequence are:

1,2,\mbox{Fizz},4,\mbox{Buzz},\mbox{Fizz},7,8,\mbox{Fizz},\mbox{Buzz},11,\mbox{Fizz},13,14,\mbox{FizzBuzz}

Among them, numbers are 1,2,4,7,8,11,13,14, and the sum of them is 60.

Sample Input 2

1000000

Sample Output 2

266666333332

Watch out for overflow.


function Main(input) {
  const num = parseInt(input);
  if(num % 15 === 0) {
    console.log("FizzBuzz");
  } else if(num % 3 === 0) {
    console.log("Fizz");
  } else if(num % 5 === 0) {
    console.log("Buzz");
  } else {
    console.log(num);
  }
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


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

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

  for (let i = 1; i < N; i++) {
    if (Math.floor(i%3) === 0 && Math.floor(i%5) === 0) {
      continue;
    } else if (Math.floor(i % 3) === 0 || Math.floor(i % 5) === 0) {
      continue;
    } else {
      sum += i;
    }
  }
  p(sum);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";

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

    const a1 = n % k;
    const a2 = a1 - k < 0 ? -(a1 - k) : a1 - k;

    console.log((a1 <= a2 ? a1 : a2).toString());
};

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

Score : 300 points

Problem Statement

Given any integer x, Aoki can do the operation below.

Operation: Replace x with the absolute difference of x and K.

You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.

Constraints

0 ≤ N ≤ 10^{18}

1 ≤ K ≤ 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible value taken by N after Aoki does the operation zero or more times.

Sample Input 1

7 4

Sample Output 1

1

Initially, N=7.

After one operation, N becomes |7-4| = 3.

After two operations, N becomes |3-4| = 1, which is the minimum value taken by N.

Sample Input 2

2 6

Sample Output 2

2

N=2 after zero operations is the minimum.

Sample Input 3

1000000000000000000 1

Sample Output 3

0


var fs = require("fs");
var buffer = fs.readFileSync(0); // STDIN_FILENO = 0
var inputs = buffer.toString().split(' ').map(v => parseInt(v));

function solve(N, K){
  var x = N % K;
  var kHalf = K / 2;
  while(x > kHalf){
    x = Math.abs(x - K)
  }
  console.log(x)
}

solve(inputs[0], inputs[1]);


"use strict"
function main(arg) {
    var tmp = arg.trim().split("\n")[0].split(" ").map(Number)
    var N = tmp[0]
    var K = tmp[1]
    // var x = N
    // for (var i = 0; i < 1000; i++) {
    //     var t = Math.abs(x - K)
    //     if (t < x) {
    //         x = t
    //     } else {
    //         break
    //     }
    // }
    var npk = N % K
    // console.log(x)
    // console.log(npk)
    console.log(
        Math.min(npk, Math.abs(npk - K))
    )
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input) {
  const inputs = input.split('\n')
  const [K] = inputs[0].split(' ').map(Number)
  // console.log(K)
  const a = [1,2,3,4,5,6,7,8,9]
  let p = 0
  while(true) {
    // console.log(K, p, a.length, a)
    if (K <= a.length) {
      // console.log('OK:', K, a.length)
      console.log(a[K - 1])
      return
    }
    const len = a.length
    for(let i = p; i < len; i++) {
      for (let j = -1; j <= 1; j++) {
        let k = String(a[i])
        let d = a[i] % 10 + j
        if (d < 10 && 0 <= d) {
          const nn = k + String((a[i] % 10) + j)
          a.push(Number(nn))
        }
      }
      p++
    }
  }
  // console.log(a)
  // console.log('finished')
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 400 points

Problem Statement

A positive integer X is said to be a lunlun number if and only if the following condition is satisfied:

In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most 1.

For example, 1234, 1, and 334 are lunlun numbers, while none of 31415, 119, or 13579 is.

You are given a positive integer K. Find the K-th smallest lunlun number.

Constraints

1 \leq K \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the answer.

Sample Input 1

15

Sample Output 1

23

We will list the 15 smallest lunlun numbers in ascending order:

1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
21,
22,
23.

Thus, the answer is 23.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

13

Sample Output 3

21

Sample Input 4

100000

Sample Output 4

3234566667

Note that the answer may not fit into the 32-bit signed integer type.


"use strict";

const main = (input) => {
    const spi = input.split('\n');
    const s = spi[0];
    if (s[2] === s[3] && s[4] === s[5])
        console.log("Yes");
    else
        console.log("No");
};

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

Score : 100 points

Problem Statement

A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal.

Given a string S, determine whether it is coffee-like.

Constraints

S is a string of length 6 consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is coffee-like, print Yes; otherwise, print No.

Sample Input 1

sippuu

Sample Output 1

Yes

In sippuu, the 3-rd and 4-th characters are equal, and the 5-th and 6-th characters are also equal.

Sample Input 2

iphone

Sample Output 2

No

Sample Input 3

coffee

Sample Output 3

Yes


function main(input) {
  function dist(a, b) {
		return Math.min(b-a, Math.abs(x-a)+Math.abs(y-b)+1);
	}

  const inp = input.split(' ');
	const n = inp[0];
	const x = inp[1];
	const y = inp[2];

  for(let i=1;i<n; i++) {
    let cnt = 0;

    for(let a=1; a<n; a++)
      for(let b=a+1; b<=n; b++)
        if(dist(a,b) == i)
          cnt++;

    console.log(cnt);
  }
}

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


const main = (inputs) => {
  if (inputs[0] == inputs[1]) {
    console.log('No');
    return false;
  }
  if (inputs[2] != inputs[3]) {
    console.log('No');
    return false;
  }
  if (inputs[4] != inputs[5]) {
    console.log('No');
    return false;
  }
  console.log('Yes');
}
main(require('fs').readFileSync('/dev/stdin', 'UTF-8').trim().split("\n"));


"use strict";

const main = arg => {

    const input = arg.trim();

    const N = parseInt(input);
    var big = N / 500;
    var small = (N - big * 500) / 5;
    console.log(big*1000 + small * 5);

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

Score : 200 points

Problem Statement

Takahashi loves gold coins. He gains 1000 happiness points for each 500-yen coin he has and gains 5 happiness points for each 5-yen coin he has. (Yen is the currency of Japan.)

Takahashi has X yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn?

(We assume that there are six kinds of coins available: 500-yen, 100-yen, 50-yen, 10-yen, 5-yen, and 1-yen coins.)

Constraints

0 \leq X \leq 10^9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the maximum number of happiness points that can be earned.

Sample Input 1

1024

Sample Output 1

2020

By exchanging his money so that he gets two 500-yen coins and four 5-yen coins, he gains 2020 happiness points, which is the maximum number of happiness points that can be earned.

Sample Input 2

0

Sample Output 2

0

He is penniless - or yenless.

Sample Input 3

1000000000

Sample Output 3

2000000000

He is a billionaire - in yen.


"use strict";

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

    let distances = []

    // 区間を作る
    for(let i=0; i<N; i++) {
        let distance;

        if(parseInt(i) === N - 1) {
            distance = (K - A[i]) + A[0];
        } else {
            distance = A[parseInt(i) + 1] - A[i];
        }

        distances.push(distance);
    }

    const sum = distances.reduce((m,n)=>m+n);
    let answer = sum - distances.sort((a,b)=>b-a)[0];

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

Score : 300 points

Problem Statement

There is a circular pond with a perimeter of K meters, and N houses around them.

The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond.

When traveling between these houses, you can only go around the pond.

Find the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Constraints

2 \leq K \leq 10^6

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

0 \leq A_1 < ... < A_N < K

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K N
A_1 A_2 ... A_N

Output

Print the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Sample Input 1

20 3
5 10 15

Sample Output 1

10

If you start at the 1-st house and go to the 2-nd and 3-rd houses in this order, the total distance traveled will be 10.

Sample Input 2

20 3
0 5 15

Sample Output 2

10

If you start at the 2-nd house and go to the 1-st and 3-rd houses in this order, the total distance traveled will be 10.


function Main(input) {
    input = input.split("\n");
  	var pre=input[0].split(" ");
  	var distance=parseInt(pre[0],10);
  	var count=parseInt(pre[1],10);
  	var minute=input[1].split(" ");
  	var array=[];
    for(var i=0;i<count-1;i++){
      var s=i+1;
      var num=parseInt(minute[s],10)-parseInt(minute[i],10);
      array.push(num);
    }
  	var k=count-1;
  	var last=distance+parseInt(minute[0],10)-parseInt(minute[k],10);
  	array.push(last);
  	array.sort(
  		function(x,y){
    	return (x < y ? -1 : 1);
  		}
	);
  	var total=0;
  	for(var j=0:j<count-1;j++){
      total+=array[j];
    }
  	console.log(total);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict"
function main(arg) {
    var k = arg.trim().split("\n")[0].split(" ").map(Number)[0]
    var a = arg.trim().split("\n")[1].split(" ").map(Number).sort((a,b) => {
        return a-b
    })
    var sum = 0
    var max = 0
    for (var i = 0; i < a.length; i++) {
        var last_index = i - 1
        var x = 0
        var y = 0
        x = a[i]
        if (i === 0) {
            last_index = a.length - 1
            y = a[last_index]
            x = k + a[0]
        } else {
            y = a[last_index]
        }
        var diff = Math.abs(x - y)
        // console.log([x,y])
        // console.log(diff)
        max = Math.max(diff, max)
        // sum +=
        sum += diff
    }
    console.log(sum - max)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict";
function Main(input) {
  input = input.split("\n");
  var volume=input/3*input/3*input/3;
  console.log(volume);
}

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

Score : 300 points

Problem Statement

Given is a positive integer L.
Find the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.

Constraints

1 ≤ L ≤ 1000

L is an integer.

Input

Input is given from Standard Input in the following format:

L

Output

Print the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.
Your output is considered correct if its absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

3

Sample Output 1

1.000000000000

For example, a rectangular cuboid whose dimensions are 0.8, 1, and 1.2 has a volume of 0.96.

On the other hand, if the dimensions are 1, 1, and 1, the volume of the rectangular cuboid is 1, which is greater.

Sample Input 2

999

Sample Output 2

36926037.000000000000


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

  var L = parseInt( input );
  var l = L / 3;

  console.log( ( l * l * l ) );
}

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


const main = (inputs) => {
  var numArray = inputs[1].split(" ");
  var numArrayCopy = numArray.slice(0, numArray.length);
  var count = 0;
  var set = new Set(numArrayCopy);
  var setToArr = Array.from(set);
  for (var i = 0; i < numArray.length; i++) {
    numArrayCopy[i] = 0;
    var count = 0;
    for (var j = 0; j < setToArr.length; j++) {
      count = count + numArrayCopy.filter(function (x) {
        return x === setToArr[j]
      }).length;
    }
    numArrayCopy = numArray.slice(0, numArray.length);
    console.log(count - 1);
  }
}
main(require('fs').readFileSync('/dev/stdin', 'UTF-8').trim().split("\n"));

Score : 400 points

Problem Statement

We have N balls. The i-th ball has an integer A_i written on it.

For each k=1, 2, ..., N, solve the following problem and print the answer.

Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.

Constraints

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

1 \leq A_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

For each k=1,2,...,N, print a line containing the answer.

Sample Input 1

5
1 1 2 1 2

Sample Output 1

2
2
3
2
3

Consider the case k=1 for example. The numbers written on the remaining balls are 1,2,1,2.

From these balls, there are two ways to choose two distinct balls so that the integers written on them are equal.

Thus, the answer for k=1 is 2.

Sample Input 2

4
1 2 3 4

Sample Output 2

0
0
0
0

No two balls have equal numbers written on them.

Sample Input 3

5
3 3 3 3 3

Sample Output 3

6
6
6
6
6

Any two balls have equal numbers written on them.

Sample Input 4

8
1 2 1 4 2 1 4 1

Sample Output 4

5
7
5
7
7
5
7
5


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

/***/ "./src/ABC159/D.js":
/*!*************************!*\
  !*** ./src/ABC159/D.js ***!
  \*************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs */ \"fs\");\n/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__);\n\n\nfunction permutation(n, r) {\n  for (var i = 0, res = 1; i < r; i++) {\n    res *= n - i;\n  }\n\n  return res;\n}\n\nfunction combination(n, r) {\n  return permutation(n, r) / permutation(r, r);\n} // const permutation = (nums, k) => {\n//   let ans = [];\n//   if (nums.length < k) {\n//     return [];\n//   }\n//   if (k === 1) {\n//     for (let i = 0; i < nums.length; i++) {\n//       ans[i] = [nums[i]];\n//     }\n//   } else {\n//     for (let i = 0; i < nums.length; i++) {\n//       let parts = nums.slice(0);\n//       parts.splice(i, 1)[0];\n//       let row = permutation(parts, k - 1);\n//       for (let j = 0; j < row.length; j++) {\n//         if (nums[i] === row[j][0]) {\n//           ans.push([nums[i]].concat(row[j]));\n//         }\n//       }\n//     }\n//   }\n//   return ans.length;\n// };\n// const combination = (nums, k) => {\n//   let counter = 0;\n//   for (let i = 0; i < nums.length; i++) {\n//     for (let j = i + 1; j < nums.length; j++) {\n//       if (nums[i] !== nums[j]) continue;\n//       counter++;\n//     }\n//   }\n//   return counter;\n// };\n\n\nvar main = function main(input) {\n  var lines = input.split('\\n');\n  var N = lines[0];\n  var cccc = {};\n  var As = lines[1].split(' ').map(function (i) {\n    return i - 0;\n  });\n\n  for (var i = 0; i < As.length; i++) {\n    var Bs = As.slice();\n    Bs.splice(i, 1);\n\n    if (cccc[Bs.sort().join()]) {\n      console.log(cccc[Bs.sort().join()]);\n      continue;\n    }\n\n    var cache = {};\n\n    for (var j = 0, jl = Bs.length; j < jl; j++) {\n      if (cache[Bs[j]]) {\n        cache[Bs[j]]++;\n      } else {\n        cache[Bs[j]] = 1;\n      }\n    }\n\n    var sum = 0;\n\n    for (var _i = 0, _Object$keys = Object.keys(cache); _i < _Object$keys.length; _i++) {\n      var e = _Object$keys[_i];\n      sum += combination(cache[e], 2);\n    }\n\n    cccc[Bs.sort().join()] = sum;\n    console.log(sum);\n  }\n};\n\nmain(fs__WEBPACK_IMPORTED_MODULE_0__[\"readFileSync\"]('/dev/stdin', 'utf8'));\n\n//# sourceURL=webpack:///./src/ABC159/D.js?");

/***/ }),

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

eval("module.exports = require(\"fs\");\n\n//# sourceURL=webpack:///external_%22fs%22?");

/***/ })

/******/ });


function Main(input) {
  var h = parseInt(input[0],10);
  var w = parseInt(input[1], 10);
  var r = h * w;

  // 偶数
  if(r % 2 === 0) {
    console.log(r/2);
  } else {
    // 奇数
    var a = r/2;
    console.log(Math.ceil(a));
  }
}

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

Score : 200 points

Problem Statement

We have a board with H horizontal rows and W vertical columns of squares.
There is a bishop at the top-left square on this board.
How many squares can this bishop reach by zero or more movements?

Here the bishop can only move diagonally.
More formally, the bishop can move from the square at the r_1-th row (from the top) and the c_1-th column (from the left) to the square at the r_2-th row and the c_2-th column if and only if exactly one of the following holds:

r_1 + c_1 = r_2 + c_2

r_1 - c_1 = r_2 - c_2

For example, in the following figure, the bishop can move to any of the red squares in one move:

Constraints

1 \leq H, W \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H \ W

Output

Print the number of squares the bishop can reach.

Sample Input 1

4 5

Sample Output 1

10

The bishop can reach the cyan squares in the following figure:

Sample Input 2

7 3

Sample Output 2

11

The bishop can reach the cyan squares in the following figure:

Sample Input 3

1000000000 1000000000

Sample Output 3

500000000000000000


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

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var s = "abcdefghijklmnopqrstuvwxyz";
  var output = [];
  dfs([], 0);
  output.sort();
  myout(myconv(output, 9));

  function dfs(list, max){
    if(list.length == N){
      output.push(list.join(""));
      return;
    }
    for(var i = 0; i <= max; i++){
      var tmp = makeClone(list);
      tmp.push(s[i]);
      dfs(tmp, Math.max(max, s.indexOf(s[i]) + 1));
    }
  }
}

Score : 400 points

Problem Statement

In this problem, we only consider strings consisting of lowercase English letters.

Strings s and t are said to be isomorphic when the following conditions are satisfied:

|s| = |t| holds.

For every pair i, j, one of the following holds:

s_i = s_j and t_i = t_j.

s_i \neq s_j and t_i \neq t_j.

For example, abcac and zyxzx are isomorphic, while abcac and ppppp are not.

A string s is said to be in normal form when the following condition is satisfied:

For every string t that is isomorphic to s, s \leq t holds. Here \leq denotes lexicographic comparison.

For example, abcac is in normal form, but zyxzx is not since it is isomorphic to abcac, which is lexicographically smaller than zyxzx.

You are given an integer N.
Print all strings of length N that are in normal form, in lexicographically ascending order.

Constraints

1 \leq N \leq 10

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Assume that there are K strings of length N that are in normal form: w_1, \ldots, w_K in lexicographical order.
Output should be in the following format:

w_1
:
w_K

Sample Input 1

1

Sample Output 1

a

Sample Input 2

2

Sample Output 2

aa
ab


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

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

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

/***/ }),

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

"use strict";
/* WEBPACK VAR INJECTION */(function(module) {
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.main = void 0;
const fs_1 = __importDefault(__webpack_require__(/*! fs */ "fs"));
function rec(len, max, sys) {
    const { N, ans, current } = sys;
    if (len === N) {
        ans.push(current);
        return;
    }
    for (let i = 0; i <= max; i++) {
        const ch = String.fromCharCode('a'.charCodeAt(0) + i);
        rec(len + 1, i + 1, { N, ans, current: current + ch });
    }
}
function solve({ N, }) {
    const ans = [];
    rec(0, 0, { N, ans, current: '' });
    return ans;
}
function main(line) {
    const N = parseInt(line);
    console.log(solve({ N }).join('\n'));
}
exports.main = main;
if (__webpack_require__.c[__webpack_require__.s] === module) {
    const line = fs_1.default.readFileSync("/dev/stdin", "utf8");
    main(line);
}

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

/***/ }),

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

module.exports = require("fs");

/***/ })

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


function main(){
  var s;
  var hitachi = "";

  for(i = 1; i<= 5; i++){
    hitachi += "hi";
    if(hitachi == s){
      console.log("Yes");
      break;
    };

  console.log("No");
  };

Score : 100 points

Problem Statement

A Hitachi string is a concatenation of one or more copies of the string hi.

For example, hi and hihi are Hitachi strings, while ha and hii are not.

Given a string S, determine whether S is a Hitachi string.

Constraints

The length of S is between 1 and 10 (inclusive).

S is a string consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a Hitachi string, print Yes; otherwise, print No.

Sample Input 1

hihi

Sample Output 1

Yes

hihi is the concatenation of two copies of hi, so it is a Hitachi string.

Sample Input 2

hi

Sample Output 2

Yes

Sample Input 3

ha

Sample Output 3

No


function main(){
  var s;
  var hitachi = "";

  for(i = 1; i<= 5; i++){
    hitachi = "hi";
    if(hitachi == s){
      console.log("Yes");
    }else{
            console.log("No");
    }


function checkHitachi(S) {

    //hihi, hiii, dadahi, dahiida

    let pass = true;

    S.split('hi').forEach((v) => {
        if (v.length > 0) {
            pass = false;
        }
    })

    return pass;
}

function checkTest() {

    let pass = true;
    if (checkHitachi('ha') !== false) {
        pass = false;
    }
    if (checkHitachi('hii') !== false) {
        pass = false;
    }
    if (checkHitachi('hihi') !== true) {
        pass = false;
    }
    if (checkHitachi('hi') !== true) {
        pass = false;
    }

    return pass;

}

function main() {

	if (checkTest()) {
      return 'Yes';
    } else {
      return 'No';
    }
}


function Main(input){
	var N = parseInt(input.trim().split(" ")[0]);
  	var A = parseInt(input.trim().split(" ")[1]);
  	var B = parseInt(input.trim().split(" ")[2]);
  	if(A === 0){
    	console.log(0);
    }else{
		var d = Math.floor(N/(A+B));
    	var r = N%(A+B);
    	if(r > B){
			console.log(d*A+(r-B))
		}else{
			console.log((d*A)+r);
		}
	}
}
Main(require("fs").readFileSync("/dev/stdin","utf8"));

Score : 100 points

Problem Statement

In AtCoder City, there are three stations numbered 1, 2, and 3.

Each of these stations is operated by one of the two railway companies, A and B. A string S of length 3 represents which company operates each station. If S_i is A, Company A operates Station i; if S_i is B, Company B operates Station i.

To improve the transportation condition, for each pair of a station operated by Company A and one operated by Company B, there will be a bus service connecting them.

Determine if there is a pair of stations that will be connected by a bus service.

Constraints

Each character of S is A or B.

|S| = 3

Input

Input is given from Standard Input in the following format:

S

Output

If there is a pair of stations that will be connected by a bus service, print Yes; otherwise, print No.

Sample Input 1

ABA

Sample Output 1

Yes

Company A operates Station 1 and 3, while Company B operates Station 2.

There will be a bus service between Station 1 and 2, and between Station 2 and 3, so print Yes.

Sample Input 2

BBA

Sample Output 2

Yes

Company B operates Station 1 and 2, while Company A operates Station 3.

There will be a bus service between Station 1 and 3, and between Station 2 and 3, so print Yes.

Sample Input 3

BBB

Sample Output 3

No

Company B operates all the stations. Thus, there will be no bus service, so print No.


'use strict';
function Main(input) {
  let stations = input.split("");
  stations = stations.map(v => v.toUpperCase());

  const stationsLen = stations.length;
  const arr = [];
  for (let i = 0; i < stationsLen; ++i){
    arr.push(new Array(stationsLen).fill(false));
  }

  for (let i = 0; i < stationsLen; ++i) {
    for (let j = 0; j < stationsLen; ++j) {
      arr[i][j] = stations[i] !== stations[j];
    }
  }

  let hasBus = false;
  let len = arr.length;
  main: for (let i = 0; i < len; ++i) {
    for (let j = 0; j < len; ++j) {
      if ( arr[i][j] ) {
        hasBus = true;
        break main;
      }
    }
  }
  console.log(hasBus ? 'Yes' : 'No');
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";
function main(input) {
    let line = input.split(/\r?\n/g);
    let arr = line[0].split(" ");
    const N = BigInt(arr[0]), A = BigInt(arr[1]), B = BigInt(arr[2]);
    if (A <= N % (A + B))
        console.log(((((N + B) / (A + B)) | BigInt(0)) * A).toString());
    else
        console.log((((N / (A + B)) | BigInt(0)) * A + N % (A + B)).toString());
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 200 points

Problem Statement

Takahashi has many red balls and blue balls. Now, he will place them in a row.

Initially, there is no ball placed.

Takahashi, who is very patient, will do the following operation 10^{100} times:

Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row.

How many blue balls will be there among the first N balls in the row of balls made this way?

Constraints

1 \leq N \leq 10^{18}

A, B \geq 0

0 < A + B \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the number of blue balls that will be there among the first N balls in the row of balls.

Sample Input 1

8 3 4

Sample Output 1

4

Let b denote a blue ball, and r denote a red ball. The first eight balls in the row will be bbbrrrrb, among which there are four blue balls.

Sample Input 2

8 0 4

Sample Output 2

0

He placed only red balls from the beginning.

Sample Input 3

6 2 4

Sample Output 3

2

Among bbrrrr, there are two blue balls.


// inputに入力データ全体が入る
function Main(input) {
  input = input.split("\n");
  N = parseInt(input[0].split(" ")[0]);
  A = parseInt(input[0].split(" ")[1]);
  B = parseInt(input[0].split(" ")[2]);
  count = 0;
  r = ''
  while(true){
    r += 'b'.repeat(A)
    count += A
    if(count >= N)break
    r += 'r'.repeat(B)
    count += B
    if(count >= N)break
  }
  str = r.slice( 0, N) ;

  console.log(( str.match( /b/g ) || [] ).length);
}

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


function Main(input) {

    tmp = input.split(" ");
    var a = parseInt(tmp[0], 10);
    var b = parseInt(tmp[1], 10);
  	var c = parseInt(tmp[2], 10);
	var e = 0;
	var f = 0;
	var d = e + f;

    if(a !== d){
    for(;d>e+f;){
    for(var i = 0; i<b; i++ ){
        e + 1 ;
    }
    for(var i = 0; i<c; i++ ){
        f + 1;
    }}}else{
        console.log(e);
    }

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


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 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 hasNext(){return obj.hasNext();}
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 s = nextCharArray();
  var Q = nextInt();
  var queryList = new Array(Q);
  var count = 0;
  for(var i = 0; i < Q; i++){
    var query = nextStrArray();
    if(query[0] == "1"){
       count++;
      queryList[i] = 1;
    }else{
       if(query[1] == "1"){
          queryList[i] = "top:" + query[2];
       }else{
          queryList[i] = "end:" + query[2];
       }
    }
  }
  if(count % 2 == 1){
     s.sort(function(){
     	return 1;
     });
  }
  var left = new Array(Q).fill("");
  var rihgt = new Array(Q).fill("");
  for(var i = 0; i < Q; i++){
    //myerr(queryList[i]);
    if(isNaN(queryList[i])){
       var tmp = queryList[i].split(":");
      if(tmp[0] == "top"){
         if(count % 2 == 0){
            left[i] = tmp[1];
         }else{
            rihgt[i] = tmp[1];
         }
      }else{
         if(count % 2 == 0){
            rihgt[i] = tmp[1];
         }else{
            left[i] = tmp[1];
         }
      }
    }else{
      count--;
    }
  }
  left = myconv(left,0);
  rihgt = myconv(rihgt,0);
  s = myconv(s,0);
  myout(left + s+ rihgt);
}

Score : 400 points

Problem Statement

Takahashi has a string S consisting of lowercase English letters.

Starting with this string, he will produce a new one in the procedure given as follows.

The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:

If T_i = 1: reverse the string S.

If T_i = 2: An integer F_i and a lowercase English letter C_i are additionally provided.

If F_i = 1 : Add C_i to the beginning of the string S.

If F_i = 2 : Add C_i to the end of the string S.

Help Takahashi by finding the final string that results from the procedure.

Constraints

1 \leq |S| \leq 10^5

S consists of lowercase English letters.

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

T_i = 1 or 2.

F_i = 1 or 2, if provided.

C_i is a lowercase English letter, if provided.

Input

Input is given from Standard Input in the following format:

S
Q
Query_1
:
Query_Q

In the 3-rd through the (Q+2)-th lines, Query_i is one of the following:

1

which means T_i = 1, and:

2 F_i C_i

which means T_i = 2.

Output

Print the resulting string.

Sample Input 1

a
4
2 1 p
1
2 2 c
1

Sample Output 1

cpa

There will be Q = 4 operations. Initially, S is a.

Operation 1: Add p at the beginning of S. S becomes pa.

Operation 2: Reverse S. S becomes ap.

Operation 3: Add c at the end of S. S becomes apc.

Operation 4: Reverse S. S becomes cpa.

Thus, the resulting string is cpa.

Sample Input 2

a
6
2 2 a
2 1 b
1
2 2 c
1
1

Sample Output 2

aabc

There will be Q = 6 operations. Initially, S is a.

Operation 1: S becomes aa.

Operation 2: S becomes baa.

Operation 3: S becomes aab.

Operation 4: S becomes aabc.

Operation 5: S becomes cbaa.

Operation 6: S becomes aabc.

Thus, the resulting string is aabc.

Sample Input 3

y
1
2 1 x

Sample Output 3

xy


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.trim().split("\n");
	N = input[0]
	// var e = input[0].split(' ').map((n) => (parseInt(n)))[0]
	// var t = input[0].split(' ').map((n) => (parseInt(n)))[1]
	m = parseInt(input[1]) + 1
	for (i = 2; i <= m; i = i + 1) {
		// var q1 = parseInt(input[i].split(" ")[0])
		var qarr = input[i].split(" ")
		if (parseInt(qarr[0]) === 2) {
			if (parseInt(qarr[1]) === 1) {
				N = qarr[2] + N
			} else {
				N = N + qarr[2]
			}
		} else {
			if (input[i + 1] && parseInt(input[i + 1].split(" ")[0]) === 1 ) {
				i++
				continue
			} else  {
				N = rev(N)
			}
			// N = N.split('').reverse().join("")
		}
	}
	console.log(N)
}

function rev(s) {
  var rv = "";
  for (var i = 0, n = s.length; i < n; i = i + 1) {
    rv = rv + s[n - i - 1];
  }
  return rv;
}

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


function Main(n) {
	isEven = (n % 2) == 0
    if(isEven) {
     	console.log(n/2)
    } else {
      	console.log(Math.floor(n/2) + 1)
    }
}

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

Score : 100 points

Problem Statement

Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper.

At least how many sheets of paper does he need?

Constraints

N is an integer.

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

5

Sample Output 1

3

By printing the 1-st, 2-nd pages on the 1-st sheet, 3-rd and 4-th pages on the 2-nd sheet, and 5-th page on the 3-rd sheet, we can print all the data on 3 sheets of paper.

Sample Input 2

2

Sample Output 2

1

Sample Input 3

100

Sample Output 3

50


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

const vertical = 3;
const width = 3;

// 解答
function main(inputs){

    // ビンゴカード
    var bingoCard = [inputs[0].split(" "), inputs[1].split(" "), inputs[2].split(" ")];
    // 選ばれた数
    var selectedNum = inputs[3];
    // 選ばれた数値リスト
    var numList = [selectedNum];
    var hit = [[0,0,0],[0,0,0],[0,0,0]];
    var verticalHit = new Array(width);
    var widthHit = 0;

    // 入力値格納
    for (var i = 0; i < selectedNum; i++) {

        numList[i] = inputs[i + 4];
    }

    // ビンゴ判定(縦横)
    for (var m = 0; m < vertical; m++) {

        widthHit = 0;

        for (var n = 0; n < width; n++) {
            if (numList.indexOf(bingoCard[m][n]) > -1) {

                widthHit++;
                hit[m][n] = 1;

                if (verticalHit[n] != 0) {

                    verticalHit[n] = 1;
                }
            } else {

                verticalHit[n] = 0;
            }

            if (n == width - 1
                && ((widthHit == 3)
                   || (m == vertical - 1 && widthHit == 3))) {

                console.log('Yes');
                return;
            }
        }
    }

    // ビンゴ判定(斜め)
    if (crossBingoCheck(hit) === true) {

        console.log('Yes');
        return;
    }

    console.log('No');
}

function crossBingoCheck(hit){

    if ((hit[0][0] + hit[1][1] + hit[2][2] === 3)
       || (hit[0][2] + hit[1][1] + hit[2][0] === 3)) {

        return true;
    }

    return false;
}

Score : 200 points

Problem Statement

We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}.

The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet.

Determine whether we will have a bingo when the N numbers are chosen, that is, the sheet will contain three marked numbers in a row, column, or diagonal.

Constraints

All values in input are integers.

1 \leq A_{i, j} \leq 100

A_{i_1, j_1} \neq A_{i_2, j_2} ((i_1, j_1) \neq (i_2, j_2))

1 \leq N \leq 10

1 \leq b_i \leq 100

b_i \neq b_j (i \neq j)

Input

Input is given from Standard Input in the following format:

A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N

Output

If we will have a bingo, print Yes; otherwise, print No.

Sample Input 1

84 97 66
79 89 11
61 59 7
7
89
7
87
79
24
84
30

Sample Output 1

Yes

We will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal from the top-left to the bottom-right.

Sample Input 2

41 7 46
26 89 2
78 92 8
5
6
45
16
57
17

Sample Output 2

No

We will mark nothing.

Sample Input 3

60 88 34
92 41 43
65 73 48
10
60
43
88
11
48
73
65
41
92
34

Sample Output 3

Yes

We will mark all the squares.