Dividing the Path
InterviewTime limit1sMemory limit128 MB
Partition the segment [0, L] into consecutive pieces of even length between 2A and 2B so no cut lands strictly inside any cow's interval, and minimize the number of pieces, or report that no partition exists.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Prefix sum, Sliding window, Intervals
- Solved
- No attempts yet
Problem
Farmer John's cows love the clover growing along the ridge of a hill in his field. To keep the clover watered, Farmer John installs water sprinklers along the ridge.
Model the ridge as a one-dimensional number line running from to (where and is even). Each sprinkler head sits on this line and waters the ground for some distance in both directions. A sprinkler's spray radius is an integer with (where ), so a sprinkler centered at position waters the closed segment .
Farmer John must water the entire ridge so that every location is covered by exactly one sprinkler (no gaps and no overlap), and no sprinkler may spray past either end of the ridge. Equivalently, the sprinklers partition into consecutive segments, each of even length between and .
Each of Farmer John's cows (where ) has a favorite stretch of clover, given as the interval from to ; these stretches may overlap. Every cow's favorite stretch must be watered by a single sprinkler (that sprinkler may also spray beyond the stretch). Equivalently, no boundary between two adjacent sprinklers may fall strictly inside any cow's interval .
Find the minimum number of sprinklers needed to water the entire ridge under these rules.
Input
- Line 1: two space-separated integers and .
- Line 2: two space-separated integers and .
- Lines 3 through : each line contains two integers and (), the start and end of one cow's favorite stretch, measured as distances from the start of the ridge.
Output
- Line 1: the minimum number of sprinklers required. If no valid sprinkler configuration exists, output .
Notes
Consider the first example. Three sprinklers suffice: one centered at with radius (covering ), one centered at with radius (covering ), and one centered at with radius (covering ). The middle sprinkler waters the entire stretch liked by the second cow ( to ), and the last sprinkler waters the entire stretch liked by the first cow ( to ).
|-----c2----|-c1| cows' preferred ranges
|---1---|-------2-------|---3---| sprinklers
+---+---+---+---+---+---+---+---+
0 1 2 3 4 5 6 7 8