题目
有n个考场,每个考场有若干数量的考生。现在给出各个考场中考生的准考证号与分数,要求将所有考生按分数从高到低排序,并按顺序输出所有考生的准考证号排名、考场号以及考场内排名。
学到的东西
cmp函数
与sort函数相匹配
bool cmp(Student a, Student b){
if(a.score != b.score) return a.score > b.score; //分数从高到低
else return a.id < b.id; //分数相等,准考证号从小到大
}
排名写法
如 1,1,3,3,5这种排名
stu[0].r = 1;
for(int i = 1; i < n; i++)
{
if(stu[i].score == stu[i-1].score)
stu[i].r = stu[i-1].r;
else
stu[i].r = i + 1;
}
或者
r = 1;
for(i = 0; i < stu_num; i++){
if(i > 0 && stu[i].score != stu[i-1].score)
r = i + 1;
stu[i].total_rank = r;
}
代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Student{
string id; //准考证
int score; //分数
int location_number;//考场号
int local_rank; //考场内排名
int total_rank; //总排名
}stu[30000];
bool cmp(Student a, Student b){
if(a.score != b.score) return a.score > b.score; //分数从高到低
else return a.id < b.id; //分数相等,准考证号从小到大
}
int main()
{
int i,j,n,Pindex = 0;
cin >> n;
int stu_num = 0, k, m, r; //stu_num为总学生数
for(i = 0; i < n; i++){
cin >> k;
/*输入每个学生信息 */
for(j = 0; j < k; j++){
cin >> stu[Pindex].id >> stu[Pindex].score;
stu[Pindex].location_number = i + 1; //考场号
Pindex++;
}
/*考场内部排序*/
sort(stu + stu_num, stu + stu_num + k, cmp);
r = 1;
for(j = stu_num, m = 0; j < stu_num + k; j++, m++){
if(j > stu_num && stu[j].score != stu[j-1].score)
r = m + 1;
stu[j].local_rank = r;
}
stu_num += k; //总人数
}
/*总人数按分数排序*/
sort(stu, stu + stu_num, cmp);
r = 1;
for(i = 0; i < stu_num; i++){
if(i > 0 && stu[i].score != stu[i-1].score)
r = i + 1;
stu[i].total_rank = r;
}
/*输出*/
cout << stu_num << "\n";
for(i=0; i<stu_num; i++){
cout << stu[i].id << " " << stu[i].total_rank << " " << stu[i].location_number << " " << stu[i].local_rank << "\n";
}
return 0;
}