Codeforces: Hamburgers
Abridged problem statement
Find the maximum number of hamburgers you can make given that one hamburger requires bread, sausage, and cheese pieces. You initially have pieces of bread, sausage, and cheese respectively, and can buy more at rubles per piece. You have rubles in total to spend.
Let us define as:
Here’s how the return values of will look:
Now our task simply reduces to finding , that is, finding the largest value of such that we can make burgers (such that ), and we can use binary search for this.
The only two things left to do are to bound the answer from both directions, and to code up . Let us tackle them sequentially.
The lower bound is obviously . For an upper bound, consider with , . In this case, the maximum number of burgers we can buy is , which is our upper bound.
Next, to code , we’ll need to have pieces of ingredients in total. If we have less than this, buy the rest and keep track of how much money you use in doing so. If this amount turns out to be , return , otherwise, return .
Code
#include <bits/stdc++.h>
typedef long long ll;
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
std::string recipe;
std::cin >> recipe;
ll b = 0, s = 0, c = 0;
for (auto &i : recipe) {
b += i == 'B';
s += i == 'S';
c += i == 'C';
}
ll nb, ns, nc, pb, ps, pc, rubles;
std::cin >> nb >> ns >> nc >> pb >> ps >> pc >> rubles;
auto f = [&](ll x) {
return std::max(x * b - nb, 0LL) * pb +
std::max(x * s - ns, 0LL) * ps +
std::max(x * c - nc, 0LL) * pc <= rubles;
};
ll l = 0, r = 1e12 + 100;
ll ans = 0;
while (l <= r) {
ll m = std::midpoint(l, r);
if (f(m)) {
ans = m, l = m + 1;
} else {
r = m - 1;
}
}
std::cout << ans << '\n';
}