POJ1852 -- Ants
题目
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.
Input
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.
Output
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.
Sample Input
2
10 3
2 6 7
214 7
11 12 7 13 176 23 191
Sample Output
4 8
38 207
题意:有一根长为Lcm的水平杆,一群蚂蚁以1cm/s的速度爬行在这根杆上。当一只蚂蚁爬行到杆的端点时立即下落,当两只蚂蚁相遇时,立即各自调头往回走。我们知道每一只蚂蚁它距离左端杆的距离xi,但是我们不知道他们的初始方向。你的任务是计算所有蚂蚁都掉落水平杆的最短和最长的时间。
输入第一行为一个整数T,代表共有T个样例。
每个样例第一行为两个整数,len为水平杆的长度,n为蚂蚁数量。
第二行为n个整数,代表第 i 个蚂蚁的初始位置。(所有的数据都不超过)
对于每一个样例的输出为两个整数,分别为所有蚂蚁落下这根杆所需最短时间和最长时间。
解析:首先想到肯定是爆搜,不过这里数据比较大,肯定会T掉。然后我们可以巧妙的发现,所有蚂蚁掉落的最短时间其实就是离杆最近的蚂蚁且头朝向较近的端点走肯定是它们每个蚂蚁所需的最短时间,然后求它们所有中最大的最短时间就是所有蚂蚁掉落下杆的最短时间。求所有蚂蚁掉落的最大时间时,我们可以不考虑两只蚂蚁碰到后继续按原方向前进,因为是求所有蚂蚁掉落的最长时间,那肯定是等到最后一个掉下去才截止计时,所以只需求出离两个端点的最大距离那个端点即可。
AC代码:
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1e6 + 5;
int t, n, l, minT, maxT;
int x[maxn];
int main()
{
cin >> t;
while(t--)
{
minT = 0, maxT = 0;
cin >> l >> n;
for(int i = 1; i <= n; i++)
cin >> x[i];
//计算最短时间
for(int i = 1; i <= n; i++)
minT = max(minT, min(x[i], l - x[i]));
//计算最长时间
for(int i = 1; i <= n; i++)
maxT = max(maxT, max(x[i], l - x[i]));
cout << minT << " " << maxT << endl;
}
return 0;
}

浙公网安备 33010602011771号