[PAT A1028]List Sorting
题目描述
1028 List Sorting (25 分)Excel can sort records according to any column. Now you are supposed to imitate this function.
输入格式
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).
输出格式
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.
输入样例1
3 1
000007 James 85
000010 Amy 90
000001 Zoe 60
输出样例1
000001 Zoe 60
000007 James 85
000010 Amy 90
输入样例2
4 2
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 98
输出样例2
000010 Amy 90
000002 James 98
000007 James 85
000001 Zoe 60
输入样例3
4 3
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 90
输出样例3
000001 Zoe 60
000007 James 85
000002 James 90
000010 Amy 90
解析
- 题目很简单,大致意思就是首先输入N和C,表示学生的个数,然后下面N行输入学生的id,姓名和成绩,如果C=1,那么就按id升序排列,同理C=2,按照姓名非降序序排列,C=3,按照成绩非降序排列,如果有一样的成绩或者姓名,那么按照id从小到大排
- 我这里写了三个cmp函数,针对不同的C对不同的列排序,其实我们可以使用一个全局变量,然后只用写一个cmp就可以了
- 另外有一点要注意的是,输出的id的格式必须是6位的,我们printf就要加%06d表示六位对齐并用0填充。
- 再就是printf好像不能输出string,这里要使用string自带的c_str()函数才能完成输出。
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
struct student
{
int id;string name;int grade;
};
bool cmp1(student s1,student s2)
{
return s1.id < s2.id;
}
bool cmp2(student s1, student s2)
{
if(s1.name!=s2.name) return s1.name < s2.name;else return s1.id < s2.id;
}
bool cmp3(student s1, student s2)
{
if (s1.grade != s2.grade) return s1.grade < s2.grade;else return s1.id < s2.id;
}
int main()
{
int N, line;vector<student> stu;cin >> N >> line;while (N--) {
student s;cin >> s.id >> s.name >> s.grade;stu.push_back(s);}if (line == 1) sort(stu.begin(), stu.end(), cmp1);if (line == 2) sort(stu.begin(), stu.end(), cmp2);if (line == 3) sort(stu.begin(), stu.end(), cmp3);for (int i = 0; i < stu.size(); i++) printf("%06d %s %d\n", stu[i].id, stu[i].name.c_str(), stu[i].grade);return 0;
}