1.题目
2.代码
#include <cstring>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <iostream>
using namespace std;
const int N = 10010;
int n, m;
struct Person{
string id;
string score;
}p[N];
bool cmp(Person a, Person b){
//按照成绩降序来排序;
//如果成绩相同,则按照字典序进行排序;
if(atoi(a.score.c_str()) != atoi(b.score.c_str())) return atoi(a.score.c_str()) > atoi(b.score.c_str());
else return a.id < b.id;
}
int main(){
cin>>n>>m;
//scanf("%d")
for(int i=0; i<n; i++){
//输入相应的考生信息
cin>>p[i].id>>p[i].score;
}
for(int i=0; i<m;i++){
string a, b;
cin>>a>>b;
printf("Case %d: %s %s\n", i+1, a.c_str(), b.c_str());
if(a == "1"){ //如果是类型1,则降序输出相应级别的考生成绩,相同则用字母序
vector<Person> persons;
for(int j=0; j<n;j++){
if(p[j].id[0] == b[0]){
persons.push_back(p[j]);
}
}
//对放入vector的学生进行排序
sort(persons.begin(), persons.end(),cmp);
if(persons.empty())
{
puts("NA");
}else{
for(auto person:persons){
printf("%s %s\n", person.id.c_str(), person.score.c_str());
}
}
}else if(a == "2"){
//如果是类型2
int sum = 0, count = 0;
for(int j=0; j<n; j++){
if(p[j].id.substr(1,3) == b){ //如果考场号相同,那么计算总数
sum += atoi(p[j].score.c_str());
count++;
}
}
if(count == 0){
puts("NA");
}else{
printf("%d %d\n", count, sum);
}
}else{
//如果是类型3,相同年月日出现的学生,以班级为单位进行统计,此时需要使用哈希表来记录
unordered_map<string, int> hash;
for(int j=0; j<n; j++){
if(p[j].id.substr(4,6) == b){
hash[p[j].id.substr(1,3)]++;
}
}
vector<pair<int,string>> rooms;
for(auto item:hash) rooms.push_back({-item.second, item.first});
sort(rooms.begin(), rooms.end());
if(rooms.empty()){
puts("NA");
}else{
for(auto room:rooms){
printf("%s %d\n", room.second.c_str(), -room.first);
}
}
}
}
return 0;
}
3.解题思路
定义一个Person结构体,存储需要读入的学生准考证和成绩信息。
逐个读入输出要求,分类讨论:
- 当输出要求是1时:将相应级别考试的学生的成绩排序输出,首先从Person结构体数组中筛选出相应的结构体,push进新开的vector中(该vector的类型是Person)。再对结构体进行sort排序,注意在cmp函数中写清楚排序的要求。
- 当输出要求是2时:在遍历person结构体时对相应考场的学生成绩进行累加和计数,遍历结束后输出。
- 当输出要求是3时:该题需要有hash表进行处理,开一个hash表,key是string类型,value是int类型。并且遍历perosn结构体数组,在时间条件符合的条件下,对相应的考场编号++。结束后再把hash表扔进一个vector的pair里,并对这个pair进行sort。
注意点:
- sort是规则不一致的情况下,可以通过输入原始数据的复数,再输出时再负负得正,就可以得到理想的排序结果。
- printf输出string时,注意要跟.c_str()
- string转int atoi()很好用
- substr(a, b) a是起始下标,b是取的长度