"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 }();
function main(input) {
  var inputs = input[0].split(" ");
  var N = bigInt(inputs[0]);
  var A = parseInt(inputs[1]);

  if(A === 0){
    console.log(0);
  }else{
    var AB = A + parseInt(inputs[2]);
    var divmo = N.divmod(AB);
    var quotient = divmo.quotient;
    var remainder = divmo.remainder;

     var res = 0;
    if (remainder >= A){
      res = bigInt(quotient).times(A).add(A);
    }else{
      res = bigInt(quotient).times(A).add(remainder);
    }

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

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


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)

	n := nextInt()
	a := nextInt()
	b := nextInt()

	if a == 0 {
		fmt.Println(0)
		return
	}

	if n <= a {
		fmt.Println(n)
		return
	}

	if n <= a+b {
		fmt.Println(a)
		return
	}

	base := a * (n / (a + b))
	amari := n % (a + b)
	if a <= amari {
		amari = a
	}

	fmt.Println(base + amari)
}

// ---- readfunc
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var stdInScanner = bufio.NewScanner(os.Stdin)

func nextInt() int {
	stdInScanner.Scan()
	i, _ := strconv.Atoi(stdInScanner.Text())
	return i
}

func main() {
	stdInScanner.Split(bufio.ScanWords)

	N := nextInt()
	A := nextInt()
	B := nextInt()

	surplus := N % (A + B)
	if surplus >= A {
		surplus = A
	}
	fmt.Println(((N / (A + B)) * A) + surplus)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

// min, max, asub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func asub(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

func main() {
	sc.Split(bufio.ScanWords)
	N, A, B := getInt(), getInt(), getInt()

	C := A + B
	p := N / C
	r := N % C
	ans := p * A
	ans += min(A, r)
	out(ans)
}


package main

import (
	"fmt"
)

func main() {

	var N, A, B int
	fmt.Scanf("%d %d %d", &N, &A, &B)

	var countA, countB, countResult int
	for i := 0; i < N; i++ {

		if countA < A {
			countA++
			countResult++
		} else if countA == A && countB < B {
			countB++
		}

		if countA == A && countB == B {
			countA = 0
			countB = 0
		}

	}

	fmt.Println(countResult)
}


package main

import (
"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
)

func main() {
	sc = initScanner(os.Stdin)
	N, A, B := scanInt(sc), scanInt(sc), scanInt(sc)

	fmt.Println(resolve(N, A, B))
}

func resolve(N, A, B int) int {
	var count int

	for {
		if N > A {
			N -= A
			count += A
		} else {
			count += N
			break
		}

		N -= B

		if N <= 0 {
			break
		}
	}

	return count
}

// --------------- BASE DEFINITIONS ---------------

const (
	initialBufSize = 100000
	maxBufSize     = 1000000
)

var sc *bufio.Scanner

func initScanner(r io.Reader) *bufio.Scanner {
	buf := make([]byte, initialBufSize)

	sc := bufio.NewScanner(r)
	sc.Buffer(buf, maxBufSize)
	sc.Split(bufio.ScanWords)
	return sc
}

func scanInt(sc *bufio.Scanner) int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i
}

func scanIntSlice(sc *bufio.Scanner, n int) []int {
	is := make([]int, n)
	for i:=0; i<n; i++ {
		is[i] = scanInt(sc)
	}

	return is
}


package main

import "fmt"

func main() {
	var n, a, b, count int

	fmt.Scan(&n, &a, &b)

	if a == 0{
		count = 0
	}

	if a + b >= n{
		count = a
	}else if a + b < n{
		if n % (a+b) >= a{
			count = n / (a+b) + a
		}else{
			count = n / (a+b) + n % (a+b)
		}
	}

	fmt.Print(count)
}


n,a,b = gets.split(" ").map(&:to_i)

wa = a + b
count = n / wa
reds = count * a

amari = n % wa
amari = a if amari > a

puts reds + amari


n, a, b = gets.chomp.split(" ").map(&:to_i)

sum = a * (n / (a + b))
amari = n % (a + b)

if amari < a
  sum += amari
else
  sum += a
end

puts sum


n, a, b = gets.chomp.split().map(&:to_i)

quotient = n / (a + b) * a
amari = n % (a + b)

if amari >= a
  quotient += a
else
  quotient += amari
end

puts quotient


N, A, B = gets.split.map &:to_i
div = N / (A + B)
rem = N % (A + B)
puts div * A + rem


A,B,N = gets.split(" ").map(&:to_i)

x = ((N/(A+B)).floor)*A
y = [N%(A+B),A].min

puts x+y


n,a,b = gets.chomp.split(' ').map(&:to_i)
puts (n / (a + b)) * a + [(n % (a + b)),b].min


#![allow(unused_imports)]

use std::cmp;
use std::cmp::{max, min, Ordering};
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
use std::io::stdin;
use std::ops::*;
use std::process::exit;
use std::str::FromStr;

pub const MOD: usize = 1000000007;

fn main() {
    let (n, a, b): (i64, i64, i64) = input_three();
    let ans = n / (a + b) * a + min(a, n % (a + b));
    println!("{}", ans);
}

pub fn input<T: FromStr>() -> T {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    buf.trim().parse().ok().unwrap()
}

pub fn input_vec<T: FromStr>() -> Vec<T> {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    buf.trim()
        .split_whitespace()
        .map(|x| x.parse().ok().unwrap())
        .collect::<Vec<_>>()
}

pub fn input_lines<T: FromStr>(l: usize) -> Vec<T> {
    let mut res = Vec::new();
    for _i in 0..l {
        res.push(input());
    }
    res
}

pub fn input_lines_two<T: FromStr, U: FromStr>(l: usize) -> Vec<(T, U)> {
    let mut res = Vec::new();
    for _i in 0..l {
        res.push(input_two());
    }
    res
}

pub fn input_lines_three<T: FromStr, U: FromStr, V: FromStr>(l: usize) -> Vec<(T, U, V)> {
    let mut res = Vec::new();
    for _i in 0..l {
        res.push(input_three());
    }
    res
}

pub fn input_two<T: FromStr, U: FromStr>() -> (T, U) {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    let s: Vec<&str> = buf.split_whitespace().collect();
    (
        s[0].parse::<T>().ok().unwrap(),
        s[1].parse::<U>().ok().unwrap(),
    )
}

pub fn input_three<T: FromStr, U: FromStr, V: FromStr>() -> (T, U, V) {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    let s: Vec<&str> = buf.split_whitespace().collect();
    (
        s[0].parse::<T>().ok().unwrap(),
        s[1].parse::<U>().ok().unwrap(),
        s[2].parse::<V>().ok().unwrap(),
    )
}

pub fn input_four<T: FromStr, U: FromStr, V: FromStr, W: FromStr>() -> (T, U, V, W) {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    let s: Vec<&str> = buf.split_whitespace().collect();
    (
        s[0].parse().ok().unwrap(),
        s[1].parse().ok().unwrap(),
        s[2].parse().ok().unwrap(),
        s[3].parse().ok().unwrap(),
    )
}


//! ----------------------------------------------
//! Framework <https://github.com/vain0x/procon>
//!
//! See the bottom of file for solution.
//! ----------------------------------------------

#![allow(unused_imports)]
#![allow(non_snake_case)]

use std::cell::RefCell;
use std::cmp::{max, min, Ordering};
use std::collections::*;
use std::fmt::{Debug, Display, Formatter, Write as FmtWrite};
use std::io::{stderr, stdin, BufRead, Write};
use std::mem::{replace, swap};
use std::ops::*;
use std::rc::Rc;

/// Print values to standard error if debug mode.
#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), stderr());
            writeln!(err, "\x1B[33m{}\x1B[0m = {:?}", e, $e).unwrap()
        })*
    };
}

