试题链接:http://codeup.cn/problem.php?cid=100000581&pid=2
样例输入:
4 1
000001 Zhao 75
000004 Qian 88
000003 Li 64
000002 Sun 90
4 2
000005 Zhao 95
000011 Zhao 75
000007 Qian 68
000006 Sun 85
4 3
000002 Qian 88
000015 Li 95
000012 Zhao 70
000009 Sun 95
0 3
样例输出:
Case 1:
000001 Zhao 75
000002 Sun 90
000003 Li 64
000004 Qian 88
Case 2:
000007 Qian 68
000006 Sun 85
000005 Zhao 95
000011 Zhao 75
Case 3:
000012 Zhao 70
000002 Qian 88
000009 Sun 95
000015 Li 95
我的解决代码:
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
struct student{
char name[9];
int grade;
char id[7];
};
bool cmpWithId(student a,student b){
if(strcmp(a.id,b.id)<=0)return true;
else return false;
}
bool cmpWithName(student a,student b){
if(strcmp(a.name,b.name)<0)return true;
else if(strcmp(a.name,b.name)==0)return cmpWithId(a,b); //相同姓名
else return false;
}
bool cmpWithGrade(student a,student b){
if(a.grade<b.grade)return true;
else if(a.grade>b.grade)return false;
else return cmpWithId(a,b); //相同成绩
}
int main(){
int num;
int C;
student stu[10000];
cin>>num>>C;
if(num!=0){
for(int i=0;i<num;i++){
cin>>stu[i].id>>stu[i].name>>stu[i].grade;
}
}else return 0;
cout<<"Case:"<<endl;
for(int i=0;i<num;i++){
if(C==1){
sort(stu, stu+num,cmpWithId);
}else if(C==2){
sort(stu, stu+num,cmpWithName);
}else if(C==3){
sort(stu, stu+num,cmpWithGrade);
}
}
for(int i=0;i<num;i++){
cout<<stu[i].id<<" "<<stu[i].name<<" "<<stu[i].grade<<endl;
}
return 0;
}
看了下比我写的简洁的多的代码- -它用了全局变量。
我太菜了。
后来又看了一下运行的相关参数,发现它的代码虽然简单,但速度和占用控件都比笨方法慢一点。
代码如下:
//链接://https://www.nowcoder.com/questionTerminal/bf3ec474bb7d410dbb9d5bbcd07a93e5
//来源:牛客网
#include <iostream>
#include <algorithm>
using namespace std;
struct Student{ string id, name; int score;};
int n = 0, c = 0; Student sts[100000];
bool MySort(Student sts1, Student sts2)
{
switch (c)
{
case 1: return sts1.id < sts2.id;
case 2: return sts1.name == sts2.name ? sts1.id < sts2.id : sts1.name < sts2.name;
case 3: return sts1.score == sts2.score ? sts1.id < sts2.id : sts1.score < sts2.score;
}
return false;
}
int main()
{
while (cin >> n >> c && 0 != n) for (int i = 0; i < n; ++i) cin >> sts[i].id >> sts[i].name >> sts[i].score;
sort(sts, sts + n, MySort); cout << "Case:" << endl; for (int i = 0; i < n; ++i) cout << sts[i].id << ' ' << sts[i].name << ' ' << sts[i].score << endl; return 0;
}