01 题目:POJ 1852 Ants

来源:互联网 发布:关于数据库方面 编辑:程序博客网 时间:2024/05/16 08:21

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

Ants
Time Limit: 1000MS Memory Limit: 30000K
Total Submissions: 19204 Accepted: 8024
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

大意
  题目意思说有n只蚂蚁以1cm/s的速度在长L的竿子上爬行,在爬到竿子的一端的时候就会掉下去,同时当两只蚂蚁相遇时他们不能交错同行,只能各自往返,对于每只蚂蚁呢,我们知道了它距离竿子左端的位置xi,但不知道朝向,问所有蚂蚁落下的最短时间和最长时间。

思路:
  首先最简单的是暴力,但是数据量是1e6那就是说暴力必定会导致TLE,那我们可以先考虑一下两只蚂蚁相遇的时候会怎么样,最短的就是两者同时朝着离端点最短的方向走,那就是xi与L-xi中取min,那最长的情况就是两者要相遇,那相遇之后呢?相遇之后又各自往回走,如果按照这样的方式计算呢,跟之前的暴力是一样的,如果我们不看两只蚂蚁的区别只看他们走的路线你就会发现——他们所走的路线就是可以交叉通过之后的长度,那么对于每一个蚂蚁就是找出离端点的最长和最短时间就行了,然后在最短时间和最长时间里面找到最大值。是时间复杂度为O(n)的算法。

代码:

 /*挑战程序设计竞赛题解库题目:http://poj.org/problem?id=1852 AntsCreated by TyxMaek1997-2017*/#include <iostream>#include <string>#include <cstdio>#include <cstdlib>#include <cstring>#include <vector>#include <set>#include <map>#include <deque>#include <stack>#include <queue>#include <algorithm>#include <cmath>using namespace std;#define MAXN 1000009//#define Debug //提交时注释此行仅供本地数据测试时使用int main(){#ifdef Debug    freopen("in.txt", "r", stdin);#endif    int n, l, m;    scanf("%d", &n);    while (n--)    {        int maxt = 0, mint = 0;        int xi = 0;        scanf("%d%d", &l, &m);        while (m--)        {            scanf("%d", &xi);            maxt = max(maxt, max(xi, l - xi));//求最长时间            mint = max(mint, min(xi, l - xi));//求最短时间        }        printf("%d %d\n", mint, maxt);    }    return 0;}/*-----------------©TyxMaek1997-2017--------------------*/