还有10题!!!
坑点
排序过程中是按照取整后的分数进行排序的(测试点5)
思路
用结构体保存学校的加权总分、考试人数、学校名。用vector保存各个学校,在输入的过程中,按照权值计算出成绩加入学校的总分中(注意这里不能取整)。用map保存学校在vector中的下标。这样,当输入学生的学校已经在vector中存在时,可以直接通过下标去进行修改。
输出的时候,vector中的第一个值直接输出,rank置为1。当输出第2-N个值时,如果与前一个学校的总分相等,排名就是rank。不相等时排名就是i+1,并且将rank置为i+1。
实现
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
struct School {
string name;
int num;
double score;
};
bool cmp(School a, School b)
{
if ((int)a.score != (int)b.score) //注意这里比较分数时是按照取整后比较的,不取整的话测试点5会错
return a.score > b.score;
else
return a.num != b.num ? a.num < b.num:a.name < b.name;
}
int main()
{
int N,i;
cin >> N;
double score;
string str,ID,sch;
vector<School> schools;
map<string, int> count; //用来记录学校在vector中的下标
for (i = 0; i < N; i++)
{
cin >> ID >> score >> sch;
transform(sch.begin(), sch.end(),sch.begin(), ::tolower);
if (ID[0] == 'B')
score = (score / 1.5);
if (ID[0] == 'T')
score = (score*1.5);
if (count[sch])
{
schools[count[sch]-1].score += score; //累加成绩时要按照double型计算
schools[count[sch]-1].num++;
}
else if (count[sch] == 0)
{
schools.push_back(School{ sch,1,score});
count[sch] = schools.size(); //比真正的下标大1
}
}
sort(schools.begin(), schools.end(), cmp);
int rank = 0;
cout << schools.size() << endl;
for (i = 0; i < schools.size(); i++)
{
if (i >= 1 && (int)schools[i].score == (int)schools[i - 1].score)
cout << rank << " " << schools[i].name << " " << (int)schools[i].score << " " << schools[i].num << endl;
else
{
cout << i + 1 << " " << schools[i].name << " " << (int)schools[i].score << " " << schools[i].num << endl;
rank=i+1;
}
}
return 0;
}