/// Read from standard input and parse each word.
/// - `read!(T, U, ..)` parses a line as a tuple of words.
/// - `read![[T]]` parses a line as an array of words.
/// - `read![..; N]` parses `N` lines, using `read!(..)` repeatedly.
#[allow(unused_macros)]
macro_rules! read {
    ([$t:ty] ; $n:expr) =>
        ((0..$n).map(|_| read!([$t])).collect::<Vec<_>>());
    ($($t:ty),+ ; $n:expr) =>
        ((0..$n).map(|_| read!($($t),+)).collect::<Vec<_>>());
    ([$t:ty]) =>
        (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::<Vec<$t>>());
    ($($t:ty),*) => {{
        let buf = rl();
        let mut w = buf.split_whitespace();
        ($(w.next().unwrap().parse::<$t>().unwrap()),*)
    }};
}

/// Read a line from standard input.
#[allow(dead_code)]
fn rl() -> String {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();

    #[allow(deprecated)]
    buf.trim_right().to_owned()
}

// -----------------------------------------------
// Solution
// -----------------------------------------------

fn main() {
    let (N, A, B) = read!(usize, usize, usize);

    let k = A + B;
    let total = A * (N / k) + min(N % k, A);

    println!("{}", total);
}


/* {{{ */
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}
/* }}} */

fn main() {
    input! {
        n: u64,
        a: u64,
        b: u64,
    }
    let d = n / (a+b);
    let m = n % (a+b);
    println!("{}", a * d + std::cmp::min(a,m));
}
/* vim:set foldmethod=marker: */


use proconio::{input, fastout};

#[fastout]
fn main() {
    input! {
        mut n: usize,
        a: usize,
        b: usize,
    }

    let mut ans = 0;

    for _ in 0..100000 {
        if n == 0 {
            break;
        }
        if a <= n {
            ans += a;
            n -=  a;
        } else {
            ans += n;
            n = 0;
        }

        if b <= n {
            n -= b;
        } else {
            n = 0;
        }
    }

    println!("{}", ans);
}


use proconio::{input, fastout};

#[fastout]
fn main() {
    input! {
        mut n: usize,
        a: usize,
        b: usize,
    }

    let mut ans = 0;

    for _ in 0..10000 {
        if n == 0 {
            break;
        }
        if a <= n {
            ans += a;
            n -=  a;
        } else {
            ans += n;
            n = 0;
        }

        if b <= n {
            n -= b;
        } else {
            n = 0;
        }
    }

    println!("{}", ans);
}


use proconio::{input, fastout};

#[fastout]
fn main() {
    input! {
        mut n: usize,
        a: usize,
        b: usize,
    }

    let mut ans = 0;

    for _ in 0..1000 {
        if n == 0 {
            break;
        }
        if a <= n {
            ans += a;
            n = n - a;
        } else {
            ans += n;
            n = 0;
        }

        if b <= n {
            n = n - b;
        } else {
            n = 0;
        }
    }

    println!("{}", ans);
}


let l = readLine()!.split(separator:" ").map{Int($0)!}
print(l[0]/(l[1]+l[2])*l[1]+min(l[1],l[0]%(l[1]+l[2])))


import Foundation
var inl=readLine()!.components(separatedBy:" ")
var n=Int(inl[0])!
var a=Int(inl[1])!
var b=Int(inl[2])!
var c=a+b
var s=0
s+=(n/c)*a
if(n%c>a){
  s+=a
}else{
  s+=n%c
}
print(s)


import Foundation

func readInts() -> [Int] {
    readLine()!.split(separator: " ").map { Int($0)! }
}

func main() {
    let nab = readInts()
    let (n,a,b) = (nab[0],nab[1],nab[2])
    var ans = 0

    ans = n / (a + b) * a
    let rem = n % (a + b)
    ans += rem < a ? rem: a
    print(ans)
}
main()


import Foundation

func readInts() -> [Int] {
    readLine()!.split(separator: " ").map { Int($0)! }
}

func main() {
    let nab = [8, 0, 4]//readInts()
    let (n,a,b) = (nab[0],nab[1],nab[2])
    var ans = 0

    ans = n / (a + b) * a
    let rem = n % (a + b)
    ans += rem < a ? rem: a
    print(ans)
}
main()


import * as fs from 'fs';
// main
function main(input: string[]) {
    // param
    let n: bigint = 0n;
    let a: bigint = 0n;
    let b: bigint = 0n;
    let ans: string = "";
    // init
    [n, a, b] = input.shift().split(" ").map(x => BigInt(x));
    // solve
    let s = n % (a + b);
    let t = (n - s) / (a + b);
    let u = (a < s) ? a : s;
    ans = String(a * t + u).replace("n", "");
    // answer
    console.log(ans);
}
// entrypoint
function entrypoint() {
    try {
        // linux
        let input = fs.readFileSync("/dev/stdin", "utf8").trim().split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        // windows
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            let input = lines;
            main(input);
        });
    }
}
entrypoint();


function main(input) {
  const inputs =input.split('\n')
  const [N, A, B] = inputs[0].split(' ').map(Number)
  let s = Math.floor(N / (A + B)) * A
  const r = N % ( A + B )
  if (r > A) {
    s = s + A
  } else {
    s = s + r
  }
  console.log(s)
}

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


function main(input) {
  const inputs =input.split('\n')
  const [N, A, B] = inputs[0].split(' ').map(Number)
  let s = N / (A + B) * A
  const r = N % ( A + B )
  if (r > A) {
    s = s + A
  } else {
    s = s + r
  }
  console.log(s)
}

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


def get_one_position(number):
    return number % 10

def get_ten_div(number):
    return number // 10 * 10 + 10

if __name__ == '__main__':
    numbers = []
    ans = 0
    min_one_point = 9
    min_one_point_index = 5
    for i in range(5):
        number = int(input())
        numbers.append(number)
        if get_one_position(number) <= min_one_point and get_one_position(number) != 0:
            min_one_point = get_one_position(number)
            min_one_point_index = i

    for i in range(len(numbers)):
        if i != min_one_point_index:
            if numbers[i] % 10 == 0:
                ans += numbers[i]
            else:
                ans += get_ten_div(numbers[i])
        else:
            ans += numbers[i]

    print(ans)


A = int(input())
B = int(input())
C = int(input())
D = int(input())
E = int(input())
a = A % 10
b = B % 10
c = C % 10
d = D % 10
e = E % 10
f = [a, b, c, d, e]
g = f.count(0)
a1 = A // 10
b1 = B // 10
c1 = C // 10
d1 = D // 10
e1 = E // 10
if g == 5:
    print(A + B + C + D + E)
else:
    f = [i for i in f if i > 0]
    print((a1 + b1 + c1 + d1 + e1 + 4 - g) * 10 + min(f))


