4

PAT A1137 Final Grading(C++)

 2 years ago
source link: https://lulalap.com/2018/12/03/PAT-A1137-cpp/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

PAT A1137 Final Grading(C++)

发表于

2018-12-03

|

分类于

PAT题解

|

0

|

30

字数统计:

632 字

|

阅读时长 ≈

3 分钟

PAT甲级目录 | PAT乙级目录

原题地址:A1137 Final Grading
中文版:B1080 MOOC期终成绩

可利用 map 将字符串型的学号转换为整型的序号,方便查找。输入全部成绩后,遍历每个学生同时计算最终成绩,然后将成绩合格的人加入结果数组,最后对结果数组进行排序。

对于将输出的合格的学生,如果某次考试成绩不存在,那只可能是期中考试。如果其他考试有缺考则不可能合格。所以只要将期中考成绩默认为 -1,最后可直接输出无需另外判断。

  • 最终成绩要四舍五入

也许陌生的知识点

  • if(nametoi.find(id) == nametoi.end()){ nametoi[id] = cnt++;}
    • 可利用 map 将字符串类型的 id 转换成整数序号,方便处理
    • 需要的头文件:map
  • sort(S, S + n, cmp);
    • 排序函数,实现 [first, last) 范围内的排序,可以自定义排序策略 cmp 函数
    • 不带 cmp 参数的 sort 函数实现从小到大排序
    • 所需头文件: algorithm
  • vector<int> ans;
    • 实现变长数组,元素类型可任意指定
      • ans.push_back(num[i])往变长数组末尾中添加一个元素
      • ans.pop_back()删除变长数组中最后一个元素
    • 需要的头文件:vector

代码示例:

#include <cstdio>
#include <vector>
#include <string>
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
struct Student{
string name;
int gp = 0, gm = -1, gf = 0, g = 0;
}newstu;
vector<Student> stu, ans;
map<string, int> nametoi;
bool cmp(Student a, Student b){
if(a.g == b.g) return a.name < b.name;
else return a.g > b.g;
}
int main() {
int n1, n2, n3;
cin >> n1 >> n2 >> n3;
string id;
int score, i, cnt = 0;
for(i = 0; i < n1 + n2 + n3; i++){
cin >> id >> score;
if(nametoi.find(id) == nametoi.end()){ // 获取序号,并记录分数
newstu.name = id;
stu.push_back(newstu);
nametoi[id] = cnt++;
}
if(i < n1) stu[nametoi[id]].gp += score;
else if(i < n1 + n2) stu[nametoi[id]].gm = score;
else stu[nametoi[id]].gf = score;
}
for(int i = 0; i < cnt; i++){
if(stu[i].gp >= 200){ // 计算最终成绩,并保存合格的学生
stu[i].g = (stu[i].gm > stu[i].gf) ? (int)((stu[i].gm * 4 + stu[i].gf * 6 + 5)/10) : stu[i].gf;
if(stu[i].g >= 60) ans.push_back(stu[i]);
}
}
sort(ans.begin(), ans.begin() + ans.size(), cmp);
for(int i = 0; i < ans.size(); i++){
cout << ans[i].name;
printf(" %d %d %d %d\n", ans[i].gp, ans[i].gm, ans[i].gf, ans[i].g);
}
return 0;
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK