题目A1025 PAT Ranking
-
题意
分别输入N
个考室的各考生成绩,按总排名输出,排名相同按编号从小到大输出。输出信息为:registration_number final_rank location_number local_rank
-
思路
首先数据需要保存,所以按数据范围申请数组,然后根据输出格式可以确定结构体中的属性是哪些。之后每个考室输入完后需要先进行局部排序,去填local_rank
。所有输入完成之后,全局排序,填final_rank
。也可以不填直接输出。
注意:
排名可以并列。 -
Code in C++
#include <iostream>
#include <algorithm>
#include <string>
#define maxn 30001
struct test_rank {
std::string registration_number;
int score;
int final_rank;
int location_number;
int local_rank;
void print() {
std::cout << registration_number << " " << final_rank << " " << location_number << " " << local_rank << std::endl;
}
} testees[maxn];
bool cmp(test_rank a, test_rank b) {
if (a.score != b.score) return a.score > b.score;
else return a.registration_number < b.registration_number;
}
void set_rank(int start, int end) {
testees[start].local_rank = 1; // 排序后第一个排名一定是第一
// 支持并列第一处理
for (int i = 1; i <= end - start; ++i) {
if (testees[start + i].score == testees[start + i -1].score) testees[start + i].local_rank = testees[start + i - 1].local_rank;
else testees[start + i].local_rank = i + 1;
}
}
int main()
{
int n, k;
int total = 0;
std::cin >> n;
for (int i = 1; i <= n; ++i) {
std::cin >> k;
for (int j = 0; j < k; ++j, ++total) {
std::cin >> testees[total].registration_number >> testees[total].score;
testees[total].location_number = i;
}
// 局部sort
std::sort(testees + total - k, testees + total, cmp);
// 设置local rank
set_rank(total - k, total - 1);
}
// 全局sort
std::sort(testees, testees + total, cmp);
std::cout << total << std::endl;
int r = 1; // 考生排名
for (int i = 0; i < total; ++i) {
if (i > 0 && (testees[i].score != testees[i -1].score)) {
r = i + 1;
}
testees[i].final_rank = r;
testees[i].print();
}
return 0;
}
小结
这里没认真看题目导致调试用了很长时间,并且在看到13位数字的时候我很自然的觉得用数值类型也可以保存编号字段,但是不知道为什么会出错,就算换了long long
,最后还是换成string
之后才AC。
PS
:感觉之后知识学的多点了,这个还可以扩展成分布式同步做的code。