A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place? [Image] 

One day, when he came to his friend Evan, Om Nom didn't find him at home but he found two bags with candies. The first was full of blue candies and the second bag was full of red candies. Om Nom knows that each red candy weighs W_{r} grams and each blue candy weighs W_{b} grams. Eating a single red candy gives Om Nom H_{r} joy units and eating a single blue candy gives Om Nom H_{b} joy units.

Candies are the most important thing in the world, but on the other hand overeating is not good. Om Nom knows if he eats more than C grams of candies, he will get sick. Om Nom thinks that it isn't proper to leave candy leftovers, so he can only eat a whole candy. Om Nom is a great mathematician and he quickly determined how many candies of what type he should eat in order to get the maximum number of joy units. Can you repeat his achievement? You can assume that each bag contains more candies that Om Nom can eat.


-----Input-----

The single line contains five integers C, H_{r}, H_{b}, W_{r}, W_{b} (1 ≤ C, H_{r}, H_{b}, W_{r}, W_{b} ≤ 10^9).


-----Output-----

Print a single integer — the maximum number of joy units that Om Nom can get.


-----Examples-----
Input
10 3 5 2 3

Output
16



-----Note-----

In the sample test Om Nom can eat two candies of each type and thus get 16 joy units.

Source: codeforces | Difficulty: HARD
Tags: Complete search

Mathematics

Greedy algorithms


Solutions:
(C, Pr, Pb, Wr, Wb) = list(map(int, input().split()))
result = 0
if Wr * Wr >= C:
	i = 0
	while Wr * i <= C:
		j = int((C - Wr * i) / Wb)
		result = max(result, Pr * i + Pb * j)
		i += 1
	print(result)
	return
if Wb * Wb >= C:
	i = 0
	while Wb * i <= C:
		j = int((C - Wb * i) / Wr)
		result = max(result, Pb * i + Pr * j)
		i += 1
	print(result)
	return
Ab = Pb / Wb
Ar = Pr / Wr
if Ab < Ar:
	i = 0
	while i * i <= C:
		j = int((C - Wb * i) / Wr)
		result = max(result, Pb * i + Pr * j)
		i += 1
	print(result)
else:
	i = 0
	while i * i <= C:
		j = int((C - Wr * i) / Wb)
		result = max(result, Pr * i + Pb * j)
		i += 1
	print(result)


def main():
	(c, hr, hb, wr, wb) = map(int, input().split())
	ans = 0
	for i in range(10 ** 6 + 1):
		if i * wr <= c:
			ans = max(ans, i * hr + (c - i * wr) // wb * hb)
		if i * wb <= c:
			ans = max(ans, i * hb + (c - i * wb) // wr * hr)
	print(ans)
main()


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
(c, hr, hb, wr, wb) = map(int, input().split())
if hr / wr > hb / wb:
	(hr, hb) = (hb, hr)
	(wr, wb) = (wb, wr)
totr = c // wr
totb = c // wb
ans = 0
if totr <= 10 ** 5:
	for a in range(totr + 1):
		b = (c - a * wr) // wb
		if a * wr + b * wb <= c:
			ans = max(ans, a * hr + b * hb)
elif totb <= 10 ** 5:
	for b in range(totb + 1):
		a = (c - b * wb) // wr
		if a * wr + b * wb <= c:
			ans = max(ans, a * hr + b * hb)
else:
	for a in range(wb):
		b = (c - a * wr) // wb
		if a * wr + b * wb <= c:
			ans = max(ans, a * hr + b * hb)
print(ans)


(C, Hr, Hb, Wr, Wb) = map(int, input().split())
ans = 0
for i in range(10 ** 5):
	if Wr * i <= C:
		ans = max(ans, Hr * i + (C - Wr * i) // Wb * Hb)
for i in range(10 ** 5):
	if Wb * i <= C:
		ans = max(ans, Hb * i + (C - Wb * i) // Wr * Hr)
print(ans)


import math

def solve(c, hr, hb, wr, wb):
	INF = math.ceil(math.sqrt(c))
	if wb > wr:
		(wb, wr) = (wr, wb)
		(hb, hr) = (hr, hb)
	if wr > INF:
		ans = 0
		i = 0
		while i * wr <= c and i < INF:
			ans = max(ans, i * hr + (c - i * wr) // wb * hb)
			i += 1
		return ans
	else:
		if wr * hb > hr * wb:
			(wb, wr) = (wr, wb)
			(hb, hr) = (hr, hb)
		ans = 0
		j = 0
		while j * wb <= c and j <= wr:
			ans = max(ans, j * hb + (c - j * wb) // wr * hr)
			j += 1
		return ans
(c, hr, hb, wr, wb) = list(map(int, input().split()))
print(solve(c, hr, hb, wr, wb))


(c, hr, hb, wr, wb) = map(int, input().split())
s = 0
if wb < wr:
	(hr, hb, wr, wb) = (hb, hr, wb, wr)
if wb * wb > c:
	for nb in range(c // wb + 1):
		s = max(s, nb * hb + hr * ((c - wb * nb) // wr))
else:
	if hr * wb < hb * wr:
		(hr, hb, wr, wb) = (hb, hr, wb, wr)
	for nb in range(min(31625, c // wb + 1)):
		s = max(s, nb * hb + hr * ((c - wb * nb) // wr))
print(s)


(m, h1, h2, w1, w2) = map(int, input().split())
if h2 / w2 > h1 / w1:
	(h1, h2) = (h2, h1)
	(w1, w2) = (w2, w1)
if w1 ** 2 >= m:
	res = 0
	for i in range(int(m ** 0.5 + 1)):
		if i * w1 <= m:
			new = i * h1 + (m - w1 * i) // w2 * h2
			res = max(res, new)
	print(res)
	exit()
res = 0
for i in range(int(m ** 0.5 + 5)):
	new_res = i * h2 + (m - i * w2) // w1 * h1
	res = max(res, new_res)
print(res)


import math
(c, x, y, a, b) = map(int, input().split())
lim = int(math.sqrt(c))
ans = 0
for i in range(lim):
	if c >= i * a:
		ans = max(ans, x * i + (c - i * a) // b * y)
	if c >= i * b:
		ans = max(ans, y * i + (c - i * b) // a * x)
print(ans)


import math
(c, hr, hb, wr, wb) = map(int, input().split())
s = int(math.sqrt(c))
ans = 0
for i in range(s):
	if c >= i * wr:
		ans = max(ans, hr * i + (c - i * wr) // wb * hb)
	if c >= i * wb:
		ans = max(ans, hb * i + (c - i * wb) // wr * hr)
print(ans)


def main():
	(c, hr, hb, wr, wb) = (int(i) for i in input().split())
	if wb < c ** (1 / 2) > wr:
		if hr / wr < hb / wb:
			(wr, hr, wb, hb) = (wb, hb, wr, hr)
		mx = 0
		for i in range(wr + 1):
			tmx = i * hb + (c - i * wb) // wr * hr
			mx = tmx if tmx > mx else mx
	else:
		if wr <= wb:
			(wr, hr, wb, hb) = (wb, hb, wr, hr)
		nr = 0
		mx = 0
		while nr * wr <= c:
			tmx = nr * hr + (c - nr * wr) // wb * hb
			mx = tmx if tmx > mx else mx
			nr += 1
	print(mx)

def __starting_point():
	main()
__starting_point()


import math
(c, hr, hb, wr, wb) = map(int, input().split())
if wr < wb:
	(wr, wb) = (wb, wr)
	(hr, hb) = (hb, hr)
ans = 0
if wr * wr >= c:
	for i in range(c // wr + 1):
		ans = max(ans, i * hr + (c - i * wr) // wb * hb)
else:
	if hr * wb < hb * wr:
		(wr, wb) = (wb, wr)
		(hr, hb) = (hb, hr)
	for i in range(wr):
		ans = max(ans, i * hb + (c - i * wb) // wr * hr)
print(ans)


(a, b, c, d, e) = list(map(int, input().split(' ')))
check = int(a ** 0.5)
ans = 0
for red in range(check + 1):
	blue = (a - d * red) // e
	if blue >= 0:
		ans = max(ans, red * b + blue * c)
for blue in range(check + 1):
	red = (a - e * blue) // d
	if red >= 0:
		ans = max(ans, red * b + blue * c)
print(ans)


def max_joy(max_grams, weight_r, joy_r, weight_b, joy_b, jollies, memoiser):
	if max_grams < 0:
		return 0
	if max_grams == 0:
		return jollies
	if str(max_grams) in memoiser:
		if jollies >= memoiser[str(max_grams)]:
			return 0
	memoiser[str(max_grams)] = jollies
	res1 = max_joy(max_grams - weight_r, weight_r, joy_r, weight_b, joy_b, jollies + joy_r, memoiser)
	res2 = max_joy(max_grams - weight_b, weight_r, joy_r, weight_b, joy_b, jollies + joy_b, memoiser)
	return max(res1, res2)

def main():
	max_grams = 982068341
	weight_r = 55
	joy_r = 57
	weight_b = 106
	joy_b = 109
	memoiser = {}
	jollies = 0
	res = max_joy(max_grams, weight_r, joy_r, weight_b, joy_b, jollies, memoiser)
	print(res)
import math
(c, x, y, a, b) = map(int, input().split())
lim = int(math.sqrt(c))
ans = 0
for i in range(lim):
	if c >= i * a:
		ans = max(ans, x * i + (c - i * a) // b * y)
	if c >= i * b:
		ans = max(ans, y * i + (c - i * b) // a * x)
print(ans)


__author__ = 'trunghieu11'

def calc(n, h1, h2, w1, w2):
	answer = 0
	len = n // w1
	for i in range(0, min(len, 100000) + 1):
		answer = max(answer, i * h1 + (n - i * w1) // w2 * h2)
	return answer
(n, hR, hB, wR, wB) = map(int, input().split())
print(max(calc(n, hR, hB, wR, wB), calc(n, hB, hR, wB, wR)))


import sys
f = sys.stdin
(C, Hr, Hb, Wr, Wb) = map(int, f.readline().strip().split())
if Hr / Wr < Hb / Wb:
	(Hr, Hb, Wr, Wb) = (Hb, Hr, Wb, Wr)
if C % Wr == 0 and C // Wr > 0:
	print(C // Wr * Hr)
elif C // Wr == 0:
	print(C // Wb * Hb)
else:
	nmax = C // Wr
	pmax = nmax * Hr + (C - nmax * Wr) // Wb * Hb
	dmax = (C - (nmax - 0) * Wr) % Wb
	if Hr / Wr > Hb / Wb:
		dx = dmax * (Hb / Wb) / (Hr / Wr - Hb / Wb)
	elif Hr / Wr < Hb / Wb:
		dx = 0
	else:
		dx = Wb * Wr
		if Wr < Wb:
			nmax = C // Wb
			pmax = nmax * Hb + (C - nmax * Wb) // Wr * Hr
		if Wr > Wb:
			nmax = C // Wr
			pmax = nmax * Hr + (C - nmax * Wr) // Wb * Hb
	if Wr > Wb and dx > 0:
		for k in range(1, C // Wr):
			if k * Wr > dx:
				break
			pk = (nmax - k) * Hr + (C - (nmax - k) * Wr) // Wb * Hb
			dk = (C - (nmax - k) * Wr) % Wb
			if pk > pmax:
				pmax = pk
			if dk == 0:
				break
	elif Wr < Wb and dx > 0:
		for j in range(1, C // Wb + 1):
			k = nmax - (C - j * Wb) // Wr
			if k * Wr > dx:
				break
			pk = (nmax - k) * Hr + (C - (nmax - k) * Wr) // Wb * Hb
			dk = (C - (nmax - k) * Wr) % Wb
			if pk > pmax:
				pmax = pk
			if dk == 0:
				break
	print(pmax)