T = [int(input()) for i in range(5)]
s = sum([x-((x-1)%10+1) for x in T])
m = sorted([(x-1)%10+1 for x in T])
print(s+m[0]+sum([(x+9)//10*10 for x in m[1:]]))


dish=[int(input()) for i in range(5)]
dish_s=[(dish[i]+9)//10 for i in range(5)]
dish_d=[dish[i]%10 for i in range(5)]
sum=0
for i in range(5):
  sum+=dish_s[i]
min=9
for i in range(5):
  if dish_d[i]!=0 and dish_d[i]<min:
    min=dish_d[i]
print((sum-1)*10+min)


dishes = [int(input()) for i in range(5)]

d = [abs(d % 10 -10) for d in dishes if d % 10 != 0] # select nums which can be divided by 10
d.remove(max(d))
print(sum(dishes) + sum(d))


import sys
a = list(sys.stdin.read().split())
t = [[int(n[:-1] or 0), int(n[-1])] for n in a]
t = list(zip(*t))
ans = (sum(t[0]) + (len(u := list(filter(lambda n: n > 0, t[1]))) - 1)) * 10 + min(u)
print(ans)


import java.io.*;
import java.util.*;

public class Main {

	static InputReader in = new InputReader(System.in);
	static PrintWriter out = new PrintWriter(System.out);

	static int MOD = 1000000007;
	static int M = 5005;
	static long INF = (long)1e15;

	public static void main(String[] args) throws IOException {

		int sum = 0;
		int M = 0;
		for(int i=0; i < 5; ++i) {
			int a = in.nextInt();
			int x = 10 - a % 10;
			if(x == 10)
				x = 0;
			sum += a + x;
			M = Math.max(M, x);
		}
		System.out.println( sum - M );

		out.close();
	}

	static void shuffle(int[] a) {
		Random r = new Random();
		for(int i = a.length - 1; i > 0; --i) {
			int si = r.nextInt(i);
			int t = a[si];
			a[si] = a[i];
			a[i] = t;
		}
	}

	static int lower_bound(int[] a, int n, int k) {
		int s = 0;
		int e = n;
		int m;
		while (e - s > 0) {
			m = (s + e) / 2;
			if (a[m] < k)
				s = m + 1;
			else
				e = m;
		}
		return e;
	}

	static int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	static class Pair implements Comparable<Pair> {
		int first, second;

		public Pair(int first, int second) {
			super();
			this.first = first;
			this.second = second;
		}

		@Override
		public int compareTo(Pair o) {
			return this.first != o.first ? this.first - o.first : this.second - o.second;
		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + first;
			result = prime * result + second;
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Pair other = (Pair) obj;
			if (first != other.first)
				return false;
			if (second != other.second)
				return false;
			return true;
		}
	}

}

class InputReader {

	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String readString() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}

}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;

public class Main {
    int[] a;
    private void solve() {
        a = new int[5];
        int ans = 0;
        int max = 0;
        for(int i = 0;i < 5;i++) {
            a[i] = nextInt();
            ans += a[i];
            int mod = 10 - a[i] % 10;
            if (mod != 10) {
                max = Math.max(max, mod);
            }
            ans += mod % 10;
        }

        out.println(ans - max);

    }

    public static void main(String[] args) {
        out.flush();
        new Main().solve();
        out.close();
    }

    /* Input */
    private static final InputStream in = System.in;
    private static final PrintWriter out = new PrintWriter(System.out);
    private final byte[] buffer = new byte[4096];
    private int p = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
        if (p < buflen)
            return true;
        p = 0;
        try {
            buflen = in.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (buflen <= 0)
            return false;
        return true;
    }

    public boolean hasNext() {
        while (hasNextByte() && !isPrint(buffer[p])) {
            p++;
        }
        return hasNextByte();
    }

    private boolean isPrint(int ch) {
        if (ch >= '!' && ch <= '~')
            return true;
        return false;
    }

    private int nextByte() {
        if (!hasNextByte())
            return -1;
        return buffer[p++];
    }

    public String next() {
        if (!hasNext())
            throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = -1;
        while (isPrint((b = nextByte()))) {
            sb.appendCodePoint(b);
        }
        return sb.toString();
    }

    public int nextInt() {
        return Integer.parseInt(next());
    }

    public long nextLong() {
        return Long.parseLong(next());
    }

    public double nextDouble() {
        return Double.parseDouble(next());
    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int[] num = new int[5];
    int ans = 0;
    int min = 10;
    for(int i=0; i<5; i++){
      num[i] = Integer.parseInt(in.readLine());
      if(num[i]%10==0)
        ans += num[i];
      else
        ans += (num[i]/10)*10+10;

      if(num[i]%10!=0)
       min = Math.min(num[i]%10,min);
    }
    System.out.println(ans-10+min);
  }
}


import java.util.*; import java.io.*; import java.math.*;
public class Main{
	//Don't have to see. start------------------------------------------
	static class InputIterator{
		ArrayList<String> inputLine = new ArrayList<String>(1024);
		int index = 0; int max; String read;
		InputIterator(){
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			try{
				while((read = br.readLine()) != null){
					inputLine.add(read);
				}
			}catch(IOException e){}
			max = inputLine.size();
		}
		boolean hasNext(){return (index < max);}
		String next(){
			if(hasNext()){
				return inputLine.get(index++);
			}else{
				throw new IndexOutOfBoundsException("There is no more input");
			}
		}
	}
	static HashMap<Integer, String> CONVSTR = new HashMap<Integer, String>();
	static InputIterator ii = new InputIterator();//This class cannot be used in reactive problem.
	static PrintWriter out = new PrintWriter(System.out);
	static void flush(){out.flush();}
	static void myout(Object t){out.println(t);}
	static void myerr(Object t){System.err.print("debug:");System.err.println(t);}
	static String next(){return ii.next();}
	static boolean hasNext(){return ii.hasNext();}
	static int nextInt(){return Integer.parseInt(next());}
	static long nextLong(){return Long.parseLong(next());}
	static double nextDouble(){return Double.parseDouble(next());}
	static ArrayList<String> nextStrArray(){return myconv(next(), 8);}
	static ArrayList<String> nextCharArray(){return myconv(next(), 0);}
	static ArrayList<Integer> nextIntArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Integer> ret = new ArrayList<Integer>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Integer.parseInt(input.get(i)));
		}
		return ret;
	}
	static ArrayList<Long> nextLongArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Long> ret = new ArrayList<Long>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Long.parseLong(input.get(i)));
		}
		return ret;
	}
	static String myconv(Object list, int no){//only join
		String joinString = CONVSTR.get(no);
		if(list instanceof String[]){
			return String.join(joinString, (String[])list);
		}else if(list instanceof ArrayList){
			return String.join(joinString, (ArrayList)list);
		}else{
			throw new ClassCastException("Don't join");
		}
	}
	static ArrayList<String> myconv(String str, int no){//only split
		String splitString = CONVSTR.get(no);
		return new ArrayList<String>(Arrays.asList(str.split(splitString)));
	}
	public static void main(String[] args){
		CONVSTR.put(8, " "); CONVSTR.put(9, "\n"); CONVSTR.put(0, "");
		solve();flush();
	}
	//Don't have to see. end------------------------------------------
	static void solve(){//Here is the main function
      ArrayList<Integer> list = new ArrayList<Integer>();
      int div = 10;
      int divIndex = -1;
      int sum = 0;
      for(int i = 0; i < 5; i++){
        int tmp = nextInt();
        list.add(tmp);
        if(tmp % 10 < div && tmp % 10 != 0){
          div = tmp % 10;
          divIndex = i;
        }
      }
      for(int i = 0; i < list.size(); i++){
        if(i == divIndex){
          sum += list.get(i);
        }else{
          int tmp = list.get(i);
          sum += tmp + (10 - (tmp % 10));
        }
      }
      myout(sum);
	}
	//Method addition frame start

	//Method addition frame end
}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		long sum=0;

		for (int i = 0; i < 4; i++) {
			int let =sc.nextInt() ;
			if (let % 10 !=0) {
				let =(let/10 + 1)*10;
			}
			sum+=let;
		}

		System.out.println(sum+sc.nextInt());

	}
}


import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
    public static void main(String[] args){

    Scanner sc = new Scanner(System.in);
    int[]a = new int[5];
    ArrayList<Integer>b = new ArrayList<>();

    for(int i=0; i<5; i++) {
    	a[i] = sc.nextInt();
    	if(a[i]%10 != 0) {
    		b.add(a[i]%10);
    	}
    }
    Collections.sort(b);
    int last = 0;
    for(int i=0; i<5; i++) {
    	if(a[i]%10 == b.get(0)) {
    		last = a[i];
    		break;
    	}
    }
    int al = 0;
    int cou = 0;
    for(int i=0; i<5; i++) {
    	if(a[i] != last) {
    		if(a[i]%10==0) {
    			al += a[i];
    		}else {
    			al += ((a[i]/10)+1)*10;
    		}
    		cou++;
    	}
     }
    if(cou != 4) {
    	al += ((last/10)+1)*10*(4-cou);
    }
    System.out.println(al + last);
    }
}


#include<bits/stdc++.h>
using namespace std;
int a[5];
int main(){
    int p,d=0,mx=0,i,sum=0;
    cin>>a[0]>>a[1]>>a[2]>>a[3]>>a[4];
    for(i=0;i<5;i++){
        if (a[i]%10!=0){
            d=(a[i]/10+1)*10-a[i];
            if(d>mx){
                mx=d;
                p=i;
            }
        }
    }
    for(i=0;i<5;i++){
        if(p!=i){
            if(a[i]%10!=0){
                sum+=
				(a[i]/10+1)*10;
            }
            else sum+=a[i];
        }
    }
    cout<<(sum+a[p])<<endl;
    return 0;

}


