《挑战程序设计竞赛》1.6 轻松热身 POJ1852

Ants
Time Limit: 1000MS   Memory Limit: 30000K
Total Submissions: 12782   Accepted: 5596

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


思路:

大意是蚂蚁在杆子上爬行,方向未知,如果相遇时会各自反向爬回去。计算所有蚂蚁落下杆子所需的最短时间和最长时间。

穷竭算法比较容易想到,枚举所有蚂蚁初始朝向的组合然后验证,复杂度为2^N,显然太高了。

其实这个题有比较巧的思路,蚂蚁相遇时两只蚂蚁若交换,就好像两个蚂蚁仍然按照自己原来的路线走一样。所以压根不需要考虑相遇而进行多次模拟。

那么其实只要检查两端的两只蚂蚁即可。


代码:

Problem: 1852		User: liangrx06
Memory: 740K		Time: 141MS
Language: G++		Result: Accepted
Source Code
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

int main(void)
{
    int t, n, len;
    int pos, minT, maxT;

    cin >> t;
    while (t--)
    {
        cin >> len >> n;
        maxT = 0;
        minT = 0;
        while (n--)
        {
            scanf("%d", &pos);
            maxT = max(maxT, max(pos, len-pos));
            minT = max(minT, min(pos, len-pos));
        }
        printf("%d %d\n", minT, maxT);
    }

    return 0;
}


posted on 2015-12-08 23:42  梁山伯  阅读(250)  评论(0编辑  收藏  举报

导航