浙江省2021年高考成绩排名程序:高效处理50万条数据
浙江省2021年高考成绩排名程序:高效处理50万条数据
问题描述:
有一个文本文件保存了浙江省2021年高考成绩。为了使问题简单,假设高考分数都是整数,没有小数。满分为750分。在数据文件里,每行保存一位考生的信息。先准考证号后高考成绩。现在要求编写一程序,确定每位考生的名次。最后以如下格式保存考生的信息:
准考证号 总分 名次 同名次人数 (同分情况下按准考证号大小排序)
提示:数据量达50万条。
输入示例:
330327969978 704
330783413356 443
330483550396 326
330726567225 215
330326613747 394
331021766290 704
输出示例:
输出一个文本文件(命名方式同之前实验),每行一位考生的信息,包括准考证号,成绩,名次和同名次人数。
330327969978 704 1 2
331021766290 704 1 2
330783413356 443 3 1
330326613747 394 4 1
330483550396 326 5 1
330726567225 215 6 1
代码实现:
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
struct Node {
int id;
int score;
Node* next;
};
bool cmp(Node* a, Node* b) {
if (a->score == b->score) {
return a->id < b->id;
}
return a->score > b->score;
}
void calculate_rank(Node* head, vector<int>& ranks, vector<int>& counts, int& rank, int& same_count) {
if (head == nullptr) {
return;
}
if (ranks.empty() || ranks.back() != head->score) {
ranks.push_back(head->score);
same_count = 1;
}
else {
same_count++;
}
if (same_count == ranks.size()) {
same_count = 1;
}
for (size_t i = 0; i < ranks.size(); ++i) {
if (head->score == ranks[i]) {
ranks[i] = rank;
counts[rank]++;
return;
}
}
ranks.push_back(head->score);
counts.push_back(1);
rank++;
calculate_rank(head->next, ranks, counts, rank, same_count);
}
int main()
{
ifstream input("C:\Users\admin\Desktop\P03_TextData500.in", ios_base::in);
ofstream output("C:\Users\admin\Desktop\1.txt");
Node* head = nullptr;
Node* tail = nullptr;
Node* newNode = nullptr;
while (input >> id >> score) {
newNode = new Node;
newNode->id = id;
newNode->score = score;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
vector<int> ranks;
vector<int> counts(ranks.size(), 0);
int rank = 1;
int same_count = 1;
calculate_rank(head, ranks, counts, rank, same_count);
Node* cur = head;
while (cur != nullptr) {
output << cur->id << " " << cur->score << " " << ranks[rank-1] << " " << counts[ranks[rank-1]] << endl;
cur = cur->next;
}
input.close();
output.close();
return 0;
}
代码说明:
- 使用链表结构存储数据,方便动态添加节点,同时方便遍历所有节点。
- 使用
calculate_rank函数计算每个节点的名次和同名次人数。 - 该函数利用递归的方式遍历链表,并利用
ranks和counts数组记录每个分数对应的名次和同名次人数。 cmp函数用于对链表进行排序,按分数从高到低排序,同分情况下按准考证号从小到大排序。- 最后,根据
ranks和counts数组输出每个节点的信息。
注意:
- 请确保输入文件路径是正确的,并且程序能够成功打开该文件进行读取。
- 程序使用了动态内存分配,使用完后需要释放内存空间,避免内存泄漏。
总结:
本程序能够高效地处理50万条高考成绩数据,计算并输出每个考生的名次和同名次人数。程序采用链表结构存储数据,并利用排序和计数算法实现高效排名,最终以指定格式输出结果。
原文地址: http://www.cveoy.top/t/topic/cv5k 著作权归作者所有。请勿转载和采集!