#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> as(5);
    for (int i = 0; i < 5; i++) cin >> as[i];
    int ans = 1e9;
    for (int i = 0; i < 5; i++) {
        int tmp = 0;
        for (int j = 0; j < 5; j++) {
            if (i == j) {
                tmp += as[j];
            } else {
                tmp += (as[j] + 9) / 10 * 10;
            }
        }
        // cerr << tmp << endl;
        ans = min(ans, tmp);
    }
    cout << ans << endl;
}


#include <iostream>
#include <climits>
using namespace std;

int best = INT_MAX;

int dish[5];
bool checked[5] = {false};

void dfs(int depth, int i_time);

int main()
{
    int i_time = 0;
    int cook = 0;
    cin >> dish[0];
    cin >> dish[1];
    cin >> dish[2];
    cin >> dish[3];
    cin >> dish[4];

    dfs(1, i_time);

    cout << best << endl;

    return 0;
}

void dfs(int depth, int i_time)
{

    for (int i = 0; i < 5; i++)
    {
        //メニューを選んで
        if (checked[i])
            continue;

        //注文する
        checked[i] = true;
        if (depth == 5)
        {
            if (i_time + dish[i] < best)
            {
                best = i_time + dish[i];
            }
        }
        else
        {
            int cook = dish[i];
            int i_i_time = i_time;
            //注文して時間を加算する 次の注文ができる時刻を求める
            while (cook > 0)
            {
                i_i_time = i_i_time + 10;
                cook = cook - 10;
            }
            dfs(depth+1, i_i_time);
        }
        checked[i] = false;
    }
}


#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int main(){
    IOS;
    int a,b,c,d,e;
    cin >> a >> b >> c >> d >>e;
    vector<int>nums;
    nums.push_back(a);
    nums.push_back(b);
    nums.push_back(c);
    nums.push_back(d);
    nums.push_back(e);
    vector<int> vec;
    for(int i=0; i<5; i++){
        if(10-(nums[i]%10)!= 10){
            vec.push_back(10-(nums[i]%10));
        }
    }
    sort(vec.begin(),vec.end());
    int count = 0;
    for(int i=0; i<vec.size()-1; i++){
        count+=vec[i];
    }
    int ans = a+b+c+d+e;
    cout << ans+count <<endl;

}


import math

def main():
    t = []
    for i in range(5):
        t.append(int(input()))

    max_wait = 0
    max_wait_order = 0
    for i in range(len(t)):
        if t[i] % 10 != 0 and 10 - (t[i] % 10) >= max_wait:
            max_wait = 10 - t[i] % 10
            max_wait_order = i

    time = 0
    for i in range(len(t)):
        if i == max_wait_order:
            continue
        else:
            time += math.ceil(t[i] / 10) * 10
    time += t[max_wait_order]

    print(time)

if __name__ == '__main__':
    main()


#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

int main(){
  int t, ans = 0, min_t = 129;
  for(int i = 0;i < 5;i++){
    cin >> t;
    if(t % 10){
      if(t % 10 <= min_t % 10) min_t = t;
      ans += ceil((double)t / 10) * 10;
    }else ans += t;
  }

  ans -= ceil((double)min_t / 10) * 10;
  ans += min_t;
  cout << ans << endl;

  return 0;
}


#include <stdio.h>

void better(){
    int X[5], x[5], i, last = 0;
    int S = 0;
    for(i = 0; i < 5; i++){
        scanf("%d", &X[i]);
        x[i] = X[i]%10;
        if(i == 0) continue;
        last = (x[i] < x[last] || x[last] == 0) && x[i] != 0? i : last;
    }
    //printf("%d\n", last);
    if(last == 4) goto aftSwap;

    int temp = X[4];
    X[4] = X[last];
    X[last] = temp;

    temp = x[4];
    x[4] = x[last];
    x[last] = temp;

    aftSwap:
    for(i = 0; i < 4; i++){
        S = x[i] != 0? S+X[i]+10-x[i] : S+X[i];
    }
    S += X[4];
    printf("%d\n", S);
}

int main(){
    better();
    return 0;
}


#include<stdio.h>
int main()
{
	int a[5],b[5],i,j,t,mt,sum=0;
	for(i=0;i<5;i++)
		scanf("%d",&a[i]);
	for(i=0;i<5;i++)
	{
		b[i]=a[i]%10;
		sum=sum+a[i]-b[i];
	}
	for(i=0;i<4;i++)
	{
		for(j=i+1;j<5;j++)
		{
			if(b[i]<b[j])
			{
				t=b[j];
				b[j]=b[i];
				b[i]=t;
			}
		}
	}
	for(i=0;i<4;i++)
	{
		if(b[i+1]==0)
		{
			mt=sum+10*i+b[i];
			break;
		}
		else
			mt=sum+40+b[4];
	}
	printf("%d\n",mt);
	return 0;
}


#include<stdio.h>
int a[5],b[5];
int main()
{
    int i,j,r,t,t1,t2,m,d,max;
    for(i=0;i<5;i++)
    {
        scanf("%d",&a[i]);
    }
     t=0;j=0;t1=0;
     for(i=0;i<5;i++)
    {
        if(a[i]%10==0)
        {
            t=t+a[i];
        }
        else
        {
            r=a[i]%10;
             t1=t1+(a[i]+(10-r));
             d=a[i]/10;
           b[j]=((d+1)*10)-a[i];

            j++;

        }
    }

    max=b[0];
     for(i=0;i<j;i++)

     {

        if(b[i]>max)
        {
            max=b[i];
        }

     }

    printf("%d\n",(t+t1)-max);
    return 0;
}


#include<stdio.h>
int main(void){

	int a[5],k=99999,x,i,m=0,w,o,y;

	scanf("%d",&a[0]);
	scanf("%d",&a[1]);
	scanf("%d",&a[2]);
	scanf("%d",&a[3]);
	scanf("%d",&a[4]);

	for(i=0;i<5;i++){
		w=a[i]%10;
		if(w<=k){
			if(w!=0){
				k=w;
				o=a[i];
				y=i;
			}
		}
	}
	printf("kは%d\n",k);

	for(x=0;x<5;x++){
		if(x!=y){
			if(a[x]%10!=0){
				a[x]=(a[x]/10)+1;
				a[x]=a[x]*10;
			}
			m+=a[x];
		}
	}
	m+=o;
	printf("%d",m);
	return(0);
}


#include<stdio.h>
int main(void){

	int a[5],k=99999,x,i,m=0,w,o;

	scanf("%d",&a[0]);
	scanf("%d",&a[1]);
	scanf("%d",&a[2]);
	scanf("%d",&a[3]);
	scanf("%d",&a[4]);

	for(i=0;i<5;i++){
		w=a[i]%10;
		if(w<=k){
			if(w!=0){
				k=w;
				o=a[i];
			}
		}
	}

	for(x=0;x<5;x++){
		w=a[x]%10;
		if(w!=k){
			if(a[x]%10!=0){
				a[x]=(a[x]/10)+1;
				a[x]=a[x]*10;
			}
			m+=a[x];
		}
	}
	m+=o;
	printf("%d",m);
	return(0);
}


#include<stdio.h>
int main(void){

	int a[5],k=99999,x,i,m=0,w,o;

	scanf("%d",&a[0]);
	scanf("%d",&a[1]);
	scanf("%d",&a[2]);
	scanf("%d",&a[3]);
	scanf("%d",&a[4]);

	for(i=0;i<5;i++){
		w=a[i]%10;
		if(w<k){
			if(w!=0){
				k=w;
				o=a[i];
			}
		}
	}

	for(x=0;x<5;x++){
		w=a[x]%10;
		if(w!=k){
			if(a[x]%10!=0){
				a[x]=(a[x]/10)+1;
				a[x]=a[x]*10;
			}
			m+=a[x];
		}
	}
	m+=o;
	printf("%d",m);
	return(0);
}


function Main(input) {
    input = input.split("\n").map(Number);
    var max = 0;
    input.forEach(function(val){
        if(max<(10-((val-0.1)%10))-0.1) max = 10-((val-0.1)%10)-0.1;
    });
    var sum = 0;
        input.forEach(function(val){
            sum += Math.ceil(val/10)*10;
    });
    console.log(sum-max);
}Main(require("fs").readFileSync("/dev/stdin","utf8").trim());


