[PAT] A1025 PAT Ranking

时间:2020-05-06
本文章向大家介绍[PAT] A1025 PAT Ranking,主要包括[PAT] A1025 PAT Ranking使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

tips

1 关注排名的实现代码。

2 熟练sort的使用。

3 熟练vector的使用。

插入用xxx.push_back(i);

题目大意

有n个考场,每个考场有若干数量的考生。现在给出各个考场中考生的准考证号和分数,要求将所有考生按分数从高到低排序,并按顺序输出所有考生的准考证号、排名、考场号、考场内排名。
原题链接

思路

1 按考场读入各考生的信息,并对当前读入考场的所有考生进行排序。之后将该考场的所有考生的排名写入结构体。

这里用了vector保存考生信息

for (j = 0; j < k; j++){
	testees temp;
	scanf("%s %d", &temp.id, &temp.score);
	temp.ln = i + 1;
	test.push_back(temp);
}

排序。
排名的实现。

sort(test.begin() + total, test.end(), cmp);
int rank = 1;
est[total].lr = 1;
for (j = total + 1; j < total + k; j++) {
	if (test[j].score == test[j - 1].score)
		test[j].lr = test[j - 1].lr;
	else test[j].lr = j - total + 1;
}

2 对所有考生进行排序,并计算总排名。

3 输出。

AC代码

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>///////
#include<iostream>
using namespace std;
#define N 102
struct testees {
	char id[14];
	int score;
	int fr, ln, lr;
};
bool cmp(testees a, testees b) {
	if (a.score == b.score)return strcmp(a.id, b.id) < 0;
	else return a.score > b.score;
}
int main(){
	int n;
	scanf("%d", &n);
	int total = 0;
	int i, j;
	vector<testees> test;
	for (i = 0; i < n; i++){
		int k;
		scanf("%d", &k);
		for (j = 0; j < k; j++){
			testees temp;
			scanf("%s %d", &temp.id, &temp.score);
			temp.ln = i + 1;
			test.push_back(temp);///////
		}
		sort(test.begin() + total, test.end(), cmp);
		int rank = 1;
		test[total].lr = 1;
		for (j = total + 1; j < total + k; j++) {
			if (test[j].score == test[j - 1].score)
				test[j].lr = test[j - 1].lr;
			else test[j].lr = j - total + 1;
		}////////
		total += k;
	}
	sort(test.begin(), test.end(), cmp);
	test[0].fr = 1; 
	for (i = 1; i < total; i++){
		if (test[i].score == test[i - 1].score) {
			test[i].fr = test[i - 1].fr;
		}
		else test[i].fr = i + 1;
	}/////////
	printf("%d\n", total);
	for (i = 0; i < total; i++)
		printf("%s %d %d %d\n", test[i].id, test[i].fr, test[i].ln, test[i].lr);
	return 0;
}

原文地址:https://www.cnblogs.com/yue36/p/12837829.html