Ants (POJ 1852)

题目描述:

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

代码如下:

 1 #include<iostream>
 2 int Max(int,int);
 3 int Min(int,int);
 4 int main()
 5 {
 6     using namespace std;
 7     int i;
 8     cin >> i;
 9     while(i--)
10     {
11         int l;
12         int num;
13         cin >> l >> num;
14         int* pt = new int [num];
15         for(int j = 0;j < num;j++)
16             cin >> pt[j];
17         int min_ = 0,max_ = 0;
18         for(int j = 0;j < num;j++)
19             min_ = Max(min_,Min(pt[j],l - pt[j]));//最小时间是蚂蚁爬向最近一端
20         for(int j = 0;j < num;j++)
21             max_ = Max(max_,Max(pt[j],l - pt[j]));//无视不同蚂蚁的区别,可以认为是保持原样交错而过
22         cout << min_ << " " << max_ << endl;
23         delete [] pt;
24     }
25     return 0;
26 }
27 
28 int Max(int a,int b)
29 {
30     return a > b ? a : b;
31 }
32 
33 int Min(int a,int b)
34 {
35     return b > a ? a : b;
36 }

代码分析:

这道题目的难度不在于用到什么算法,而在于想明白两只蚂蚁相遇然后返回,等同于无视蚂蚁的区别,保持原样交错而过。所以有的题目有时候想多了,反而不得解。

参考书籍:[挑战程序设计竞赛第2版]

原文地址:https://www.cnblogs.com/linxiaotao/p/3418578.html