fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. // Extracted helper function to verify if target_units can be produced
  7. bool can_produce(long long target_units, int n, const vector<int>& composition, const vector<int>& stock, const vector<int>& cost, int budget) {
  8. long long total_cost = 0;
  9.  
  10. for (int i = 0; i < n; ++i) {
  11. long long required_metal = target_units * composition[i];
  12.  
  13. if (required_metal > stock[i]) {
  14. long long need_to_buy = required_metal - stock[i];
  15. total_cost += need_to_buy * cost[i];
  16. }
  17.  
  18. // Early exit if the running cost exceeds the budget
  19. if (total_cost > budget) {
  20. return false;
  21. }
  22. }
  23. return true;
  24. }
  25.  
  26. long long maxAlloys(int n, const vector<int>& composition, const vector<int>& stock, const vector<int>& cost, int budget) {
  27. // Upper bound set slightly higher than max budget + max stock based on constraints
  28. long long low = 0, high = 2e9;
  29. long long max_units = 0;
  30.  
  31. // Binary Search execution
  32. while (low <= high) {
  33. long long mid = low + (high - low) / 2;
  34.  
  35. // Pass necessary arrays and variables to the outside function
  36. if (can_produce(mid, n, composition, stock, cost, budget)) {
  37. max_units = mid; // mid is possible, store it
  38. low = mid + 1; // try searching for a larger amount
  39. } else {
  40. high = mid - 1; // mid is impossible, reduce target
  41. }
  42. }
  43.  
  44. return max_units;
  45. }
  46.  
  47. int main() {
  48. // Example test case
  49. int n = 2;
  50. vector<int> composition = {1, 2};
  51. vector<int> stock = {0, 1};
  52. vector<int> cost = {1, 1};
  53. int budget = 3;
  54.  
  55. cout << "Maximum units of alloy: " << maxAlloys(n, composition, stock, cost, budget) << "\n";
  56. // Expected output: 1
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Maximum units of alloy: 1