Baekjoon #1461 Library
Conditions
- Current position is 0, books are also at 0.
- You can carry M books at a time and move a total of N books.
- There’s no need to return to 0 for the last move.
Strategy
- Split positive and negative ways.
- Since there’s a requirement to return to zero, the sum of travel distances is minimal when rounding as little as possible.
- If the number of books in one direction is divided by M, then the sum of the distance traveled should be minimal.
- If it does not divided, move r books first and move M books is the smallest.
- The last move does not need to return to 0.
1po = [i for i in b if i > 0]
2ne = sorted(-i for i in b if i < 0)
3# Sort in positive ascending order for ease of calculation.
1def g(li, m):
2 if len(li) == 0: # Case if there's no books in the side.
3 return 0
4 o = len(li) % m
5
6 if o == 0:
7 # Can divide by M
8 return sum(li[m - 1::m]) * 2
9 else:
10 return sum(li[o - 1::m]) * 2
1 # Last move does not need to return to zero.
2 # Substract more far distance to make the result smaller.
3 print(g(po, m) + g(ne, m) - max(abs(b[0]), abs(b[-1])))
Comments