3 条题解
-
0
插入排序:
#include <bits/stdc++.h> using namespace std; struct Student { string name; int score; }; void insertSort(vector<Student>& students, int n) { for (int i = 1; i < n; i++) { Student temp = students[i]; int j = i - 1; // 比较成绩,成绩从高到低,如果相同则按名字字典序排序 while (j >= 0 && (students[j].score < temp.score || (students[j].score == temp.score && students[j].name > temp.name))) { students[j + 1] = students[j]; j--; } students[j + 1] = temp; } } int main() { int n; cin >> n; vector<Student> students(n); // 读取学生的名字和成绩 for (int i = 0; i < n; i++) { cin >> students[i].name >> students[i].score; } // 使用插入排序对学生按成绩和名字排序 insertSort(students, n); // 输出排序后的学生成绩单 for (int i = 0; i < n; i++) { cout << students[i].name << " " << students[i].score << endl; } return 0; } -
0
选择排序方法:
#include <bits/stdc++.h> using namespace std; // 定义学生信息结构体 struct Student { string name; int score; }; // 自定义比较函数,按照分数从高到低,若分数相同则按名字字典序从小到大排序 bool compare(Student a, Student b) { if (a.score == b.score) { return a.name < b.name; // 如果分数相同,按名字字典序升序 } return a.score > b.score; // 按分数降序 } // 实现选择排序 void selectionSort(vector<Student>& students, int n) { for (int i = 0; i < n - 1; i++) { int maxIndex = i; for (int j = i + 1; j < n; j++) { // 比较学生元素,找到最大(或最小)元素的下标 if (compare(students[j], students[maxIndex])) { maxIndex = j; } } // 交换位置 swap(students[i], students[maxIndex]); } } int main() { int n; cin >> n; // 输入学生人数 vector<Student> students(n); // 创建学生信息存储数组 for (int i = 0; i < n; i++) { cin >> students[i].name >> students[i].score; // 输入学生名字和成绩 } // 对学生信息进行选择排序 selectionSort(students, n); // 输出排序后的学生信息 for (int i = 0; i < n; i++) { cout << students[i].name << " " << students[i].score << endl; } return 0; } -
0
sort排序:
#include <bits/stdc++.h> using namespace std; struct student { string name; double score; }; bool cmp(student a, student b) { if (a.score == b.score) return a.name < b.name; return a.score > b.score; } int main() { int n; cin >> n; student a[n]; for (int i = 0; i < n; i++) cin >> a[i].name >> a[i].score; sort(a, a + n, cmp); for (int i = 0; i < n; i++) cout << a[i].name << " " << a[i].score << endl; return 0; }
- 1
信息
- ID
- 658
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 9
- 标签
- 递交数
- 10
- 已通过
- 5
- 上传者