My Ideal Futon Stack
Time limit8sMemory limit512 MB
Choose a closet order for N futons so that, using only stack pushes and pops, the daily total warmth on the bed minimizes the sum of |demand - warmth| over M days.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Bit manipulation, Brute force, Stack
- Solved
- No attempts yet
Problem
You bought futons to prepare for a new chapter in life. The -th futon has warmth supply . From the forecast for the next days, day is expected to have warmth demand . Too little or too much warmth spoils comfort, so define the discomfort of day as the absolute difference between and the total warmth supply of the futons on you that day. You want to make the sum of discomfort over these days as small as possible.
Unfortunately, your room is tiny and contains only a bed and a closet. To add one futon to the bed, you must take the futon on top of the closet and put it on top of the bed. Conversely, to remove one futon from the bed, you must take the futon on top of the bed and put it on top of the closet. There is no limit on how many futons you move in a day, but you can move only one futon at a time.
Now you are about to put the futons you just bought into the closet. Only at this moment can you put the futons into the closet in any order you like. How should you store the futons in the closet, and how should you take them out and put them back day by day, to spend each day comfortably? Find the minimum possible sum of discomfort over the days. Some futons may never be used, and on some days you may use no futon at all.
Input
The input consists of multiple data sets. Each data set has the following format.
N M
s1 s2 ... sN
d1 d2 ... dM
The first line of a data set contains integers , the number of futons, and , the number of days with a temperature forecast, separated by a space. The second line contains integers separated by spaces, where is the warmth supply of the -th futon. The third line contains integers separated by spaces, where is the warmth demand on day . These integers satisfy , , and .
The end of the input is marked by a data set with . Do not produce output for this data set.
Output
For each data set, output the minimum sum of discomfort over the days on one line.
Hint
For the fifth case, put the futons into the closet in the order 5, 2, 3, 1 from top to bottom. On day 1 take out 3 futons: . On day 2 put back 2 futons: . On day 3 take out 1 futon: . The total is .