Umbrellas for Cows
InterviewTime limit1sMemory limit128 MB
Given cow positions on a line and a price for each umbrella width, find the cheapest set of umbrellas that covers every cow, allowing overlaps.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Sorting, Prefix sum, Greedy
- Solved
- No attempts yet
Problem
It is a rainy day. Farmer John's () cows, numbered , do not like getting wet. The cows stand in roofless stalls arranged along a number line. The stalls occupy the integer coordinates from to (). Cow stands at coordinate (), and no two cows share a stall.
To keep the cows dry, Farmer John wants to buy umbrellas. An umbrella that spans coordinates to (with ) has width . An umbrella of width costs (). A wider umbrella is not necessarily more expensive than a narrower one.
Find the minimum total cost of a set of umbrellas that keeps every cow dry. In an optimal solution the umbrellas may overlap.
Input
- The first line contains two space-separated integers and .
- Each of the next lines contains one integer .
- Each of the following lines contains one integer; the -th of these lines is , the cost of an umbrella of width .
Output
- Print a single integer: the minimum cost required to buy umbrellas that keep all cows dry.
Hint
There are stalls, and cows occupy stalls , , , , , and . An umbrella covering one stall costs , one covering two stalls costs , and so on.
By buying a width- umbrella, a width- umbrella, and a width- umbrella, all cows can be covered for a total cost of :
UUUUUUUUUU U UUUU
C C C C C C
|--|--|--|--|--|--|--|--|--|--|--|
1 2 3 4 5 6 7 8 9 10 11 12
Here C marks a cow and U marks part of an umbrella.