本题链接:1141 PAT Ranking of Institutions - PAT (Advanced Level) Practice (pintia.cn)
题意:
给定一些学生的考试成绩,通过给定的成绩计算方式来对院校进行排名。
但是一直后三个测试点一直不通过,看了柳神的博客发现是因为成绩计算时有浮点数,如果直接用int类型存储会导致部分数据有偏差(这谁想得到啊也太偏了)
代码:
#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
struct node {
string name;
int rank, ns;//tws为总分数,ns为参加人数
double tws;
int resTws;
};
node newNode(string name, double tws, int rank, int ns) {
node aa;
aa.name = name;
aa.tws = tws;
aa.rank = rank;
aa.ns = ns;
return aa;
}
bool cmp(node a,node b) {
if (a.resTws == b.resTws) {
if (a.ns == b.ns) {
return a.name < b.name;
}
return a.ns < b.ns;
}
return a.resTws > b.resTws;
}
double charge(char level,double score) {
double ss = 0;
switch (level) {
case 'a': ss = score; break;
case 't': ss = score * 1.5; break;
case 'b': ss = score / 1.5; break;
}
return ss;
}
int main() {
vector<node>list;
map<string, int> mp;//名字与vector对应
int n;
int dig = 0;
cin >> n;
for (int i = 0; i < n; i++) {
double score;
string id,school;
cin >> id >> score >> school;
transform(school.begin(), school.end(),school.begin(), ::tolower);
if (mp.find(school) == mp.end()) {
double s = charge(tolower(id[0]),score);
list.push_back(newNode(school, s, 0, 1));
mp[school] = dig;
dig++;
}
else {
int index = mp[school];
list[index].tws += charge(tolower(id[0]), score);
list[index].ns++;
}
}
for (int i = 0; i < list.size(); i++) {
list[i].resTws = (int)list[i].tws;
}
sort(list.begin(), list.end(), cmp);
int r = 1;
int lastScore = 0;
for (int i = 0; i < list.size(); i++) {
if (i == 0) {
list[i].rank = r;
lastScore = list[i].resTws;
}
else {
if ((int)list[i].resTws == lastScore) {
list[i].rank = r;
}
else {
r = i + 1;
list[i].rank = r;
lastScore = list[i].resTws;
}
}
}
cout << list.size() << endl;
for (int i = 0; i < list.size(); i++) {
printf("%d ", list[i].rank);
cout << list[i].name;
printf(" %d %d\n", (int)list[i].tws, list[i].ns);
}
return 0;
}