Spreading Out the Cows
InterviewTime limit1sMemory limit128 MB
Place N cows into S stalls so adjacent gaps are D or D+1 with as many D as possible, minimizing total movement from given start positions.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Greedy, Sorting, Math
- Solved
- No attempts yet
Problem
Farmer John keeps prize milk cows numbered through . His freshly painted barn has stalls numbered through laid out in a single line, and every pair of neighboring stalls is exactly unit of distance apart.
The cows have settled into the stalls to rest: cow is in stall . Because the cows are antisocial and get grumpy when packed too close together, Farmer John wants to move them so they are as spread out as possible.
He wants the distances between adjacent cows to be as large as possible and also as uniform as possible (close to equal spacing). Concretely, let using integer division. Every distance between adjacent cows must differ from by at most , and as many of those distances as possible must equal exactly .
For instance, with four cows and eight stalls the cows may be placed at or , but not at or .
Compute the minimum total distance the cows must move to achieve such a spacing. Ignore the distance a cow needs to enter or leave a stall.
Input
- Line 1: two space-separated integers and .
- Lines 2 through : line contains a single integer .
Constraints: , , .
Output
- A single integer: the minimum total distance the cows must travel. This value is guaranteed to be under 1,000,000,000, so it fits comfortably in a signed 32-bit integer.
Hint
The diagram below illustrates a barn with cows and stalls whose starting positions are .
1 2 3 4 5 6 7 8 9 10
Cow Locs | A | B | C | . | . | . | . | D | E | . |
Cows move from stall to , from to , and from to . The total distance moved is . The final positions of the cows are stalls .
1 2 3 4 5 6 7 8 9 10
Init Stall | A | B | C | . | . | . | . | D | E | . |
Final Stall | A | . | B | . | C | . | . | D | . | E |
Distance moved | 0 | . | 1 | . | 2 | . | . | 0 | . | 1 |