解题思路
一道常规的排序题,涉及到多个维度,具体按照哪个维度排序取决于输入的参数C。根据题意我们可以为每一种情况写一个cmp函数,但是出题人显然不希望我们这么干。因为按照出题人的习惯,一般都是成绩高的放在前面,但是这次是按照成绩递增(非减)排序,这样无论C等于多少,我们都是递增排序,由此为统一的cmp函数提供了条件。另外我们可以发现,不管是哪种情况都需要保证学生的id递增,所以我们可以先将所有的数据按照id递增排序,然后根据参数C的取值判断需不需要进行第二次排序,当然这种方法的可行性依赖于sort()
函数是稳定的。
另外,一开始我使用了string
,所以要用cin
和cout
进行输入输出,结果最后一个测试点超时了。
AC代码
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
int now = 0, n ,c;
struct stu {
char r[3][10];
};
vector<stu> a;
bool cmp(stu a, stu b) {
return strcmp(a.r[now], b.r[now]) < 0;
}
int main() {
scanf("%d %d", &n, &c);
a.resize(n);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < 3; ++j) {
scanf("%s", a[i].r[j]);
}
}
sort(a.begin(), a.end(), cmp);
if (c != 1) {
now = c - 1;
sort(a.begin(), a.end(), cmp);
}
for (int i = 0; i < a.size(); ++i) {
for (int j = 0; j < 3; ++j) {
printf("%s", a[i].r[j]);
if (j == 2) cout << "\n";
else cout << " ";
}
}
return 0;
}