题解 | #奥运排序问题#
奥运排序问题
https://www.nowcoder.com/practice/100a4376cafc439b86f5f8791fb461f3
#include "iostream"
#include "vector"
#include "algorithm"
using namespace std;
struct Country{
int G, M, P;
float G_P, M_P;
int r[4]; // 四种排序方式下的排名
int number;
};
bool compare1(Country a, Country b){
return a.G > b.G;
}
bool compare2(Country a, Country b){
return a.M > b.M;
}
bool compare3(Country a, Country b){
return a.G_P > b.G_P;
}
bool compare4(Country a, Country b){
return a.M_P > b.M_P;
}
bool compare5(Country a, Country b){ // 用于恢复原序
return a.number < b.number;
}
int main(){
int n, m;
while(scanf("%d%d", &n, &m) != EOF) {
vector<Country> temp(n);
for (int i = 0; i < n; i++) {
cin >> temp[i].G >> temp[i].M >> temp[i].P;
temp[i].number = i;
temp[i].G_P = (float) temp[i].G / (float) temp[i].P;
temp[i].M_P = (float) temp[i].M / (float) temp[i].P;
}
vector<Country> c; // 实际需要排名的国家
for (int i = 0; i < m; i++) {
int x;
cin >> x;
c.push_back(temp[x]); // 选出要求排名的国家
}
// 按金牌总数排序,计算 r[0]
sort(c.begin(), c.end(), compare1);
c[0].r[0] = 1;
for (int i = 1; i < m; i++) {
if (c[i].G == c[i - 1].G) c[i].r[0] = c[i - 1].r[0];
else c[i].r[0] = i + 1;
}
// 按奖牌总数排序,计算 r[1]
sort(c.begin(), c.end(), compare2);
c[0].r[1] = 1;
for (int i = 1; i < m; i++) {
if (c[i].M == c[i - 1].M) c[i].r[1] = c[i - 1].r[1];
else c[i].r[1] = i + 1;
}
// 按金牌人口比例排序,计算 r[2]
sort(c.begin(), c.end(), compare3);
c[0].r[2] = 1;
for (int i = 1; i < m; i++) {
if (c[i].G_P == c[i - 1].G_P) c[i].r[2] = c[i - 1].r[2];
else c[i].r[2] = i + 1;
}
// 按奖牌人口比例排序,计算 r[3]
sort(c.begin(), c.end(), compare4);
c[0].r[3] = 1;
for (int i = 1; i < m; i++) {
if (c[i].M_P == c[i - 1].M_P) c[i].r[3] = c[i - 1].r[3];
else c[i].r[3] = i + 1;
}
// 恢复原序
sort(c.begin(), c.end(), compare5);
// 输出
for(int i = 0;i < m; i++){
int rank = c[i].r[0], way = 1;
for(int j = 1; j < 4; j++){
if(c[i].r[j] < rank){
rank = c[i].r[j];
way = j + 1;
}
}
cout << rank << ':' << way << endl;
}
cout << endl;
}
}
OPPO成长空间 955人发布