Explanation
Firstly, notice that we can binary search on the answer, or in this case. For each , we must check if it is valid, and update the binary search accordingly. We can binary search on because, for smaller values of , we are giving more gallons of milk. Therefore, if it is possible for one value to meet the requirement, it is possible for all of the values less than that to do so as well.
To efficiently determine whether a given value is valid, we can simulate the process. However, we process all states where , the number of gallons Bessie pays back, does not change all at once.
Additionally, notice that if Bessie gives more than distinct values of , then she will have definitely paid off the debt, since , which means that the upper bound of the number of operations we must make is , satisfying our time constraints.
Therefore, we can validate a given value of in time, and the entire solution runs in .
Implementation
Time Complexity:
C++
#include <algorithm>#include <fstream>#include <iostream>using std::cout;using std::endl;/*** @return whether Farmer John gives Bessie at least N (numGallons)* gallons of milk within withinDays with the given X value
Java
import java.io.*;import java.util.*;public class Loan {/*** @return whether Farmer John gives Bessie at least N (numGallons)* gallons of milk within withinDays with the given X value*/static boolean canRepay(long numGallons, long withinDays, long atLeast, long xVal) {long g = 0;
Python
def can_repay(num_gallons: int, within_days: int, at_least: int, x_val: int) -> bool:""":return: whether Farmer John gives Bessie at least N (num_gallons)gallons of milk within within_days with the given X value"""g = 0while within_days > 0 and g < num_gallons:y = (num_gallons - g) // x_valif y < at_least:leftover = (num_gallons - g + at_least - 1) // at_least
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!