'use strict'
function Main(input) {
  const cookT = input.split("\n").map(Number);
  cookT.pop();
  // console.log({ cookT });

  let hitoketa = 10;

  for (let i = 0; i < 5; i++) {
    let num = cookT[i] % 10;
    if (num !== 0 && hitoketa > num) {
      hitoketa = num;
    }
  }

  let result = 0;

  for (let i = 0; i < 5; i++) {
    result += Math.ceil(cookT[i] / 10) * 10;
    // console.log(result);
  }
  result = result - 10 + hitoketa;
  console.log(result);

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


function Main(input){
  const abcde = input.split("\n").map(n=>parseInt(n));
  // const len = abcde.length;
  const len = 5;

  var total_time = 0;

  var last_cal_num = 10;
  var last_cal_num_index = 0;

  // 最後に注文するものを割り出す
  for(var i = 0; i < len; i++){
    var j = abcde[i] % 10
    if(0 < j && j < last_cal_num){
      last_cal_num = j;
      last_cal_num_index = i;
    }
  }

  // 最後に注文するもの以外の時間を足す
  for(var i = 0; i < len; i++){
    if(i !== last_cal_num_index){
      var j = abcde[i];
      var k = j % 10;
      j = k ? j + (10-k) : j; // k=0の時はそのままの値を入れる
      total_time += j;
    }
  }

  // 最後の注文の時間を足す
  total_time += abcde[last_cal_num_index];
  console.log(String(total_time).trim());

}

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


'use strict';
// inputに入力データ全体が入る
function Main(input) {
  input = input.split("\n");
  let modArr = input.map(function(val){
    val = parseInt(val);
    if(val%10===0){
      return 10;
    }else{
      return val%10;
    }
  });
  let min = modArr.indexOf(Math.min.apply(null, modArr));
  let last = parseInt(input[min]);

  input.splice(min, 1);
  let result =0;
  for(let i = 0 ; i< input.length; i++){
  	let x = Math.ceil(input[i] /10)*10;
    result += x;
  };
  result += last;
  console.log(result);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
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 = () => {
    let dishs = []
    while(hasNext()){
        let tmp = nextInt()
        dish.push([tmp, tmp % 10, tmp + tmp % 10])
    }
    dish.sort((a,b) => a[1]-b[1])
    let total = 0
    total += dish[0][2]
    total += dish[1][2]
    total += dish[2][2]
    total += dish[3][2]
    total += dish[4][0]
    console.log(total)
}
Main()


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 a = Number(lines[0]);
  var b = Number(lines[1]);
  var c = Number(lines[2]);
  var d = Number(lines[3]);
  var e = Number(lines[4]);
  var ans = 0;
  var info = [];

  info.push(a);
  info.push(b);
  info.push(c);
  info.push(d);
  info.push(e);

  var amari = [];
  amari.push(a%10);
  amari.push(b%10);
  amari.push(c%10);
  amari.push(d%10);
  amari.push(e%10);
  var amari_t = amari.filter(function(value){
    return !(value == 0);
  });

  var min = Math.min(...amari_t);

  var index = amari.indexOf(min);

  for(i=0; i<5; i++){
    if(i==index){
      continue;
      console.log('A');
    }
    ans += info[i]
    if(ans%10 !== 0){
      while(ans%10 !== 0){
        ans++;
      }
    }
  }

  ans += info[index];

  console.log(ans);

});


package main

import (
        "fmt"
        "sort"
)

type Order []int

func (o Order) Len() int {
        return len(o)
}

func (o Order) Swap(i, j int) {
        o[i], o[j] = o[j], o[i]
}

func (o Order) Less(i, j int) bool {
        if o[i]%10 == 0 {
                return true
        }
        return o[i]%10 > o[j]%10
}

func solution(order Order) int {
        sort.Sort(order)
        out := 0
        for i := 0; i < 4; i++ {
                t := 0
                if order[i]%10 == 0 {
                        t = order[i]
                } else {
                        t = order[i] + 10 - order[i]%10
                }
                out += t
        }
        return out + order[4]
}

func main() {
        order := make(Order, 0, 5)
        for i := 0; i < 5; i++ {
                n := 0
                fmt.Scan(&n)
                order = append(order, n)
        }
        fmt.Println(solution(order))
}


package main

import "fmt"

func main() {
	A := make([]int, 5)
	for i := 0; i < 5; i++ {
		fmt.Scanf("%d", &A[i])
	}

	mini := -1
	min := 10
	for i := 0; i < 5; i++ {
		if A[i]%10 != 0 && A[i]%10 < min {
			min = A[i] % 10
			mini = i
		}
	}
	sum := 0
	for i := 0; i < 5; i++ {
		if A[i]%10 == 0 {
			sum += A[i]
		} else {
			if mini == i {
				sum += A[i]
			} else {
				sum += A[i] - A[i]%10 + 10
			}
		}
	}
	fmt.Println(sum)

}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	num, _ := strconv.Atoi(scanString())
	return num
}

func scanString() string {
	sc.Scan()
	return sc.Text()
}

func scanInts(n int) []int {
	sl := make([]int, n)
	for i := range sl {
		sl[i] = scanInt()
	}
	return sl
}

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	n := scanInts(5)

	var sum, maxRem int
	for _, e := range n {
		sum += maxTime(e)

		if maxRem < remTime(e) {
			maxRem = remTime(e)
		}
	}

	fmt.Println(sum - maxRem)
}

func maxTime(n int) int {
	return ((n + 9) / 10) * 10
}

func remTime(n int) int {
	return maxTime(n) - n
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
)

var mod = 1000000007
var inf = 1000000007

func main() {
	r := bufio.NewReader(os.Stdin)
	costs := make([]int, 5)
	for i := 0; i < 5; i++ {
		fmt.Fscan(r, &costs[i])

	}

	ans := 0
	remainderCounts := 0
	mn := math.MaxInt64
	for i := 0; i < 5; i++ {
		ans += (costs[i] / 10) * 10
		if costs[i]%10 != 0 {
			remainderCounts++
			mn = min(mn, costs[i]%10)
		}
	}
	ans += (remainderCounts-1)*10 + mn
	fmt.Println(ans)
}

// permutations
func permutations(arr []int) [][]int {
	var helper func([]int, int)
	res := [][]int{}

	helper = func(arr []int, n int) {
		if n == 1 {
			tmp := make([]int, len(arr))
			copy(tmp, arr)
			res = append(res, tmp)
		} else {
			for i := 0; i < n; i++ {
				helper(arr, n-1)
				if n%2 == 1 {
					tmp := arr[i]
					arr[i] = arr[n-1]
					arr[n-1] = tmp
				} else {
					tmp := arr[0]
					arr[0] = arr[n-1]
					arr[n-1] = tmp
				}
			}
		}
	}
	helper(arr, len(arr))
	return res
}

// Union-Find
type unionFind struct {
	d []int
}

func newUnionFind(n int) *unionFind {
	uf := new(unionFind)
	uf.d = make([]int, n)
	for i := 0; i < n; i++ {
		uf.d[i] = -1
	}
	return uf
}

func (uf *unionFind) find(x int) int {
	if uf.d[x] < 0 {
		return x
	}
	uf.d[x] = uf.find(uf.d[x])
	return uf.d[x]
}

func (uf *unionFind) unite(x, y int) bool {
	rootX := uf.find(x)
	rootY := uf.find(y)
	if rootX == rootY {
		return false
	}

	if uf.d[rootX] < uf.d[rootY] {
		uf.d[rootX] += uf.d[rootY]
		uf.d[rootY] = rootX
	} else {
		uf.d[rootY] += uf.d[rootX]
		uf.d[rootX] = rootY
	}

	return true
}

func (uf *unionFind) same(x, y int) bool {
	return uf.find(x) == uf.find(y)
}

func (uf *unionFind) size(x int) int {
	return -uf.d[uf.find(x)]
}

// mod
func modpow(a, n, mod int) int {
	res := 1
	for n > 0 {
		if n%2 != 0 {
			res = res * a % mod
		}
		a = a * a % mod
		n = n / 2
	}
	return res
}

func modinv(n, mod int) int {
	return modpow(n, mod-2, mod)
}

func modcomb(n, a, mod int) int {
	x := 1
	y := 1
	for i := 0; i < a; i++ {
		x = x * (n - i)
		x %= mod
		y = y * (i + 1)
		y %= mod
	}
	return x * modpow(y, mod-2, mod) % mod
}

func modfactorial(n, mod int) int {
	result := 1
	for i := 1; i <= n; i++ {
		result = (result * i) % mod
	}
	return result
}

// Combination ...
type Combination struct {
	facts, invs []int
	mod         int
}

// NewCombination ...
func NewCombination(n, mod int) Combination {
	return Combination{
		facts: make([]int, n+1),
		invs:  make([]int, n+1),
		mod:   mod,
	}
}

func (cmb *Combination) calc(n, k int) int {
	ret := cmb.facts[n] * cmb.invs[k]
	ret %= cmb.mod
	ret = ret * cmb.invs[n-k]
	ret %= cmb.mod
	return ret
}

func (cmb *Combination) init(n int) {
	cmb.facts[0] = 1
	// 階乗を算出
	for i := 1; i <= n; i++ {
		cmb.facts[i] = cmb.facts[i-1] * i % cmb.mod
	}
	// 逆元を算出
	cmb.invs[n] = modinv(cmb.facts[n], cmb.mod)
	for i := n - 1; i >= 0; i-- {
		cmb.invs[i] = cmb.invs[i+1] * (i + 1) % cmb.mod
	}
}

// Utility
func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func primeFactor(x int) map[int]int {
	res := make(map[int]int)
	for i := 2; i*i <= x; i++ {
		for x%i == 0 {
			res[i]++
			x = x / i
		}
	}
	if x != 1 {
		res[x] = 1
	}
	return res
}

func divisor(x int) []int {
	res := make([]int, 0)
	for i := 1; i*i <= x; i++ {
		if x%i == 0 {
			res = append(res, i)
			if i != x/i {
				res = append(res, x/i)
			}
		}
	}
	return res
}

func gcd(x, y int) int {
	if y == 0 {
		return x
	}
	return gcd(y, x%y)
}

func lcm(x, y int) int {
	return x / gcd(x, y) * y
}

func reverseString(s string) string {
	r := []rune(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}

func pow(a, n int) int {
	ret := 1
	for i := 1; i <= n; i++ {
		ret *= a
	}
	return ret
}

// Queue ...
type Queue []int

// pop ...
func (q *Queue) empty() bool {
	return len(*q) == 0
}

// push ...
func (q *Queue) push(i int) {
	*q = append(*q, i)
}

// pop ...
func (q *Queue) pop() (int, bool) {
	if q.empty() {
		return 0, false
	} else {
		res := (*q)[0]
		*q = (*q)[1:]
		return res, true
	}
}

// Stack ...
type Stack []int

// pop ...
func (s *Stack) empty() bool {
	return len(*s) == 0
}

// push ...
func (s *Stack) push(i int) {
	*s = append(*s, i)
}

// pop ...
func (s *Stack) pop() (int, bool) {
	if s.empty() {
		return 0, false
	} else {
		index := len(*s) - 1
		res := (*s)[index]
		*s = (*s)[:index]
		return res, true
	}
}

// priority_queue
type intHeap []int

func (h intHeap) Len() int           { return len(h) }
func (h intHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h intHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *intHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}
func (h *intHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

// sortable points
type point struct {
	x int
	y int
}

type points []point

func (p points) Len() int {
	return len(p)
}

func (p points) Less(i, j int) bool {
	return p[i].x < p[j].x
}

func (p points) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}


package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"math"
	"os"
	"strconv"
)

const (
	initialBufSize = 10000
	maxBufSize     = 1000000
	mod            = 1e9 + 7
)

var (
	sc *bufio.Scanner = func() *bufio.Scanner {
		sc := bufio.NewScanner(os.Stdin)
		buf := make([]byte, initialBufSize)
		sc.Buffer(buf, maxBufSize)
		sc.Split(bufio.ScanWords)
		return sc
	}()
)

func main() {
	times := getIntArray(5)

	var just []int
	var notJust []int

	for i := 0; i < 5; i++ {
		if times[i] % 10 == 0 {
			just = append(just, times[i])
		} else {
			notJust = append(notJust, times[i])
		}
	}

	result := 0

	for _, time := range just {
		result += time
	}

	minIndex := 0
	minValue := 10
	for i, time := range notJust {
		if time % 10 < minValue {
			minValue = time % 10
			minIndex = i
		}
	}

	for i, time := range notJust {
		if i == minIndex {
			continue
		}
		result += (time / 10 + 1) * 10
	}

	result += notJust[minIndex]

	fmt.Println(result)
}

type Graph struct {
	n     int
	edges [][]int
}

func NewGraph(n int) *Graph {
	g := &Graph{
		n:     n,
		edges: make([][]int, n),
	}
	return g
}

func (g *Graph) AddEdge(u, v int) {
	g.edges[v] = append(g.edges[v], u)
	g.edges[u] = append(g.edges[u], v)
}

func dfs(c int, edges [][]int, visited map[int]struct{}) {
	visited[c] = struct{}{}

	for _, v := range edges[c] {
		_, flag := visited[v]
		if flag {
			continue
		}
		dfs(v, edges, visited)
	}
}

