Ants(POJ 1852) (UVa:10714)

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

题目大意:题中每组数据给出蚂蚁洞的长度、蚂蚁的个数及每只蚂蚁的位置,即从洞左端测量的距离( n integers giving the position of each ant on the pole as the distance measured from the left end of the pole)。蚂蚁开始走的速度大小一样方向不定,且两只蚂蚁相遇都会改变方向,每只蚂蚁走到洞边缘停下,要求蚂蚁全部走到洞边缘所用的最短和最长时间。

解题思路:首先如果两个蚂蚁相遇,题中说改变方向,其实可以看做,蚂蚁继续按原方向走。
先说最长时间,我的解法是先用数组存数据,然后从小到大排序,答案就是 max(总距离 - a[0], a[n-1]),即这两个结果中最大的数,就是走的最长距离 * 1就是最长时间。
最短时间要使所有蚂蚁都走到洞的边缘,则按中点分,中点前的蚂蚁向左走,其余向右走,能保证最短时间且没有蚂蚁相遇。计算最短时间,就要先求得中点两边的蚂蚁走的距离,选取最大值 * 1就是最短时间。不能选最小值,因为这样一定会有一只蚂蚁还没走到终点。

#include<stdio.h>
#include<algorithm>
#include<math.h>
using namespace std;
#define SF(n) scanf("%d",&n)

int ant[1000005];
int main()
{
    int i,j;
    double mid;
    int t,n,distance;
    int ans_e,ans_l,ans;
    SF(t);
    while(t--)
    {
        SF(distance);
        SF(n);
        for(i=0; i<n; ++i)
            SF(ant[i]);
            
        sort(ant,ant+n);
        mid = distance/2.0;
        
        for(i=0; i<n; ++i)
            if(ant[i]>=mid)
                break;

        ans_e = distance-ant[i];   //中点右边的蚂蚁走的距离
        i--;
        ans = ant[i];	//中点左边的蚂蚁走的距离

        ans_e = max(ans,ans_e);		//最短时间

        ans_l = max(ant[n-1],distance-ant[0]);  //最长时间
        printf("%d %d\n",ans_e,ans_l);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

葛济维的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值