POJ 1852: Ants
——AD HOC
原题传送门
变版传送门
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.
Data
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.
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
All input integers are not bigger than 1000000 and they are separated by whitespace.
思路
这是一道很好鬼畜的题目
直接模拟?直接否定.(你行你试试)
那么,为什么需要21000000的复杂度呢?
因为每只蚂蚁都需要判断左与右两种情况.
那为什么不对连续几个蚂蚁判断呢?
因为,每只蚂蚁都有初始方向.
那,真的不一样吗?
对于两只蚂蚁①和②,可以看看 在两只蚂蚁相遇时会发生什么.
根据题意,两只蚂蚁相遇后会以原速相离而去.
就像这样.
那对于两只蚂蚁,它们相遇以后变化了什么呢?
两只蚂蚁的方向变了.
那这两只蚂蚁有区别吗?
没有区别!
换句话,这只蚂蚁和那只蚂蚁是一样的!
那两只蚂蚁相遇时,直接假设它们按原速继续行走不就好了!我真聪明
这就很简单了, O(n) 算法于是诞生.
枚举所有蚂蚁的位置,每次对最短时间和最长时间求最大值即可(这里有点绕可以花时间自己理解 )
而最短时间等价于最短距离.
所以,代码其实很简单:
Code
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=1e6+5;
int L,n,x;
int main()
{
// IQ up to 1000
int T;
scanf("%d",&T);
while (T--)
{
scanf("%d%d",&L,&n);
int mx=0,mi=0;
for (int i=1;i<=n;i++)
{
scanf("%d",&x);
mx=max(mx,max(x,L-x));
mi=max(mi,min(x,L-x));
}
printf("%d %d\n",mi,mx);
}
return 0;
}
后记
一道很考验智商的题目.
LUOGU 的题目描述稍有不同,可以思考如何修改代码.
感谢奆老关注 qwq ?