func bfs(c int, graph *Graph) {
	next := make([]int, 0)
	next = append(next, c)
	visited := make(map[int]struct{})

	for ; len(next) != 0; {
		u := next[0]
		next = next[1:]
		visited[u] = struct{}{}

		for _, v := range graph.edges[u] {
			_, flag := visited[v]
			if flag {
				continue
			}

			// なにか処理

			next = append(next, v)
		}
	}
}

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getIntArray(n int) []int {
	array := make([]int, n)
	for i := 0; i < n; i++ {
		array[i] = getInt()
	}
	return array
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func powMod(n, p int) int {
	if p == 0 {
		return 1
	} else if p%2 == 0 {
		t := powMod(n, p/2)
		return calcMod(t * t)
	} else {
		return calcMod(n * powMod(n, p-1))
	}
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func printIntArray(array []int) {
	strArray := fmt.Sprint(array)
	fmt.Println(strArray[1 : len(strArray)-1])
}

func calcMod(x int) int {
	return x % mod
}

func reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func isPrime(n int) bool {
	if n < 2 {
		return false
	} else if n == 2 {
		return true
	} else if n % 2 == 0 {
		return false
	}

	sqrtN := int(math.Sqrt(float64(n)))
	for i := 3; i <= sqrtN; i += 2 {
		if n % i == 0 {
			return false
		}
	}

	return true
}

func contains(s []int, e int) bool {
	for _, v := range s {
		if e == v {
			return true
		}
	}
	return false
}

func makeRange(min, max int) []int {
	a := make([]int, max-min+1)
	for i := range a {
		a[i] = min + i
	}
	return a
}

func powerset2(nums []int) [][]int {
	length := int(math.Pow(2, float64(len(nums))))
	result := make([][]int, length)

	index := 0
	result[index] = []int{}
	index++

	for _, n := range nums {
		max := index
		for i := 0; i < max; i++ {
			result[index] = copyAndAppend(result[i], n)
			index++
		}
	}

	return result
}

func copyAndAppend(nums []int, n int) []int {
	dst := make([]int, len(nums)+1)
	copy(dst, nums)
	dst[len(nums)] = n
	return dst
}

func calcGcd(x, y int) int {
	if y == 0 {
		return x
	} else if x >= y {
		return calcGcd(y, x % y)
	} else {
		return calcGcd(x, y % x)
	}
}

func getDivisor(n int) []int {
	var divisor []int
	divisor = append(divisor, 1)
	if n != 1 {
		divisor = append(divisor, n)
	}

	sqrt := int(math.Sqrt(float64(n)))
	for i := 2; i <= sqrt; i++ {
		if n % i == 0 {
			divisor = append(divisor, i)
			divisor = append(divisor, n/i)
		}
	}
	return divisor
}

type intHeap []int

func (h intHeap) Len() int {
	return len(h)
}

func (h intHeap) Less(i, j int) bool {
	return h[i] > h[j]
}

func (h intHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *intHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}

func (h *intHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func initHeap() *intHeap {
	ih := &intHeap{}
	heap.Init(ih)
	return ih
}

func (h *intHeap) pushHeap(n int) {
	heap.Push(h, n)
}

func (h *intHeap) popHeap() int {
	return heap.Pop(h).(int)
}

func factMod(n int) int {
	value := 1
	for ; n > 1; n-- {
		value = calcMod(value * n)
	}
	return value
}

func combinationMod(n, k int) int {
	factN := factMod(n)
	factK := factMod(k)
	factNK := factMod(n - k)
	factKR := powMod(factK, mod - 2)
	factNKR := powMod(factNK, mod - 2)
	return calcMod(factN * calcMod(factKR * factNKR))
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"reflect"
	"sort"
	"strconv"
	"strings"
	// "regexp"
)

/* sort */
type pair struct {
	index  int64
	p1, p2 interface{}
}
type pairs []pair

func (slice pairs) Len() int {
	return len(slice)
}

func (slice pairs) Less(i, j int) bool {
	return slice[i].index < slice[j].index
}

func (slice pairs) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

/* sort */
type Int64Slice []int64

func (slice Int64Slice) Len() int {
	return len(slice)
}

func (slice Int64Slice) Less(i, j int) bool {
	return slice[i] < slice[j]
}

func (slice Int64Slice) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}
func Int64s(a []int64)                    { sort.Sort(Int64Slice(a)) }
func Int64sSliceAreSorted(a []int64) bool { return sort.IsSorted(Int64Slice(a)) }

const (
	initialBufSize = 1e4
	maxBufSize     = 1e8
	INF            = 1e8
)

var (
	scanner = bufio.NewScanner(os.Stdin)
	writer  = bufio.NewWriter(os.Stdout)
	di      = []int64{-1, 0, 1, 0}
	dj      = []int64{0, -1, 0, 1}
)

func main() {
	buf := make([]byte, initialBufSize)
	scanner.Buffer(buf, maxBufSize)
	scanner.Split(bufio.ScanWords)
	A, B, C, D, E := readInt(), readInt(), readInt(), readInt(), readInt()
	ss := []int64{A, B, C, D, E}
	max := int64(-1)
	maxi := 0
	min := int64(INF)
	for i := 0; i < len(ss); i++ {
		if ss[i]%10 > max {
			max = ss[i]
			maxi = i
		}
		if ss[i]%10 != 0 && ss[i]%10 < min {
			min = ss[i] % 10
		}
	}
	time := max + (10 - max%10)
	for i := 0; i < len(ss); i++ {
		if i == maxi {
			continue
		}
		if ss[i]%10 == 0 {
			time += ss[i]
		} else {
			time += ss[i] + (10 - ss[i]%10)
		}
	}
	fmt.Println(time - (10 - min))
}

/*==========================================
 *             Library
 *==========================================*/
func NextPermutation(x sort.Interface) bool {
	n := x.Len() - 1
	if n < 1 {
		return false
	}
	j := n - 1
	for ; !x.Less(j, j+1); j-- {
		if j == 0 {
			return false
		}
	}
	l := n
	for !x.Less(j, l) {
		l--
	}
	x.Swap(j, l)
	for k, l := j+1, n; k < l; {
		x.Swap(k, l)
		k++
		l--
	}
	return true
}
func doubleAry(h int64, w int64, init int64) (res [][]int64) {
	res = make([][]int64, h)
	for i := int64(0); i < h; i++ {
		res[i] = make([]int64, w)
		for j := int64(0); j < w; j++ {
			res[i][j] = init
		}
	}
	return
}

func aryEq(a []int64, b []int64) bool {
	return reflect.DeepEqual(a, b)
}

func clone(n []int64) (r []int64) {
	r = make([]int64, len(n))
	for i := 0; i < len(n); i++ {
		r[i] = n[i]
	}
	return
}
func write(s string) {
	writer.WriteString(s)
}

func print() {
	writer.Flush()
}

// scanner.Split(bufio.ScanWords) をコメントアウトしないと使用不可
func readLine() (s string) {
	if scanner.Scan() {
		s = scanner.Text()
	}
	return s
}

func readInt() (read int64) {
	scanner.Scan()
	read, err := strconv.ParseInt(scanner.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return
}

func readFloat() (read float64) {
	scanner.Scan()
	read, err := strconv.ParseFloat(scanner.Text(), 64)
	if err != nil {
		panic(err)
	}
	return
}

func readRunes() (read []rune) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, v)
	}
	return
}

func readString() (read string) {
	scanner.Scan()
	read = scanner.Text()
	return
}

func readStrings() (read []string) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, string(v))
	}
	return
}

func s2i(s string) int64 {
	var intVal, e = strconv.ParseInt(s, 10, 64)
	if e != nil {
		panic(e)
	}
	return intVal
}

func i2s(i int64) string {
	var strVal = strconv.FormatInt(i, 10)
	return strVal
}

func s2f(s string) float64 {
	var floatVal, e = strconv.ParseFloat(s, 64)
	if e != nil {
		panic(e)
	}
	return floatVal
}

func abs(i int64) int64 {
	return int64(math.Abs(float64(i)))
}

func sum(i []int64) int64 {
	sum := int64(0)
	for _, val := range i {
		sum += val
	}
	return sum
}

func split(s string) []string {
	return strings.Fields(s)
}

func strAry2intAry(strs []string) []int64 {
	var ret = make([]int64, 0, len(strs))
	for _, str := range strs {
		var intVal = s2i(str)
		ret = append(ret, intVal)
	}
	return ret
}

func intAry2strAry(nums []int64) []string {
	var ret = make([]string, 0, len(nums))
	for _, num := range nums {
		var strVal = i2s(num)
		ret = append(ret, strVal)
	}
	return ret
}

func ary2str(strs []string) string {
	return strings.Join(strs, " ")
}

func reverse(res []int64) []int64 {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}
func reverseStr(res []string) []string {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}

func ini(res []int, init int) {
	if len(res) == 0 {
		return
	}
	res[0] = init
	for i := 0; i < len(res); i++ {
		copy(res[i:], res[:i])
	}
}

//
// func regexpExample() {
//     // Your code here!
//     var str = "13:20"
//     r := regexp.MustCompile(`(\d+):(\d+)`)
//     fmt.Println(r.FindStringSubmatch(str))
// }

// type Country struct {
//     gold int
//     silver int
//     blonze int
// }

// // 複数ソートのサンプル
// func stableSortExample() []Country{
//     var country = []Country {
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:3, blonze:2},
//         {gold:1, silver:3, blonze:3},
//     }
//     sort.SliceStable(country, func(i, j int) bool { return country[i].blonze > country[j].blonze })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].silver > country[j].silver })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].gold > country[j].gold })
//     return country
// }


food = []

5.times do
  food << gets.to_i
end

min = 10
sum = 0

food.each do |n|
  sum += (n/10.0).ceil * 10
  while n/10 != 0
    n %= 10
  end
  next if n == 0
  min = [min, n].min
end

puts sum - (10-min)


a = []
5.times do
	a << gets.to_i
end
a.sort!
sum = 1000
a.permutation(5).each do |per|
  tmp = 0
  per.each do |i|
    if tmp % 10 == 0
      tmp += i
    else
      while tmp % 10 != 0
        tmp += 1
      end
      tmp += i
    end
  end
  sum = tmp if tmp < sum
end
puts sum


as=$<.read.split.map(&:to_i)

ret = 0
min = 10
as.each do |a|
    ret += ((a/10.0).ceil * 10).to_i
    t = a % 10
    min = t if t < min && t != 0
end

ret -= 10-min
puts ret


time = []
min = Float::INFINITY
min_1 = 9
5.times do
  x = gets.chomp
  if x[-1].to_i != 0 && x[-1].to_i <= min_1
    min_1 = x[-1].to_i
    min = x.to_i
  end
  time << x.to_i
end
time.delete_at(time.find_index(min))
puts time.inject(min){|a,b| a+b.ceil(-1) }


time = []
min = Float::INFINITY
min_1 = 9
5.times do
  x = gets.chomp
  if x[-1].to_i != 0 && x[-1].to_i < min_1
    min_1 = x[-1].to_i
    min = x.to_i
  end
  time << x.to_i
