ZeroJudge M931: 遊戲選角

題目敘述

每筆資料第一行有一個正整數N,接下來會有N行,每行有兩個整數a和b。要求將a和b的平方和做排序後將第二大的平方和的a和b做輸出。


範例輸入 #1

3

3 1

5 2

1 4

範例輸出 #1

1 4


範例輸入 #2

6

6 6

1 3

8 6

5 4

2 8

7 2

範例輸出 #2

6 6


範例輸入 #3

5

34 35

84 32

39 79

59 89

59 31

範例輸出 #3

84 32


解題思路

可以將a和b的平方和存到一個陣列/Vector中,然後使用Map將平方和作為Key,存的資料可以使用Pair來存,這樣就可以一次存兩個數字。使用Sort將陣列中的資料做排序後只要輸出倒數第二個位子的Map值即可。

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

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    int N;
    cin >> N;
    vector<long long int>num;
    map<long long int, pair<int, int>>MAP;
    for (int i = 0; i<N; i++)
    {
        int a, b;
        cin >> a >> b;
        long long int tmp = (a*a) + (b*b);
        num.push_back(tmp);
        MAP[tmp].first = a;
        MAP[tmp].second = b;
    }
    sort(num.begin(), num.end());
    long long int tmp = num[num.size()-2];
    cout << MAP[tmp].first << " " << MAP[tmp].second << "\n";
}

留言