题目描述
An army of ants walk on a horizontal pole of length l cm, each with a constant speed of 1 cm/s. When a walking ant reaches an end of the pole, it immediatelly falls off it. When two ants meet they turn back and start walking in opposite directions. We know the original positions of ants on the pole, unfortunately, we do not know the directions in which the ants are walking. Your task is to compute the earliest and the latest possible times needed for all ants to fall off the pole.
输入
The first line of input contains one integer giving the number of cases that follow. The data for each case start with two integer numbers: the length of the pole (in cm) and n, the number of ants residing on the pole. These two numbers are followed by n integers giving the position of each ant on the pole as the distance measured from the left end of the pole, in no particular order. All input integers are not bigger than 1000000 and they are separated by whitespace.
输出
For each case of input, output two numbers separated by a single space. The first number is the earliest possible time when all ants fall off the pole (if the directions of their walks are chosen appropriately) and the second number is the latest possible such time.
样例输入
2
10 3
2 6 7
214 7
11 12 7 13 176 23 191
样例输出
4 8
38 207
题目大意
一群蚂蚁在长度为1 cm的水平杆上行走,每根恒定速度为1 cm / s。当步行蚂蚁到达杆的一端时,它立即从杆上掉下来。当两只蚂蚁相遇时,他们转身开始向相反的方向行走。我们知道蚂蚁在杆子上的原始位置,不幸的是,我们不知道蚂蚁的行走方向。您的任务是计算所有蚂蚁掉下来所需的最早和最晚可能的时间。
输入
第一行是下面有几组数据
第二行第一个是杆的长度,第二个是蚂蚁的个数
第三行是每一个蚂蚁在杆上面的位置
理解
因为方向不确定,所有求的方法不一样。
只要离杆最远的蚂蚁都到达杆端了,那肯定所有蚂蚁都到了。
蚂蚁相遇,因为每只蚂蚁都是单独行走,所以只需要求出每一只蚂蚁的最优解就可以了。
对于最早的时间,我们只需要以蚂蚁离杆最近的一端为方向,然后找出所有蚂蚁中的最大值,就是最早的时间。
对于最晚的时间,我们只需要以蚂蚁离杆最远的一端为方向,然后找出所有蚂蚁中的最大值,就是最晚时间。
#include <iostream>
#include <algorithm>
#include <cstring>using namespace std;int main()
{
int t;int l,n;int mintime,maxtime;int ants;while(cin>>t){
while(t--){
mintime=0;maxtime=0;cin>>l>>n;for(int i=0;i<n;i++){
cin>>ants;mintime=max(mintime,min(ants,l-ants));//找出最早时间,取离杆端最小的值maxtime=max(maxtime,max(ants,l-ants));//找出最晚时间,取离杆端最大的值}cout<<mintime<<" "<<maxtime<<endl;}}return 0;
}