#39386: C++ 2ms. struct, sort解


h3584935@gmail.com (高宇哲)

學校 : 不指定學校
編號 : 79959
來源 : [1.175.156.171]
最後登入時間 :
2024-02-12 22:31:37
m931. 1. 遊戲選角 -- 2024年1月APCS | From: [1.175.156.171] | 發表日期 : 2024-02-12 22:36

#include <iostream>
#include <algorithm>

 

using namespace std;

 

struct Power {
int a;
int b;
int total;
};

 

bool compare(struct Power p1, struct Power p2) {
return p1.total > p2.total;
}

 

int main() {
int num;
struct Power power[20];
cin >> num;
for(int i = 0; i < num; i++) {
    cin >> power[i].a;
    cin >> power[i].b;
    power[i].total = power[i].a * power[i].a + power[i].b * power[i].b;
}

 

    sort(power, power + num, compare);

 

    cout << power[1].a << " " << power[1].b;
}
 
這個解足夠AC,但是會複製一份struct Power的data到Compare裡面,是比較沒有效率的做法,所以需要改成用struct Power *來進行排序,這樣就只會排address

#include <iostream>
#include <algorithm>

using namespace std;

struct Power {
int a;
int b;
int total;
};

bool compare(struct Power* p1, struct Power* p2) {
return p1->total > p2->total;
}

int main() {
int num;
struct Power *power[20];
cin >> num;
for(int i = 0; i < num; i++) {
power[i] = (Power *)malloc(sizeof(struct Power));
cin >> power[i]->a;
cin >> power[i]->b;
power[i]->total = power[i]->a * power[i]->a + power[i]->b * power[i]->b;
}

sort(power, power + num, compare);
cout << power[1]->a << " " << power[1]->b;
}



 
 
ZeroJudge Forum