m931. 1. 遊戲選角 - 高中生程式解題系統

題目:

有 n 個角色,每個角色有攻擊力和防禦力。

角色的能力值是攻擊力和防禦力的平方和,輸出能力值第二大的攻擊力和防禦力數值。

保證每個角色的能力值相異。

<aside> 💡

使用迴圈搭配陣列(也可以像我C++的寫法 只用if_else 不使用陣列

(寫python可使用append及pop)

</aside>

python

list_a = []   #攻擊力
list_d = []   #防禦力
list_ad = []  #能力值

n = int(input())

for i in range(n):
    A = list(map(int, input().split()))
    list_a.append(A[0]) 
    list_d.append(A[1])   
    list_ad.append(A[0]**2 + A[1]**2)  

max_1 = list_ad.index(max(list_ad))   #找最大值
list_a.pop(max_1)  #移掉最大值
list_d.pop(max_1)
list_ad.pop(max_1)

max_2 = list_ad.index(max(list_ad))   #找次大
print(list_a[max_2],list_d[max_2])

c++

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int all,x,y,max1=0,max2=0,x1,y1,x2,y2;
	scanf("%d",&all);
	for (int i=0;i<all;i++)
		{
		scanf("%d %d",&x,&y);
		int p = x*x+y*y;
		if(p>max1){
			max2=max1;
			max1=p;
			x2=x1;y2=y1;
			x1=x;y1=y;} 
		
		else if(p<max1 && p>max2){
			max2=p;
			x2=x;y2=y;}
		}		
		printf("%d %d",x2,y2);
		
		return 0;
}