思路:
1、建立一个结构体school用来存储各个学校的分数,人数、排名以及学校名称。
2、然后创建一个map<string,struct school>。key就用学校名称,value就是这个学校的数据。
这样通过名称就能查找所指向的数据。
3、为了方便排序,我们想到用vector,所以将整个map复制到vector中。
4、使用unordered_map代替map,unordered_map比map快很多。
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <math.h>
using namespace std;
struct school{
double score; //分数
int stu_amount; //学生人数
string name; //学校名称
int rank; //排名
}sch;
bool cmp(pair<string,struct school> p1,pair<string,struct school> p2){
if(p1.second.score!=p2.second.score){
return p1.second.score>p2.second.score;
}else if(p1.second.stu_amount!=p2.second.stu_amount){
return p1.second.stu_amount<p2.second.stu_amount;
}else{
return p1.second.name<p2.second.name;
}
}
int main(){
int i,j,n;
string s,name;
double score;
cin>>n;
unordered_map<string,struct school> mp;
for(i=0;i<n;i++){
cin>>s>>score>>name;
for(j=0;j<name.length();j++){
name[j]=tolower(name[j]);
}
char c=s[0];
if(c=='B'){
score=score*1.0/1.5;
}else if(c=='T'){
score=score*1.0*1.5;
}
if(mp.find(name)==mp.end()){ //没找到 这块查找应该还有更快的写法
sch.name=name;
sch.score+=score;
sch.stu_amount++;
mp.insert(make_pair(name,sch)); //没找到就插入新的数据
}else{ //找到了
auto it=mp.find(name);
it->second.score+=score;
it->second.stu_amount++;
}
sch.score=0;sch.stu_amount=0;
}
vector<pair<string,struct school>> v;
for(auto it=mp.begin();it!=mp.end();it++){
it->second.score=(int)it->second.score; //这句很重要,不然最后一个测试点答案错误
v.push_back(*it); //将Map中的数据重新复制到vector中,主要是为了方便排序!
}
sort(v.begin(),v.end(),cmp);
v[0].second.rank=1;
for(i=1;i<v.size();i++){ //排名
if(v[i].second.score==v[i-1].second.score){
v[i].second.rank=v[i-1].second.rank;
}else{
v[i].second.rank=i+1;
}
}
cout<<v.size()<<endl;
for(i=0;i<v.size();i++){
cout<<v[i].second.rank<<" "<<v[i].second.name<<" "<<int(v[i].second.score)<<" "<<v[i].second.stu_amount<<endl;
}
return 0;
}