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

題目大意:

一根水平的棍子上有n只螞蟻, 每隻螞蟻在離棍子左端x m遠以1m/s的速度以任意方向在棍子上爬行, 若兩隻螞蟻相遇則會掉頭, 問所有螞蟻掉落的最長最短時間分別是多少。

解題思路:

首先我們並不知道螞蟻的初始方向是朝着哪邊爬行, 所以我們把所有螞蟻離散化(其實就是把一隻螞蟻看成所有螞蟻), 那麼問題就變成了求一隻螞蟻掉落的最長時間和最短時間。 因爲棍子有兩端, 所以我們要計算出螞蟻距離棍子兩端的距離。 對於最短時間, 我們取每隻螞蟻離棍子較短的那個值, 因爲要保證所有螞蟻都掉落, 所以我們在所有螞蟻的最小時間裏取最大值, 同樣對於最長時間我們則是取所有螞蟻對於棍子最長距離裏取最大值。

代碼:

#include <iostream>
#include <sstream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iomanip>
#include <utility>
#include <string>
#include <cmath>
#include <vector>
#include <bitset>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>

using namespace std;

/*tools:
 *ios::sync_with_stdio(false);
 *freopen("input.txt", "r", stdin);
 */

typedef long long ll;
typedef unsigned long long ull;
const int dir[5][2] = {0, 1, 0, -1, 1, 0, -1, 0, 0, 0};
const ll ll_inf = 0x7fffffff;
const int inf = 0x3f3f3f;
const int mod = 1000000;
const int Max = (int) 1e6 + 7;

int n, m, num;

int main() {
    //freopen("input.txt", "r", stdin);
    int t;
    scanf("%d", &t);
    while (t--) {
        int minx = -1, maxx = -1;
        scanf("%d %d", &n ,&m);
        for (int i = 0; i < m; ++i) {
            scanf("%d", &num);
            minx = max(min(num, n - num), minx);
            maxx = max(max(num, n - num), maxx);
        }
        printf("%d %d\n", minx, maxx);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章