Hi all, I recently attempted Square Price. In this problem we are given N items, and it costs $$$k^2P_i$$$ yen to buy k units of the i-th product. We need to maximize $$$\sum_{i = 1}^{n}k_i$$$ given the total cost cannot exceed M.
While the standard approach to solve this is with binary search, my approach was to treat this as a constrained optimization problem. We need to maximize $$$f = \sum_{i = 1}^{n}k_i$$$ under the constraint $$$g = \sum_{i = 1}^{n}k_i^2P_i = M$$$. So for now, let us allow $$$k_i$$$ to range over all positive real numbers.
Setting $$$\nabla f = \lambda\nabla g$$$, we have a system of equations:
$$$\frac{\partial \sum_{j = 1}^{n}k_j}{\partial k_i} = \lambda \frac{\partial \sum_{j = 1}^{n}k_j^2P_j}{\partial k_i}$$$ for all $$$1 \leq i \leq n$$$
$$$\implies 1 = 2\lambda k_{i}P_i$$$
$$$\implies k_i = \frac{1}{2\lambda P_i}$$$
Along with:
$$$\sum_{i = 1}^{n}k_i^2P_i = M$$$
Plugging in the expression for $$$k_i$$$ gives:
$$$\frac{1}{4\lambda^2}\sum_{i = 1}^{n}\frac{1}{P_i} = M$$$
$$$\implies \lambda = \frac{1}{2}\sqrt{\frac{\sum_{i = 1}^{n}\frac{1}{P_i}}{M}}$$$
Finally we get the expression for $$$k_i$$$
$$$k_i = \frac{1}{P_i \sqrt{\frac{\sum_{j = 1}^{n}\frac{1}{P_j}}{M}}}$$$
Now consider our original problem which requires $$${k_i}$$$ to be integers. The answer must be one of the integer coordinate points in N-dimensional obtained by either rounding down or rounding up each $$$k_i$$$. However we do not need to check all of them, we can simply round each $$$k_i$$$ down, and then greedily round up the coordinate which contributes the least cost, i.e. with the least value of $$$(2k_i + 1)P_i$$$, while the total cost does not exceed M. This works because rounding up any coordinate contributes exactly 1 to f, thus it is never better to pick a more expensive rounding up.
Here is my code:
Unfortunately, I do not get AC with this approach.
What could be the issue?
P.S. Thanks for reading my blog! Also it is my first time writing a blog so I apologize for any mistakes/bad code










Hello! I found a testcase:
1 9999999999999999991Whose answer should be
1e9-1(999999999999999999=1e18-1), but your output is1e9, becausesqrt(1e18-1)==1000000000.0000000000due to precision loss. You can convertmtolong doubleto prevent this.Hi, thank you very much for the testcase! I converted m to long double and your test case passes, however it still fails on test case 5 :(
Oh, maybe float is not predictable after all, unfortunately