PAT乙级1025
https://pintia.cn/problem-sets/994805342720868352/problems/994805474338127872
对应相同分数考生排名的处理,要记住如何处理
#include <algorithm>
#include <iostream>
#include <string.h>
#include <string>
#include <vector>
using namespace std;
struct Student {
string number; // 学号
int score; // 分数
int location_number; // 考场号
int local_rank; // 考场内名次
int total_rank; // 总名次
};
bool cmp(Student s1, Student s2)
{
// 如果成绩不相等时,根据成绩降序排列
// 如果成绩相等时,按照啊考号升序排列
if (s1.score != s2.score)
return s1.score > s2.score;
else
return s1.number < s2.number;
}
// 1234567890003 3 1 2
void printStu(Student s)
{
// cout <<
printf("%s %d %d %d\n", s.number.c_str(), s.total_rank, s.location_number, s.local_rank);
}
/*
1.按考场读入考上信息,并对当前读入考场的所有考生进行排序,
然后将排名写入到其结构体中
2.对所有考上进行排序
3.按顺序一边计算总排名,一边输出考生信息
*/
int main(int argc, const char** argv)
{
// n1:有几个考场,n2每个考场人数
int n1, n2, rank;
vector<Student> VlocalStu, VallStu;
while (cin >> n1) {
for (int i = 0; i < n1; i++) {
// n2考场人数
cin >> n2;
for (int j = 0; j < n2; j++) {
Student s;
cin >> s.number >> s.score;
s.location_number = i + 1;
VlocalStu.push_back(s);
}
sort(VlocalStu.begin(), VlocalStu.end(), cmp);
// 现将第一个学生 的成绩当做第一名,然后将考生的排名写入类中
VlocalStu.begin()->local_rank = 1;
// 根据排名的排序方式进行排名,相同分数的考生赋予相同的排名
rank = 2;
for (vector<Student>::iterator it = VlocalStu.begin() + 1; it != VlocalStu.end(); it++) {
if (it->score == (it - 1)->score)
it->local_rank = (it - 1)->local_rank;
else
it->local_rank = rank;
rank++;
}
// 将该考场的考生写入总的容器中,方便后面进行总排序
VallStu.insert(VallStu.end(), VlocalStu.begin(), VlocalStu.end());
// 写入下一个考场的考生
VlocalStu.clear();
}
cout << VallStu.size() << endl;
// 对所有考生进行总排名
sort(VallStu.begin(), VallStu.end(), cmp);
VallStu.begin()->total_rank = 1;
rank = 2;
for (vector<Student>::iterator it = VallStu.begin() + 1; it != VallStu.end(); it++) {
if (it->score == (it - 1)->score)
it->total_rank = (it - 1)->total_rank;
else
it->total_rank = rank;
rank++;
}
// for_each(VallStu.begin(), VallStu.end(), printStu);
for_each(
VallStu.begin(), VallStu.end(), [=](Student s) {
printf("%s %d %d %d\n", s.number.c_str(), s.total_rank, s.location_number, s.local_rank);
});
}
return 0;
}