Ferry Loading II_贪心

时间:2023-03-08 20:11:33
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

【题意】给出m辆车达到码头的时间,小船每次只能运过去n辆车,耗时t一趟。求最短时间和次数

【思路】贪心

  1. 最短时间只和最后一只船有关系. 如果 m%n==0 则每次都运n个,必是最优。
  2. 否则,第一次运 m%n个, 可保证最优。
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int n,m,t;
int main()
{
int ti;
scanf("%d",&ti);
while(ti--)
{
scanf("%d%d%d",&n,&t,&m);
int a=m%n;
int k=m/n;
if(a!=)//余数不为0,多运一次
{
k++;
}
int mint=;
int tmp;
int i=;
if(a)//余数不为0,第一次将a辆车运过去
{
for(i=;i<a;i++)
{
scanf("%d",&tmp);
}
mint=tmp+*t;//a辆车中最后一辆车达到的时间出发
}
int cnt=;
while(i<m)//另外的m/n组
{
scanf("%d",&tmp);
cnt++;
if(cnt==n)//到n一组的车辆
{
if(tmp>mint)//时间晚的话,从tmp时间出发
mint=tmp+*t;
else mint+=*t;//时间早的话,直接出发,没有等待时间
cnt=;//清零
}
i++;
}
mint-=t;//最后一趟,不用回来了
printf("%d %d\n",mint,k);
}
return ;
}