链接:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=113&page=show_problem&problem=1655
原题:
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.
2 10 3 2 6 7 214 7 11 12 7 13 176 23 191
4 8 38 207
题目大意:
一根棍子上有蚂蚁, 这些蚂蚁朝着一个方向以相同的速度(每秒一个单位长度)一直走(可能是往棍子的任意一端走),一旦蚂蚁碰到迎面走来的一直蚂蚁,那么这两只蚂蚁都会马上往相反方向走。求当所有蚂蚁都会走下棍子的,花费的最小的和最大时间。
分析与总结:
对于每一只蚂蚁,它在棍子上面,距离左端点和右端点的距离可能是相等的也可能是不同的。暂时把距离远的那端叫做远端,距离近的那端叫做近端。
那么为了使得所有花时间最短,就要让所有的蚂蚁都往近端走,最后总间取决于所有蚂蚁中近端最远的那只蚂蚁,它的时间即是最小时间花费。
同理可推得,要使得所花时间最长,就要让所有蚂蚁都往远端走,这样最后长时间取决于所有蚂蚁中的远端最远的那只蚂蚁。
不用去考虑两只蚂蚁碰头的情况, 因为离远端最远的那只一定是在最右边或者最左边的那只蚂蚁,那么当它往远端方向走时,可能会碰到迎面走来的,那么他马上往回走,对面那只也往回走走,这就相当于“接力”过程,即对面那只蚂蚁替他走这一段本该由他走的路程(整个过程可能会有无数次“接力”,但最终结果都是一样的,只是这段最远路程变成由很多只蚂蚁一起完成)。
描述的有点挫,慢慢意会吧。
代码:
/* * UVa: 10714 Ants * Result: Accept * Time: 0.072s * Author: D_Double */ #include<iostream> #include<cstdio> #include<cstring> using namespace std; inline int max(int a,int b){ return a>b?a:b; } inline int min(int a,int b){ return a<b?a:b; } int main(){ int nCase, len, n, dist; scanf("%d",&nCase); while(nCase--){ scanf("%d%d",&len, &n); int minLen = -100, maxLen = -100; for(int i=0; i<n; ++i){ scanf("%d",&dist); maxLen = max(maxLen, max(dist, len-dist)); minLen = max(minLen, min(dist, len-dist)); } printf("%d %d\n", minLen, maxLen); } return 0; }
—— 生命的意义,在于赋予它意义。
原创 http://blog.csdn.net/shuangde800 , By D_Double (转载请标明)