题目
Excel can sort records according to any column. Now you are supposed to imitate this function.
Input Specification:
Each input file contains one test case. For each case, the first line contains two integers N (≤10
5 ) and C, where N is the number of records and C is the column that you are supposed to sort the records with. Then N lines follow, each contains a record of a student. A student’s record consists of his or her distinct ID (a 6-digit number), name (a string with no more than 8 characters without space), and grade (an integer between 0 and 100, inclusive).
Output Specification:
For each test case, output the sorting result in N lines. That is, if C = 1 then the records must be sorted in increasing order according to ID’s; if C = 2 then the records must be sorted in non-decreasing order according to names; and if C = 3 then the records must be sorted in non-decreasing order according to grades. If there are several students who have the same name or grade, they must be sorted according to their ID’s in increasing order.
代码和思路
思路
- 一个很简单的排序问题,写好对应的cmp函数就行,要注意当名字成绩相同时,第二关键字是学号
- 名字直接用string,注意输入输出
- 水题
代码
#include<cstdio>
#include<vector>
#include<algorithm>
#include<string>
#include<iostream>
using namespace std;
struct student {
int id;
int score;
string name;
student(int _id, int _score, string _str) : id(_id), score(_score), name(_str) {}
};
vector<student> stu;
int n;
bool cmpid(student a, student b) {
return a.id < b.id;
}
bool cmpname(student a, student b) {
if (a.name != b.name) {
return a.name < b.name;
}
else {
return a.id < b.id;
}
}
bool cmpscore(student a, student b) {
if (a.score != b.score) {
return a.score < b.score;
}
else {
return a.id < b.id;
}
}
int main() {
int n, id, score, query;
string name;
scanf_s("%d %d", &n, &query);
for (int i = 0; i < n; i++) {
scanf_s("%d", &id);
getchar();
cin >> name;
scanf_s("%d", &score);
stu.push_back(student(id, score, name));
}
switch (query) {
case 1:
sort(stu.begin(), stu.end(), cmpid);
break;
case 2:
sort(stu.begin(), stu.end(), cmpname);
break;
case 3:
sort(stu.begin(), stu.end(), cmpscore);
break;
}
for (int i = 0; i < stu.size(); i++) {
printf("%06d ", stu[i].id);
cout << stu[i].name;
printf(" %d\n", stu[i].score);
}
}