One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task.
Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following way. We have n people standing on the first floor, the i-th person wants to go to the fi-th floor. Unfortunately, there is only one elevator and its capacity equal to k (that is at most k people can use it simultaneously). Initially the elevator is located on the first floor. The elevator needs |a - b| seconds to move from the a-th floor to the b-th floor (we don't count the time the people need to get on and off the elevator).
What is the minimal number of seconds that is needed to transport all the people to the corresponding floors and then return the elevator to the first floor?
The first line contains two integers n and k (1 ≤ n, k ≤ 2000) — the number of people and the maximal capacity of the elevator.
The next line contains n integers: f1, f2, ..., fn (2 ≤ fi ≤ 2000), where fi denotes the target floor of the i-th person.
Output a single integer — the minimal time needed to achieve the goal.
3 2 2 3 4
8
4 2 50 100 50 100
296
10 3 2 2 2 2 2 2 2 2 2 2
8
In first sample, an optimal solution is:
- The elevator takes up person #1 and person #2.
- It goes to the 2nd floor.
- Both people go out of the elevator.
- The elevator goes back to the 1st floor.
- Then the elevator takes up person #3.
- And it goes to the 2nd floor.
- It picks up person #2.
- Then it goes to the 3rd floor.
- Person #2 goes out.
- Then it goes to the 4th floor, where person #3 goes out.
- The elevator goes back to the 1st floor.
题目大意:一楼有n个人等电梯。电梯的容量为k,。怎样用最少的时间把全部人都送到要去的楼层。当中楼梯的初、末位置均为1楼。
解题思路:贪心。这个贪心确实不太好想,智商不够。搞了好几天。先按楼层从小到大排序。最优的解是,先把电梯n%k个人放到他们要去的楼层。这是就会把k - (n%k)个人带到a[n%k]层。然后电梯再下去接k个人,途中下一部分。然后继续把原来那k - (n%k)个人带着继续上升,一直反复这样,就会刚好把全部人送到他们要去的楼层,而且保证是最优解。
AC代码:
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; int a[2005]; int main(){ // freopen("in.txt","r",stdin); int n, k; while(scanf("%d%d", &n, &k) == 2){ for(int i=0; i<n; i++){ scanf("%d", &a[i]); } sort(a, a+n); int ans = 0; for(int i=n-1; i>=0; i-=k) ans += 2*(a[i] - 1); printf("%d\n", ans); } return 0; }