a382中等排序・保留原始資料

APCS 2024/01:遊戲選角 (ZeroJudge m931)

以平方和排名角色,再輸出第二名的原始攻防數值。

前往題目練習 →回報教學錯誤時間 O(n log n),空間 O(n)。

這題在學什麼

每個角色的比較鍵是 a²+d²,不是 a+d,也不需開根號。把這個鍵與原本的 a、d 一起存成紀錄,依鍵由大到小排序後,索引 1 就是第二高者。

題目保證能力值互異,所以不用處理並列名次。排序使前面的角色能力嚴格較高,因此第二筆恰有一個角色比它強;輸出其 a、d 而非平方和即可。n≤20,直接排序足夠且容易查核。

Step-by-step animation

公開範例 1:三個角色

回報動畫錯誤
步驟 1 / 3

建立排序鍵

三筆能力依序為 3²+1²=10、5²+2²=29、1²+4²=17。

(3,1):10
(5,2):29
(1,4):17
角色數
3

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
struct Hero {
    int power, attack, defense;
};
int main() {
    int n;
    cin >> n;
    vector<Hero> heroes(n);
    for (auto &hero : heroes) {
        cin >> hero.attack >> hero.defense;
        hero.power = hero.attack * hero.attack + hero.defense * hero.defense;
    }
    sort(heroes.begin(), heroes.end(),
         [](const Hero &a, const Hero &b) { return a.power > b.power; });
    cout << heroes[1].attack << ' ' << heroes[1].defense << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多