2024 1月 APCS 實作一 遊戲選角

有n個角色,每個角色有攻擊力和防禦力。
角色的能力值是攻擊力和防禦力的平方和,輸出能力值第二大的攻擊力和防禦力數值。
保證每個角色的能力值相異。
https://zerojudge.tw/ShowProblem?problemid=m931

這題可以用來練習structsort,當然還有其他更簡單的方法


首先引入sort需要的標頭檔

#include<iostream> #include<algorithm> //sort

接著最重要的struct部分(在主程式外用)

struct S { int d, f; bool operator<(S b) //自定義比較 { return d*d + f*f < b.d*b.d + b.f*b.f; } }; S people[100];

輸入

int n; cin >> n; for(int i = 0 ; i < n ; i++) cin >> people[i].f >> people[i].d;

輸出

sort(people, people+n); cout << people[n-2].f << " " << people[n-2].d;

n-2項就是平方和第二高所對應的數值了


完整程式碼

#include<iostream> #include<algorithm> using namespace std; struct S { int d, f; bool operator<(S b) { return d*d + f*f < b.d*b.d + b.f*b.f; } }; S people[100]; int main() { int n; cin >> n; for(int i = 0 ; i < n ; i++) cin >> people[i].f >> people[i].d; sort(people, people+n); cout << people[n-2].f << " " << people[n-2].d; return 0; }

掰掰:D