# **2024 1月 APCS 實作一 遊戲選角** :::warning 有n個角色,每個角色有攻擊力和防禦力。 角色的能力值是攻擊力和防禦力的平方和,輸出能力值第二大的攻擊力和防禦力數值。 保證每個角色的能力值相異。 https://zerojudge.tw/ShowProblem?problemid=m931 ::: 這題可以用來練習**struct**和**sort**,當然還有其他更簡單的方法 *** **首先引入sort需要的標頭檔** ```cpp= #include<iostream> #include<algorithm> //sort ``` *** **接著最重要的struct部分(在主程式外用)** ```cpp= 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]; ``` *** **輸入** ```cpp= int n; cin >> n; for(int i = 0 ; i < n ; i++) cin >> people[i].f >> people[i].d; ``` *** **輸出** ```cpp= sort(people, people+n); cout << people[n-2].f << " " << people[n-2].d; ``` n-2項就是平方和第二高所對應的數值了 *** :::success 完整程式碼 ::: ```cpp= #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; } ``` :::success 掰掰:D :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up