题解 | #奥运排序问题#
奥运排序问题
https://www.nowcoder.com/practice/100a4376cafc439b86f5f8791fb461f3
用结构体加sort花了4个小时,机试考这种题我直接暴毙而亡
#include<iostream> #include<algorithm> using namespace std; typedef struct Country { int gold; int pedal; int population; int l1, l2, l3, l4; int order; //记录顺序 }country; //定义四种排名方式 bool compare1(country lhs, country rhs) { if (lhs.gold > rhs.gold) return true; else return false; } bool compare2(country lhs, country rhs) { if (lhs.pedal > rhs.pedal) return true; else return false; } bool compare3(country lhs, country rhs) { if (1.0 * lhs.gold / lhs.population > 1.0 * rhs.gold / rhs.population) return true; else return false; } bool compare4(country lhs, country rhs) { if (1.0 * lhs.pedal / lhs.population > 1.0 * rhs.pedal / rhs.population) //利用乘以1.0来实现格式转换 return true; else return false; } bool compare5(country lhs, country rhs) { if (lhs.order < rhs.order) return true; else return false; } int main() { country con[20]; int n, m; int arr[10]; //要求排名的国家号 while (cin >> n >> m) { for (int i = 0; i < n; i++) { //输入 cin >> con[i].gold >> con[i].pedal >> con[i].population; con[i].order = i; } for (int i = 0; i < m; i++) cin >> arr[i]; //输入要求排名的国家号 sort(con, con + n , compare1); con[0].l1 = 1; for (int i = 1,j=1; i <= n; i++) { if (con[i].gold == con[i - 1].gold) { con[i].l1 = con[i - 1].l1; } else con[i].l1 = i + 1; } sort(con, con + n, compare2); con[0].l2 = 1; for (int i = 1; i <= n; i++) { if (con[i].pedal == con[i - 1].pedal) { con[i].l2 = con[i - 1].l2; } else con[i].l2 = i+1; } sort(con, con + n, compare3); con[0].l3 = 1; for (int i = 1; i <= n; i++) { if (1.0 * con[i].gold/con[i].population == 1.0*con[i - 1].gold/con[i-1].population ) { con[i].l3 = con[i - 1].l3; } else con[i].l3 = i+1; } sort(con, con + n, compare4); con[0].l4 = 1; for (int i = 1; i <= n; i++) { if (1.0 * con[i].pedal / con[i].population == 1.0 * con[i - 1].pedal / con[i - 1].population) { con[i].l4 = con[i - 1].l4; } else con[i].l4 = i+1; } sort(con, con + n, compare5); for (int i = 0; i < m; i++) { //输出结果 if(con[arr[i]].l1<=con[arr[i]].l2 && con[arr[i]].l1 <= con[arr[i]].l3 && con[arr[i]].l1 <= con[arr[i]].l4) cout << con[arr[i]].l1 << ':' << 1 << endl; else if (con[arr[i]].l2 <= con[arr[i]].l1 && con[arr[i]].l2 <= con[arr[i]].l3 && con[arr[i]].l2 <= con[arr[i]].l4) cout << con[arr[i]].l2 << ':' << 2 << endl; else if (con[arr[i]].l3 <= con[arr[i]].l1 && con[arr[i]].l3 <= con[arr[i]].l2 && con[arr[i]].l3 <= con[arr[i]].l4) cout << con[arr[i]].l3 << ':' << 3 << endl; else if (con[arr[i]].l4 <= con[arr[i]].l1 && con[arr[i]].l4 <= con[arr[i]].l2 && con[arr[i]].l4 <= con[arr[i]].l3) cout << con[arr[i]].l4 << ':' << 4 << endl; } cout << endl; } }