Explanation
Let be true if it's possible to connect a house to at least one fire hydrant after placing fire hydrants such that the length of each hose is . We know that if is true, is also true, because an increase in the length of the hose will not prevent a valid configuration of fire hydrants from being built. Consequently, is monotonic, and we can binary search for the smallest value of such that is true.
We use a greedy algorithm to find . Firstly, we want to sort all houses by their address. For each from , let be the address of the th house. Place a fire hydrant at address , and this hydrant will cover all houses in the range . We can repeat this process for the first house to the right whose address does not fall into this range until every house can be connected with at least one first hydrant. Note that due to the circular nature of the street, we must do all calculations. If the number of hydrants needed is greater than the number of fire hydrants allowed, is false; otherwise, it is true.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;const int MAX_H = 1000;const int STREET_SIZE = 1000000;int num_houses;int num_hydrants;int houses[MAX_H];
Java
import java.io.*;import java.util.*;public class Firehose {private static final int MAX_H = 1000;private static final int STREET_SIZE = 1000000;private static boolean possible(int length, int numHydrants, int[] houses) {for (int i = 0; i < houses.length; i++) {int needed = 0; // Number of fire hydrants that are needed.
Python
MAX_H = 1000STREET_SIZE = 1000000def possible(length: int, num_hydrants: int, houses: list) -> bool:for i in range(len(houses)):# Number of fire hydrants that are needed.needed = 0# The house that we need to connect a fire hydrant to.start = houses[i]
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!