Codeforces - D. Make Them Equal
Algorithm used: Knapsack DP
Time Complexity: O(N²)
In this problem, you start out with
- an array A of size N where all elements are initially 1
- an array B of size N where all elements are in the range 1 - 10³
- an array C of size N where all elements are in the range 1 - 10⁶.
For each A[i], find the minimum number of operations needed to convert 1 to B[i]. This can be done using a simple BFS, where each node is the current value of A[i], and the distance to this node is the number of operations needed to reach this value. For a distance x, we can increase it by x/1, x/2, x/3 ... x/x. It doesn't make sense to divide x by any number greater than x, because then the increment would be equal to 0. So for each node, we add nodes x + x/1, x + x/2 ... x + x/x to a queue, so long as they haven't already been visited.
From here it is a simple knapsack problem, where we find out the maximum number of coins that we can receive, by performing no more than j operations and choosing from the first i items. However, this may get a TLE verdict, since j is at most K and i is at most N; K * N = 10⁹ * 10³ = 10¹².
To avoid this, observe that at most 12 operations are needed to covert 1 to B[i]. This means that a total of N * 12 ≈ 10⁴ operations will be done. Reset K to n * 12, if this is smaller. The computer will perform K * N = 10⁴ * 10³ = 10⁷ operations, which will be enough to pass.
Code
Comments