Ferry Loading II
Description
Before bridges were common, ferries were used to transport cars across rivers. River ferries, unlike their larger cousins, run on a guide line and are powered by the river’s current. Cars drive onto the ferry from one end, the ferry crosses the river, and the cars exit from the other end of the ferry.
There is a ferry across the river that can take n cars across the river in t minutes and return in t minutes. m cars arrive at the ferry terminal by a given schedule. What is the earliest time that all the cars can be transported across the river? What is the minimum number of trips that the operator must make to deliver all cars by that time?
Input
The first line of input contains c, the number of test cases. Each test case begins with n, t, m. m lines follow, each giving the arrival time for a car (in minutes since the beginning of the day). The operator can run the ferry whenever he or she wishes, but can take only the cars that have arrived up to that time.
Output
For each test case, output a single line with two integers: the time, in minutes since the beginning of the day, when the last car is delivered to the other side of the river, and the minimum number of trips made by the ferry to carry the cars within that time.
You may assume that 0 < n, t, m < 1440. The arrival times for each test case are in non-decreasing order.
Sample Input
2 2 10 10 0 10 20 30 40 50 60 70 80 90 2 10 3 10 30 40
Sample Output
100 5 50 2
思路
第i个车可以与前0~n-1个车拼船,得到将前i个车过河所需要的最短时间。注意可以不需要特地去关注趟数是否能够更新,这里用了一个贪心。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,t,m;
int arrTime[1500];
int dp[1500];
int step[1500];
int main(){
int k;
scanf("%d",&k);
while (k--){
memset(dp,0x3f3f3f3f,sizeof(dp));
memset(step,0x3f3f3f3f,sizeof(step));
scanf("%d%d%d",&n,&t,&m);
for (int i=1;i<=m;i++){
scanf("%d",&arrTime[i]);
}
for (int i=1;i<=n&&i<=m;i++){
dp[i]=arrTime[i]+t;
step[i]=1;
}
for (int i=n+1;i<=m;i++){
for (int j=n;j>0;j--){//这层循环为什么要倒着写???行吧。。。因为这一趟越少说明之前的运送的越多
if (max(dp[i-j]+t,arrTime[i])+t<dp[i]){
dp[i]=max(dp[i-j]+t,arrTime[i])+t;
step[i]=step[i-j]+1;
}
}
}
printf("%d %d\n",dp[m],step[m]);
}
return 0;
}
我在一个细节上卡了一下:注释的那个循环,我原先是升序j的,一开始没想明白为什么要降序。