用C++库函数sort秒杀了,建一个结构体就好了,同时储存输入次序。
#include<iostream>
#include<algorithm>
#include<cstdlib>
using namespace std;
struct node{
int num;
char x[20];
int score;
};
typedef struct node student;
bool comp1(student left,student right){
if(left.score > right.score) return true;
if(left.score==right.score && left.num < right.num) return true;
return false;
}
bool comp2(student left,student right){
if(left.score < right.score) return true;
if(left.score==right.score && left.num < right.num) return true;
return false;
}
int main(){
long n = 0;
int tag = 0;
while(cin >> n >> tag ){
student* A=(student*)malloc(sizeof(student) *n );
for(long i = 0; i < n ; i++){
A[i].num=i;
cin >> A[i].x >> A[i].score ;
}
if(tag==0){
sort(A,&A[n],comp1);
}else{
sort(A,&A[n],comp2);
}
for(long i = 0; i < n ; i++){
cout << A[i].x <<' ' << A[i].score << '\n' ;
}
}
return 0;
}
结果如下: