PAT甲级 1025 PAT Ranking (25分)

生来就可爱ヽ(ⅴ<●) 提交于 2020-02-07 00:48:46

1025 PAT Ranking (25分)

题目链接:PAT A 1025
在这里插入图片描述
在这里插入图片描述

题目大意:给出每个考场的所有考生号以及考生成绩,要求将他们归并到一起排序后输出,同时还要输出考生所在的考场号(编号由1到n)以及考生在那个考场的排名,如果考生成绩相同,则按考生号升序输出~

思路分析:在排序题中算是非常简单的了,只是根据成绩和考生号排序,简单直观。而考场编号和考生在考场的排名则存储到map容器里,一个考生号对应一个排名,最后直接输出即可。需要注意的是,如果考生成绩相同,那么他们的名次应该是一样的,同时后面考生的名次要依次顺延。

AC代码:

#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
using namespace std;
struct stu{
	string id; //考生号 
	int score; //成绩 
};
bool cmp(stu a, stu b) { //排序函数 
	if(a.score != b.score) //成绩不同则按成绩排序 
		return a.score > b.score;
	else //成绩相同则按考生号升序的方式排 
		return a.id < b.id;
}
int main() {
	int n, k, num = 0; //num统计考生数 
	scanf("%d", &n);
	vector<stu> v; //答案数组 
	map<string, int> m, localrank; //m记录考生所在考场,localrank记录考生在考场的排名 
	for(int i = 0; i < n; i++) {
		scanf("%d", &k);
		num += k;
		vector<stu> temp; //临时数组 
		for(int j = 0; j < k; j++) {
			stu student;
			cin >> student.id >> student.score;
			m[student.id] = i + 1; //因为i是从0开始 
			temp.push_back(student);
			v.push_back(student);
		}
		sort(temp.begin(), temp.end(), cmp);
		localrank[temp[0].id] = 1; //第一名 
		int gain = temp[0].score, cnt = 1; //cnt为间隔 
		for(int i = 1; i < temp.size(); i++) {
			if(temp[i].score != gain) { //和前一名分数不一样 
				localrank[temp[i].id] = localrank[temp[i - 1].id] + cnt;
				cnt = 1; //重置cnt 
			}
			else { //和前一名分数一样 
				localrank[temp[i].id] = localrank[temp[i - 1].id];
				cnt++;
			}
			gain = temp[i].score;
		}
	}
	sort(v.begin(), v.end(), cmp);
	int finalrank = 1, cnt = 1;
	cout << num << endl;
	cout << v[0].id << " " << finalrank << " " << m[v[0].id]  << " " << localrank[v[0].id] << endl;
	for(int i = 1; i < v.size(); i++) {
		if(v[i].score == v[i - 1].score) 
			cnt++;
		else {
			finalrank += cnt;
			cnt = 1;
		}
		cout << v[i].id << " " << finalrank << " " << m[v[i].id]  << " " << localrank[v[i].id] << endl;
	}
	return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!