Ants(POJ NO.1852)
总Time Limit: 1000ms
Memory Limit: 65536kB
Question
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
My Hints
Algorithm
首先容易想到蛮力搜索,即枚举所有蚂蚁的初始朝向组合。若n较小时还尚可接受,但组合数随n增大而呈指数爆炸趋势。
故应改变算法思想:
- 对于最短时间,看起来蚂蚁都朝向较近的短点走较好
- 为了思考最长时间的情况,我们看看蚂蚁相遇时会发生什么:
由此看来,蚂蚁相遇后,当它们保持原样交错而过继续前行也无任何问题。即蚂蚁的运动均可看做独立。故要求最长时间,只要求蚂蚁到杆子端点的最大距离就好了。
这样,不论最长时间还是最短时间,都只要对每只蚂蚁检查一次就好了,时间复杂度为O(n),对于限制条件
n≤106此算法够用了。
Codes
@ hzhang_97@foxmail.com
// Author: Florence
// Created Time: 2017/07/24 11:24
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char** argv) {
int cases,len,num,xtemp;
cin >> cases;
for(int i = 0;i < cases;i ++){
cin >> len >> num;
int x[num];
int MinT = 0,MaxT = 0;
for(int j = 0;j < num;j++){
cin >> x[j];
xtemp = len - x[j];
//计算最短时间
MinT = max(MinT,min(x[j],xtemp));
//计算最长时间
MaxT = max(MaxT,max(x[j],xtemp));
}
cout << MinT << " " << MaxT << endl;
}
return 0;
}
这个问题可以说是考察想象力类型的经典例子。通过分析之后,程序并不难实现。
参考资料: 《挑战程序设计竞赛(第2版) 1 .