題目:輸入任意(用戶,成績)序列,可以獲得成績從高到低或從低到高的排列,相同成績
都按先錄入排列在前的規則處理。
示例:
jack 70
peter 96
Tom 70
smith 67
從高到低 成績
peter 96
jack 70
Tom 70
smith 67
從低到高
smith 67
jack 70
Tom 70
peter 96
代碼:
# include <iostream>
# include <algorithm>
using namespace std;
typedef struct stu{
char name[20];
int score;
int i;
}Stu;
int cmp1(struct stu a,struct stu b){
if(a.score != b.score){
return a.score < b.score;
}else{
return a.i < b.i;
}
}
int cmp2(struct stu a, struct stu b){
if(a.score != b.score){
return a.score > b.score;
}else{
return a.i < b.i;
}
}
int main(){
int num;
int flag;
while(scanf("%d%d",&num,&flag) != EOF){
Stu *a = new Stu[num];
for(int i = 0; i < num ; ++i){
scanf("%s%d",&a[i].name,&a[i].score);
a[i].i= i;
}
if(flag == 0){
sort(a,a+num,cmp2);
}else{
sort(a,a+num,cmp1);
}
for(int i = 0; i < num ; ++i){
printf("%s %d\n",a[i].name, a[i].score);
}
}
return 0;
}