本文共 2073 字,大约阅读时间需要 6 分钟。
POJ上的1852题,刚读完题有一种云里雾里的感觉,尤其是每只蚂蚁的运动方向不确定而且不能交错通过,更让人迷惑。
题目如下:DescriptionAn 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 32 6 7214 711 12 7 13 176 23 191Sample Output
4 8
38 207Source
Waterloo local 2004.09.19挑战程序设计竞赛中提到用暴力搜索和递归函数可以实现解题,但是随着蚂蚁数量的增加,搜索的时间也会急剧增加。所以选择一个合适的算法才是最重要的。
首先思考最短时间,我们假设所有蚂蚁都朝向更近的端点,这种情况下不会出现两只蚂蚁碰撞。最短时间即为使所有蚂蚁都落下的时间。
其次是最长时间,我们先想象两只蚂蚁碰面再掉头,然而如果认为两只蚂蚁没有掉头而是交错通过也符合题意。所以,我们可以将每只蚂蚁的运动都看作独立运动,而最长时间也是蚂蚁离杆子端点的最大距离。
所以有以下代码:
#include#define maxn 100010int a[maxn];int l,n;int max(int a,int b) /*max函数返回最大值*/ { if(a>b) return a; else return b;}int min(int a,int b) /*min函数返回最小值*/ { if(a
该算法时间复杂度O(n),对于10^6足够了,运行通过。
本题最大的惊喜应该是对于选手思维上的挑战和启发,将蚂蚁间相遇的情况考虑清楚后,借助一个循环就能轻松解决问题。实际上也不用考虑最长时间和最短时间问题,借助max和min函数即可解决问题。
转载于:https://blog.51cto.com/13990947/2286277