ZeroJudge H658: 捕魚 (Fishing)

題目敘述

每筆測資第一行有兩個正整數代表漁船的座標,第二行有一個正整數N,接下來會有N行,每行會有兩個正整數代表一個魚群的中心座標。要求輸出距離漁船最短距離的魚群的中心座標。


範例輸入 #1

5 6

1

10 10

範例輸出 #1

10 10


範例輸入 #2

8 2

3

7 9

10 3

5 1

範例輸出 #2

10 3


範例輸入 #3

20 15

7

25 34

100 0

12 51

3 9

37 22

10 71

2 36

範例輸出 #3

3 9


解題思路

因為計算座標距離會需要用到根號,可能會有無條件捨去或進位的錯誤發生導致誤判最小值,所以可以不用在計算座標時將答案進行根號計算。

解題程式碼如下 (僅供參考):

#include <iostream>
#include <math.h>
using namespace std;

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    int x, y;
    cin >> x >> y;
    int N;
    cin >> N;
    int ans = 9999999;
    pair<int, int>loc;
    for (int i = 0; i<N; i++)
    {
        int a, b;
        cin >> a >> b;
        int dis = pow(a-x, 2) + pow(b-y, 2);
        if (dis < ans)
        {
            ans = dis;
            loc.first = a;
            loc.second = b;
        }
    }
    cout << loc.first << " " << loc.second << "\n";
}

留言

這個網誌中的熱門文章

ZeroJudge M933: 邏輯電路

ZeroJudge A148: You Cannot Pass?!

ZeroJudge A263: 日期差幾天