原题链接
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
题解思路
这道题相对比较简单,其实容易卡住人的点就是一个思维的转变;
针对于每一个输入实例,我们可以先观察任意两只蚂蚁,题目所说的,当两只蚂蚁相遇时,它们就会转变前进的方向,然后一直前进,直到到达杆的尽头;
然后要求我们根据给定的初始位置分别设定两只蚂蚁的前进方向,来求得这两只蚂蚁能行走的最大路程和最小路程;
其实这句话我们可以这样理解:当两只蚂蚁相遇时,它们不会转变前进方向,而是绕过对方继续前行;这种情况下它们行走的总路程与原题的情况并无差别!
其实这很容易理解,因为对于任意两只蚂蚁并无任何差别,是否转向还是一样要行走那么多路程,你可以理解为当它们相遇时,一只蚂蚁走了另一只蚂蚁本该行走的路程,但它们的总路程是不变的;
只要理解了上面,接下来就容易解决了;
在这个前提下,我们可以把距离蚂蚁初始化位置最近的一端设置为蚂蚁的前进方向,当所有的蚂蚁都这般设置之后,它们的路程总和也就能达到最小值了!
一样的道理,我们把距离蚂蚁的初始化位置最远的一端设置为蚂蚁的前进方向,就可求得总路程的最大值了!
代码如下
/*
题解:当两只蚂蚁相遇时,调转方向,其实等同于按原先方向前进,因为每只蚂蚁都一样,在同一个点(相遇时)到两端距离一样
*/
#include<iostream>
#include<cmath>
#include<string>
#include<iomanip>
#include<map>
#include<algorithm>
#include<bitset>
#include<vector>
using namespace std;
int L, n;
vector<int>a(n);
void fun()
{
int Min = 0, Max = 0;
for (int i = 0; i < n; i++)
{
/*
分别比较每一只蚂蚁与杆两端的距离,选取较短的那方为蚂蚁前进的方向
再选所有蚂蚁前进路程的最大值(保证每一只蚂蚁都能通过),即为总时间的最小值
*/
Min = max(Min, min(a[i], L - a[i]));
}
for (int i = 0; i < n; i++)
{
/*
分别比较每一只蚂蚁离杆两端的距离,每一只都取数值较大的一端为前进方向
*/
Max = max(Max, max(a[i], L - a[i]));
}
cout << Min << " " << Max << endl;
}
int main()
{
int sum;
cin >> sum;
while (sum--)
{
cin >> L >> n;
for (int i = 0; i < n; i++)
{
int z;
cin >> z;
a.push_back(z);
}
fun();
a.clear();
}
return 0;
}
如果此文能够帮助到您,烦请点赞收藏,嘻嘻!
以上内容如有不足,请谅解并欢迎指出,最后附上本人微信公众号,欢迎大家一起讨论学习,更多精彩内容请关注公众号:“艺千秋录”,欢迎留言共同进步;
在公众号留言“书籍”可以免费领取大量计算机专业书籍!