1505. 列表排序
作者:
lvjj
,
2024-03-15 18:26:55
,
所有人可见
,
阅读 14
#include <bits/stdc++.h>
using namespace std;
int n,m;
const int N = 100010;
struct Gather{
string name;
int score;
string number;//学号怎么定义?
}gather[N];
bool cmp1(Gather a,Gather b){
//当出现学生名字相同或是成绩相同的情况时,按照 ID 升序的顺序,对他们进行排序。
// if(a.name==b.name||a.score==b.score) return a.score<b.score; //学号是不会重复的,所以直接排序就行
return a.number<b.number;
}
bool cmp2(Gather a,Gather b){
//下面这种写法不对,要按照优先级排序;比如拿两个人比较,先比较他们的名字,也就是return a.name<b.name,再比较学号,那么什么时候比较学号,等到名字有重复的时候排学号。那也就是说,不重复名字就对名字排序,也就是 if(a.name!=b.name)return a.name<b.name;
// if(a.name==b.name||a.score==b.score) return a.score<b.score;
// return a.name<b.name;
if(a.name!=b.name)return a.name<b.name;
return a.number<b.number;
}
bool cmp3(Gather a,Gather b){
// if(a.name==b.name||a.score==b.score) return a.score<b.score;
// return a.score<b.score;
if(a.score!=b.score)return a.score<b.score;
return a.number<b.number;
}
int main(){
// ios::sync_with_stdio(false);//这个也超时间
// cin.tie(0);
// cin>>n>>m;
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)cin>>gather[i].number>>gather[i].name>>gather[i].score;
//scanf("%s%s%d",gather[i].number,gather[i].name,gather[i].score);//暂时不会scanf读入
if(m == 1){//如果 C=1,则按照 ID 升序的顺序排序。
sort(gather,gather+n,cmp1);
}else if(m==2){
sort(gather,gather+n,cmp2);
}else{
sort(gather,gather+n,cmp3);
}
for(int i=0;i<n;i++) //cout<<gather[i].number<<' '<<gather[i].name<<' '<<gather[i].score<<endl;//注意输出格式(即每输出一个属性要一个空格,输入不需要):' '
printf("%s %s %d\n",gather[i].number.c_str(),gather[i].name.c_str(),gather[i].score);//改成printf 注意%s只支持c风格的char数组,需要用c_str()函数转一下
return 0;
}
getline getchar
遗留一个坑:scanf,printf,cin,cout之间具体优化问题