【2019暑期】【PAT甲级】1141 PAT Ranking of Institutions (25 分)

本文深入探讨了C++中排名算法的实现,包括如何使用结构体和容器进行数据排序和排名,同时介绍了vector和unordered_map在算法优化中的作用。通过实例,展示了如何在竞赛编程中高效地处理数据,实现快速排名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

rank排名方法
注意是和前一个比,也可以学习大佬方法

arr[0].rank = 1;
for(int i=1; i<l; i++){
    if(arr[i].score == arr[i-1].score) arr[i].rank = arr[i-1].rank;
    else arr[i].rank = i+1;
}
int rank=0;
	int pre = -1;
	for(int i=0; i<ans.size(); i++){
		if(pre != ans[i].score) rank++;
		pre = ans[i].score;
	}

unordered_map 是map的无序版,时间更短,不会超时
map底层是红黑树,平衡二叉树插入,需要时间
unordered_map 是用哈希,时间更短
注意需要加头文件,和本身名字一样

学习到了vector里面是结构体的时候怎么插入
ans.push_back(node{,})

#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
#include <cmath>
#include <map> 
#include <set>
#include <unordered_map> 
using namespace std;

struct student{
	string school;
	int tws,ns;
};
bool my(student a,student b){
	if(a.tws==b.tws){
		if(a.ns==b.ns) return a.school < b.school;
		else return a.ns < b.ns;
	}		
	else return a.tws > b.tws;
}

int main(){
	
	int n;
	cin >> n;
	unordered_map<string,int> cnt;
	unordered_map<string,double> sum;
	for(int i=0; i<n; i++){
		string a,b;
		double c;
		cin >> a >> c >> b;
		for(int j=0; j<b.length();j++)
			b[j] = tolower(b[j]);
		if(a[0]=='B') c = c/1.5;
		if(a[0]=='T') c = c*1.5;
		sum[b] += c;
		cnt[b]++;		
	}
	vector<student> ans;
	for(auto it = cnt.begin(); it!=cnt.end();it++)
		ans.push_back(student{it->first,(int)sum[it->first],cnt[it->first]});
	sort(ans.begin(),ans.end(),my);
	cout << ans.size() << endl;
	int rank=1;
	cout << rank << " " << ans[0].school << " ";
	cout << ans[0].tws << " " << ans[0].ns << endl;	
	for(int i=1; i<ans.size(); i++){
		if(ans[i].tws == ans[i-1].tws) ;
		else rank = i+1;
		cout << rank << " " << ans[i].school << " ";
		cout << ans[i].tws << " " << ans[i].ns << endl;			
	}
	
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值