代码
#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
using namespace std;
const int K = 6; // 题目编号
int n,k,m;
int p_score[K]; // 题目满分
struct Student{
string id;
int score[K]; // -1 未通过 -2 未提交
int cnt;
int total_score;
Student(){}
Student(string _id) : id(_id){
for (int i = 1; i <= k; i ++ ) score[i] = -2;
total_score = cnt = 0;
}
bool isSubmit(){
for(int i = 1; i <= k ; i++)
if(score[i] >= 0) return true;
return false;
}
void calc(){
for(int i = i; i <= k ; i++){
if(score[i] >= 0){
total_score += score[i];
if(score[i] == p_score[i]) cnt ++;
}
}
}
bool operator< (const Student& t) const{
if(total_score != t.total_score) return total_score > t.total_score;
if(cnt != t.cnt) return cnt > t.cnt;
return id < t.id;
}
};
unordered_map<string, Student> map;
int main(){
scanf("%d%d%d", &n, &k, &m);
for(int i = 1; i <= k; i++)
scanf("%d", &p_score[i]);
for(int i = 1; i <= m; i++){
string id;
char u_id_c[10];
int p_id, p_s;
scanf("%s%d%d", u_id_c, &p_id, &p_s);
id = u_id_c;
if(map.count(id) == 0)
map[id] = Student(id);
map[id].score[p_id] = max(p_s, map[id].score[p_id]);
}
vector<Student> validStudent;
for(auto& item : map){
auto& student = item.second;
if(student.isSubmit()) {
student.calc();
validStudent.push_back(student);
}
}
sort(validStudent.begin(), validStudent.end());
for(int i = 0, rank = 1; i < validStudent.size(); i++){
auto& item = validStudent[i];
if(i && item.total_score != validStudent[i-1].total_score) rank = i + 1;
printf("%d %s %d", rank, item.id.c_str(), item.total_score);
for(int j = 1; j <= k; j++){
if(item.score[j] == -1) printf(" 0");
else if(item.score[j] == -2) printf(" -");
else printf(" %d",item.score[j]);
}
printf("\n");
}
return 0;
}
总结
1. 由于题要的复杂性,因此设计结构体来实现部分操作,比如结构体内部的calc计算与isSubmit的判断。结构体初始化的代码也需要学习。
Student(){}
Student(string _id) : id(_id){
for (int i = 1; i <= k; i ++ ) score[i] = -2;
total_score = cnt = 0;
}
2. 重载运算符
bool operator< (const Student& t) const{
if(total_score != t.total_score) return total_score > t.total_score;
if(cnt != t.cnt) return cnt > t.cnt;
return id < t.id;
}
3. 用map来完成对重复id数据的映射,类似于object
4. 过滤合法数据
5. 排名输出