0
点赞
收藏
分享

微信扫一扫

B1085 PAT单位排行 (25 分| unordered_map| vector,附详细注释,逻辑分析)


写在前面

  • 思路分析
  • 1个map-cnt存储学校名称-参赛人数
  • 1个map-sum计算学校名称-加权成绩
  • map中学校元数据信息封装至vector ans,类型为node
  • 对ans数组排序,按要求输出。
  • pres表示前1个学校加权总分,pres和当前学校加权总分不同,rank下标+1
  • 否则不变
  • 问题点
  • 学校排名,​​间隔​
  • 加权分数取整数是对最后总和取整(​​3分测试点​​)
  • map最后1个测试点超时,更改为unordered_map
  • 题目简单,35分钟内a题目

测试用例

input:
10
A57908 85 Au
B57908 54 LanX
A37487 60 au
T28374 67 CMU
T32486 24 hypu
A66734 92 cmu
B76378 71 AU
A47780 45 lanx
A72809 100 pku
A03274 45 hypu

output:
5
1 cmu 192 2
1 au 192 3
3 pku 100 1
4 hypu 81 2
4 lanx 81 2

ac代码

  • ​​参考链接​​

#include <iostream>
#include <algorithm>
#include <cctype>
#include <vector>
#include <unordered_map>
using namespace std;
struct node
{
string school;
int tws, rs;
};

bool cmp(node a, node b)
{
if(a.tws != b.tws)
return a.tws>b.tws;
else if(a.rs!=b.rs)
return a.rs<b.rs;
else
return a.school < b.school;
}

int main()
{
int n;
scanf("%d", &n);
unordered_map<string, int> cnt;
unordered_map<string, double> sum;

string id, school;
double score;
for(int i=0; i<n; i++)
{
cin >> id >> score >> school;
transform(school.begin(),school.end(), school.begin(), ::tolower);
if(id[0]=='B')
score = score/1.5;
else if(id[0]=='T')
score = score*1.5;
sum[school] += score;
cnt[school]++;
}

vector<node> ans;
for(auto it=cnt.begin(); it!=cnt.end(); it++)
ans.push_back(node{it->first, (int)sum[it->first],cnt[it->first]});
sort(ans.begin(), ans.end(), cmp);

int ranks = 0, pres = -1;
printf("%d\n", ans.size());
for(int i=0; i<ans.size(); i++)
{
if(pres != ans[i].tws) ranks = i+1;
pres = ans[i].tws;
printf("%d %s %d %d\n", ranks,ans[i].school.c_str(),ans[i].tws, ans[i].rs);
}

return 0;
}

知识点小结

// 无序map
unordered_map<string, int> cnt;

// 字符串大小写转换
transform(school.begin(),school.end(), school.begin(), ::tolower);

// 结构体迭代赋值
vector<node> ans;
ans.push_back(node{it->first, (int)sum[it->first], cnt[it->first]});

// 不定序号实现
int rank = 0, pres = -1;
printf("%d\n", (int)ans.size());
for (int i = 0; i < ans.size(); i++) {
if (pres != ans[i].tws) rank = i + 1;
pres = ans[i].tws;
......
}


举报

相关推荐

1085 PAT单位排行 (25 分)

0 条评论