POJ 1852 Ants
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ 1852 Ants相关的知识,希望对你有一定的参考价值。
POJ上的1852题,刚读完题有一种云里雾里的感觉,尤其是每只蚂蚁的运动方向不确定而且不能交错通过,更让人迷惑。
题目如下:
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
Source
Waterloo local 2004.09.19
挑战程序设计竞赛中提到用暴力搜索和递归函数可以实现解题,但是随着蚂蚁数量的增加,搜索的时间也会急剧增加。所以选择一个合适的算法才是最重要的。
首先思考最短时间,我们假设所有蚂蚁都朝向更近的端点,这种情况下不会出现两只蚂蚁碰撞。最短时间即为使所有蚂蚁都落下的时间。
其次是最长时间,我们先想象两只蚂蚁碰面再掉头,然而如果认为两只蚂蚁没有掉头而是交错通过也符合题意。所以,我们可以将每只蚂蚁的运动都看作独立运动,而最长时间也是蚂蚁离杆子端点的最大距离。
所以有以下代码:
#include<stdio.h>
#define maxn 100010
int 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<b) return a;
else return b;
}
void solve()
{
int minT=0,i;
for(i=0;i<n;i++) /*遍历每只蚂蚁,求每只蚂蚁的最小时间,并时刻更新minT*/
minT=max(minT,min(a[i],l-a[i]));
printf("%d ",minT); /*输出最小时间,注意加空格*/
int maxT=0;
for(i=0;i<n;i++) /*遍历每只蚂蚁,求每只蚂蚁的最大时间,并时刻更新maxT*/
maxT=max(maxT,max(a[i],l-a[i]));
printf("%d
",maxT); /*输出最大时间,注意要换行*/
}
int main()
{
int t,i;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&l,&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]); /*存储每只蚂蚁离左端点的距离*/
solve(); /*调用solve函数*/
}
return 0;
}
该算法时间复杂度O(n),对于10^6足够了,运行通过。
本题最大的惊喜应该是对于选手思维上的挑战和启发,将蚂蚁间相遇的情况考虑清楚后,借助一个循环就能轻松解决问题。实际上也不用考虑最长时间和最短时间问题,借助max和min函数即可解决问题。
以上是关于POJ 1852 Ants的主要内容,如果未能解决你的问题,请参考以下文章