题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; struct student { public: string name; int grade; int order; student() = default; student(string& a, int b, int c): name(a), grade(b), order(c) {} }; bool compare_1(const student& a, const student& b) { return a.grade < b.grade; } bool compare_2(const student& a, const student& b) { return a.grade > b.grade; } int main() { int n; cin >> n; int way; cin >> way; vector<student> num; for (int i = 0; i != n; ++i) { string temp; int t; cin >> temp >> t; student te(temp, t, i); num.push_back(te); } if (way == 0) sort(num.begin(), num.end(), compare_2); else sort(num.begin(), num.end(), compare_1); for (int i = 0; i != n - 1; ++i) { for (int j = 0; j != n - 1 - i; ++j) { if (num[j].grade == num[j + 1].grade) { if (num[j].order > num[j + 1].order) { student a = num[j]; num[j] = num[j + 1]; num[j + 1] = a; } } } } for (auto& i : num) { cout << i.name << " " << i.grade << endl; } } // 64 位输出请用 printf("%lld")
写一个结构体,三个成员,名字,成绩,和次序,然后在排序完以后,要根据次序重新对相同的值进行位置上的调整