1028 List Sorting (25分)
题目链接:PAT A 1028
题目大意:题目输入一个数n为学生个数,对于每个学生,给出他们的id,名字以及成绩。输入一个c代表行数,即我们需要排序的行数。如果c为1,则按照id升序排列,如果c为2,则按照名字字母序升序排列,如果名字相同,按照id升序排列,如果c为3,按照成绩升序排列,如果成绩相同,按照id升序排列。
思路分析:很简单的排序题,写好cmp函数就可以了。需要注意的是如果用字符串存储的话,用cin,cout输入输出会导致最后一组数据超时。把cout改为printf即可(printf可以输出字符串,需要加上.c_str())。这样用时将为300ms左右,如果时间限制为200ms,则不能使用string,需要使用字符数组char,然后用strcmp函数进行比较~
AC代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct stu{
string id, name;
int score;
};
int n, c;
bool cmp(stu a, stu b) {
if(c == 1) {
return a.id < b.id;
}
else if(c == 2) {
if(a.name != b.name) //名字不同按名字升序排列
return a.name < b.name;
else //名字相同按id升序排列
return a.id < b.id;
}
else if(c == 3) {
if(a.score != b.score) //分数不同按分数升序排列
return a.score < b.score;
else //分数相同按id升序排列
return a.id < b.id;
}
}
int main() {
cin >> n >> c;
vector<stu> v(n);
for(int i = 0; i < n; i++)
cin >> v[i].id >> v[i].name >> v[i].score;
sort(v.begin(), v.end(), cmp);
for(int i = 0; i < n; i++)
printf("%s %s %d\n", v[i].id.c_str(), v[i].name.c_str(), v[i].score);
return 0;
}
ps:如果时间限制为200ms,代码如下:
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
const int maxn = 100001;
struct NODE {
int no, score;
char name[10];
}node[maxn];
int c;
int cmp1(NODE a, NODE b) {
if(c == 1) {
return a.no < b.no;
} else if(c == 2) {
if(strcmp(a.name, b.name) == 0) return a.no < b.no;
return strcmp(a.name, b.name) < 0;
} else {
if(a.score == b.score) return a.no < b.no;
return a.score < b.score;
}
}
int main() {
int n;
scanf("%d%d", &n, &c);
for(int i = 0; i < n; i++)
scanf("%d %s %d", &node[i].no, node[i].name, &node[i].score);
sort(node, node + n, cmp1);
for(int i = 0; i < n; i++)
printf("%06d %s %d\n", node[i].no, node[i].name, node[i].score);
return 0;
}
时间在100ms以内