POJ 1852:Ants【规律】

Ants
Time Limit: 1000MS   Memory Limit: 30000K
Total Submissions: 12914   Accepted: 5654

Description

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
 
  

题目大意:很多的蚂蚁都在长度为L(cm)的膀子上爬行,它们的速度都是1cm/s,到了棒子终端的时候,蚂蚁就会掉下去。如果在爬行途中遇到其他蚂蚁,两只蚂蚁的方向都会逆转。已知蚂蚁在棒子的最初位置坐标,但是我们不知道他们会往哪一个方向爬。请求出所有蚂蚁掉下去的最短时间和最长时间。

题目分析:虽然当蚂蚁数量很多的时候情况会有很多种,但是先考虑小数量的分析就可以找到解决方法:如果只有两只的话,那么最短时间就是两只蚂蚁距离两端点距离较小的距离中取大者就是所需最短时间,而最长时间就是两只蚂蚁距离两端点距离较大者中取大者就是所需最长时间,例如,长度为10,一只在距离左端2的位置,一只在距离左端6的位置,则最短时间为max(min(2,10-2),min(6,10-6))为4,最长时间为max((max(2,10-2),max(6,10-6)))为8其实就是两只相向而行,当相遇后,都转为逆向,则时间为从相遇点到端点距离大者与相遇前所需时间,分析实际就是2到10的距离,当蚂蚁数量增加时,情况相同

则需要时间最长的的就是让距离端点最近的蚂蚁爬到另一个端点(最远)所需要的时间。
也就是说,只要找出所有蚂蚁与较远端比较,然后找出最大值就是所需要的最大时间
在距离短的一边中求出最大的一边。就能找到距离端点最远的蚂蚁需要爬到端点的时间

AC-code:
 
  
#include
#define inf 0x3f3f3f3f
#define min(a,b) a>b?b:a
#define max(a,b) a


你可能感兴趣的:(ACM成长脚印)