POJ 1852 — Ants

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

题目链接

http://poj.org/problem?id=1852

题目翻译

n只蚂蚁以每秒1cm的速度在长为Lcm的竹竿上爬行。当蚂蚁看到竿子的端点时就会落下来。由于竿子太细,两只蚂蚁相遇时,它们不能交错通过,只能各自反方向爬行。对于每只蚂蚁,我们只知道它离竿子最左端的距离为xi,但不知道它当前的朝向。请计算所有蚂蚁落下竿子的最短时间和最长时间。
1<=L<=10^6,1<=n<=10^6,0<=xi<=L

题目分析

首先,所有蚂蚁落下竿子的最短时间和最长时间,指的是最后一个落下的蚂蚁使用的时间,而不是所有蚂蚁使用的时间之和。
先来分析一下两只蚂蚁相遇后发生了什么,蚂蚁相遇后会调头,但是对于一群蚂蚁来说,相当于这两只蚂蚁交错通过了。也就是说,如果我们关注的是蚂蚁下落这个问题,可以看作一只蚂蚁🐜一直向当前方向运动,与别的蚂蚁相遇也没有任何影响。我们关心的是有蚂蚁下落,而不关心具体是哪一只蚂蚁下落。
这样就简单多了。
最短时间就是让所有蚂蚁向较近端点移动,只要找到最长的(距较近端点的距离)即可。事实上,即使没有刚刚对蚂蚁相遇的分析,这样计算最短时间也是合理的,因为所有蚂蚁向较近端点移动时,不会出现蚂蚁相遇的情况。
最长时间就是让所有蚂蚁向较远端点移动,只要找到最长的(距较远端点的距离)即可。

AC代码

#include <iostream>
#include <cstdio>
using namespace std;

int x[1000005];
int main()
{
    int t, l, n, i, minans, maxans;
    scanf("%d", &t);
    while (t--)
    {
        minans = maxans = 0;
        scanf("%d%d", &l, &n);
        for (i = 0; i < n; i++)
        {
            scanf("%d", &x[i]);
            minans = max(minans, min(x[i], l - x[i]));
            maxans = max(maxans, max(x[i], l - x[i]));
        }
        printf("%d %d\n", minans, maxans);
    }
    return 0;
}

注意事项

数据量较大,要使用 scanf 读入数据。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部