2012-06-01 22:20:41Morris

[UVA] 10714 - Ants

Problem B: 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.

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.

Sample input

 
2
10 3
2 6 7
214 7
11 12 7 13 176 23 191

Output for sample input

4 8
38 207

這題有一個很妙的想法, 兩隻螞蟻相撞會回頭 等效於 兩隻螞蟻繼續向前,
也就是說最慢的時間是 某隻螞蟻往左或右的最大值 中的最大值,
反之則是 最小值 中的最大值

#include <stdio.h>

int main() {
int t, x;
scanf("%d", &t);
while(t--) {
int l, n, min = 0, max = 0;
scanf("%d %d", &l, &n);
while(n--) {
scanf("%d", &x);
x = x < l-x ? x : l-x;
if(x > min)
min = x;
if(l-x > max)
max = l-x;
}
printf("%d %d\n", min, max);
}
return 0;
}