POJ1852 UVa10714 Ants【水题】

来源:互联网 发布:淘宝用工具吧怎样打折 编辑:程序博客网 时间:2024/05/22 06:58

Ants
Time Limit: 1000MS Memory Limit: 30000KTotal Submissions: 18360 Accepted: 7736

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

210 32 6 7214 711 12 7 13 176 23 191

Sample Output

4 838 207

Source

Waterloo local 2004.09.19


问题链接:POJ1852 UVa10714 Ants。

问题简述

很多的蚂蚁都在长度为l(cm)的横着的杆子上爬行,其速度均为1cm/s,蚂蚁到了杆子两头时就会掉下去。蚂蚁如果在爬行途中相遇,则两只蚂蚁都会逆转方向。已知蚂蚁在棒子的最初位置坐标,但是我们不知道他们会往哪一个方向爬。请求出所有蚂蚁掉下去的最短时间和最长时间。

问题分析

对一个一个蚂蚁进行穷举搜索显然不是一个好主意。

蚂蚁在位置p时,若往左其距离为p,若往右则其距离为l-p。

蚂蚁碰头后,仍然是一只往左另一只往右,所以可以看作是各自继续行走。

考虑最短时间,则对所有蚂蚁而言,每只蚂蚁取往左或往右取最短时间,然后从中找出最长时间。

考虑最长时间,则对所有蚂蚁而言,每只蚂蚁取往左或往右取最长时间,然后从中找出最长时间。

程序说明

全部使用C++的输入输出,有可能LTE,需要注意。

程序逻辑尽可能简洁,使用数组存储数据也是没有必要的。

程序中,使用了库函数max()和min(),使得程序代码十分简洁。

参考链接:(略)

题记:程序要简洁简洁再简洁。


AC的C++程序如下:

/* POJ1852 UVa10714 Ants */#include <iostream>#include <cstdio>using namespace std;int main(){    int t, l, n, pos, minans, maxans;    scanf("%d", &t);;    while(t--) {        minans = 0;        maxans = 0;        scanf("%d%d", &l, &n);        for(int i=1; i<=n; i++) {            scanf("%d", &pos);            minans = max(minans, min(pos, l - pos));            maxans = max(maxans, max(pos, l - pos));        }        printf("%d %d\n", minans, maxans);    }    return 0;}