end
time.delete_at(time.find_index(min))
puts time.inject(min){|a,b| a+b.ceil(-1) }


s=[]
a=[]
5.times do |i|
  s[i]=gets.to_i
  a[i]=10-s[i]%10
end
sum=0
a.zip(s).sort.each{|c,d|sum+=(c+d)}
puts sum-a.max


macro_rules! input {
  (source = $s:expr, $($r:tt)*) => {
      let mut iter = $s.split_whitespace();
      let mut next = || { iter.next().unwrap() };
      input_inner!{next, $($r)*}
  };
  ($($r:tt)*) => {
      let stdin = std::io::stdin();
      let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
      let mut next = move || -> String{
          bytes
              .by_ref()
              .map(|r|r.unwrap() as char)
              .skip_while(|c|c.is_whitespace())
              .take_while(|c|!c.is_whitespace())
              .collect()
      };
      input_inner!{next, $($r)*}
  };
}

macro_rules! input_inner {
  ($next:expr) => {};
  ($next:expr, ) => {};

  ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
      let $var = read_value!($next, $t);
      input_inner!{$next $($r)*}
  };

  ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {
    let mut $var = read_value!($next, $t);
    input_inner!{$next $($r)*}
  };
}

macro_rules! read_value {
  ($next:expr, ( $($t:tt),* )) => {
      ( $(read_value!($next, $t)),* )
  };

  ($next:expr, [ $t:tt ; $len:expr ]) => {
      (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
  };

  ($iter:expr, [ next / $t:tt ]) => {
    {
        let len = read_value!($iter, usize);
        (0..len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    }
  };

  ($next:expr, chars) => {
      read_value!($next, String).chars().collect::<Vec<char>>()
  };

  ($next:expr, usize1) => {
      read_value!($next, usize) - 1
  };

  ($next:expr, $t:ty) => {
      $next().parse::<$t>().expect("Parse error")
  };
}

pub trait LexicalPermutation {
    /// Return `true` if the slice was permuted, `false` if it is already
    /// at the last ordered permutation.
    fn next_permutation(&mut self) -> bool;
    /// Return `true` if the slice was permuted, `false` if it is already
    /// at the first ordered permutation.
    fn prev_permutation(&mut self) -> bool;
}

impl<T> LexicalPermutation for [T]
where
    T: Ord,
{
    /// Original author in Rust: Thomas Backman <serenity@exscape.org>
    fn next_permutation(&mut self) -> bool {
        // These cases only have 1 permutation each, so we can't do anything.
        if self.len() < 2 {
            return false;
        }

        // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
        let mut i = self.len() - 1;
        while i > 0 && self[i - 1] >= self[i] {
            i -= 1;
        }

        // If that is the entire vector, this is the last-ordered permutation.
        if i == 0 {
            return false;
        }

        // Step 2: Find the rightmost element larger than the pivot (i-1)
        let mut j = self.len() - 1;
        while j >= i && self[j] <= self[i - 1] {
            j -= 1;
        }

        // Step 3: Swap that element with the pivot
        self.swap(j, i - 1);

        // Step 4: Reverse the (previously) weakly decreasing part
        self[i..].reverse();

        true
    }

    fn prev_permutation(&mut self) -> bool {
        // These cases only have 1 permutation each, so we can't do anything.
        if self.len() < 2 {
            return false;
        }

        // Step 1: Identify the longest, rightmost weakly increasing part of the vector
        let mut i = self.len() - 1;
        while i > 0 && self[i - 1] <= self[i] {
            i -= 1;
        }

        // If that is the entire vector, this is the first-ordered permutation.
        if i == 0 {
            return false;
        }

        // Step 2: Reverse the weakly increasing part
        self[i..].reverse();

        // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
        let mut j = self.len() - 1;
        while j >= i && self[j - 1] < self[i - 1] {
            j -= 1;
        }

        // Step 4: Swap that element with the pivot
        self.swap(i - 1, j);

        true
    }
}

#[cfg(not(debug_assertions))]
macro_rules! mydbg {
    ($($arg:expr),*) => {};
}

macro_rules! echo {
    ($($a:expr),*) => {
          $(println!("{}",$a))*
      }
}

use std::cmp::Ordering::*;
#[allow(unused_imports)]
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet, VecDeque};
use std::io::{stdout, BufWriter, Write};
use std::mem::swap;

fn main() {
    input! {
        a: usize,
        b: usize,
        c: usize,
        d: usize,
        e: usize,
    }
    let mut v = vec![a, b, c, d, e];
    v.sort_by_key(|v| if v % 10 == 0 { 10 } else { v % 10 });
    let mut sum = v[0];
    for i in 1..v.len() {
        sum += v[i] / 10 * 10;
        if v[i] % 10 > 0 {
            sum += 10;
        }
    }
    echo!(sum);
}


#![allow(dead_code, unused_variables, unused_macros, unused_imports)]

// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes .by_ref() .map(|r|r.unwrap() as char) .skip_while(|c|c.is_whitespace()) .take_while(|c|!c.is_whitespace()) .collect() }; input_inner!{next, $($r)*} }; }
macro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $var = read_value!($next, $t); input_inner!{$next $($r)*} }; }
macro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>() }; ($next:expr, chars) => { read_value!($next, String).chars().collect::<Vec<char>>() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect("Parse error") }; }

fn main() {
    input! {
        mut foods: [i32; 5],
    }

    foods.sort_by(|a, b| match (a % 10, b % 10) {
        (0, 0) => std::cmp::Ordering::Equal,
        (0, _) => std::cmp::Ordering::Greater,
        (_, 0) => std::cmp::Ordering::Less,
        (a, b) => a.cmp(&b),
    });
    let mut ans = foods[0];
    for &x in foods.iter().skip(1) {
        ans += if x % 10 == 0 { x } else { x / 10 * 10 + 10 };
    }
    println!("{}", ans);
}


use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("filed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let mut arr:Vec<u64> = (0..5).map(|_| read()).collect();
    arr.sort_by_key(|&x| ((x as f64/10.0).ceil()*10.0)as u64 - x );
    let mut cnt = 0.0;
    let last = arr.pop().unwrap();
    for i in arr {
        cnt += (i as f64 / 10.0).ceil() * 10.0;
    }
    cnt += last as f64;
    println!("{}", cnt);
}


#![allow(unused_imports)]

use text_io::*;
use proconio::*;
use std::collections::*;
use std::process::exit;
use std::cmp::*;
use itertools::Itertools;

fn main() {
    input! {
    a:[isize;5],
    }
    let mut z =110;
    let mut ans =0;
    for i in 0..5 {
        ans+=(a[i]+9)/10*10;
        if z>a[i]%10&&a[i]%10!=0 {z=a[i]%10;}
    }
    println!("{}",ans+z-10)
}


use proconio::{fastout, input};

#[fastout]
fn main() {
    input!(n: [usize; 5]);

    let mut min = 100_000;

    let mut sum = 0;
    for v in &n {
        let d_v = *v % 10;

        if d_v != 0 {
            min = std::cmp::min(min, d_v);
        }

        sum += *v + (10 - d_v) % 10;
    }
    println!("{}", sum - (10 - min) % 10);
}


use proconio::{fastout, input};

#[fastout]
fn main() {
    input!(n: [usize; 5]);

    let mut min = 100_000;

    let mut sum = 0;
    for v in &n {
        let d_v = *v % 10;

        if d_v != 0 {
            min = std::cmp::min(min, d_v);
        }

        sum += *v + (10 - d_v) % 10;
    }
    println!("{}", sum - (10 - min));
}


var array: [Int] = []
var sum = 0

for _ in 0..<5 {
  let item = Int(readLine()!)!
  let a = item % 10
  sum += (item - a)
  if a != 0 {
    array.append(a)
  }
}

if array.count == 0 {
  print(sum)
} else {
  array.sortInPlace { (lhs, rhs) in
    return lhs > rhs
  }
  for i in 0..<array.count-1 {
    let item = array[i]
    let amari = item % 10
    let add = item + 10 - amari
    sum += add
  }
  sum += array[array.count-1]
  print(sum)
}