名人堂与代金券(结构体排序)

对于在中国大学MOOC(http://www.icourse163.org/ )学习“数据结构”课程的学生,想要获得一张合格证书,总评成绩必须达到 60 分及以上,并且有另加福利:总评分在 [G, 100] 区间内者,可以得到 50 元 PAT 代金券;在 [60, G) 区间内者,可以得到 20 元PAT代金券。全国考点通用,一年有效。同时任课老师还会把总评成绩前 K 名的学生列入课程“名人堂”。本题就请你编写程序,帮助老师列出名人堂的学生,并统计一共发出了面值多少元的 PAT 代金券。

输入格式:
输入在第一行给出 3 个整数,分别是 N(不超过 10 000 的正整数,为学生总数)、G(在 (60,100) 区间内的整数,为题面中描述的代金券等级分界线)、K(不超过 100 且不超过 N 的正整数,为进入名人堂的最低名次)。接下来 N 行,每行给出一位学生的账号(长度不超过15位、不带空格的字符串)和总评成绩(区间 [0, 100] 内的整数),其间以空格分隔。题目保证没有重复的账号。

输出格式:
首先在一行中输出发出的 PAT 代金券的总面值。然后按总评成绩非升序输出进入名人堂的学生的名次、账号和成绩,其间以 1 个空格分隔。需要注意的是:成绩相同的学生享有并列的排名,排名并列时,按账号的字母序升序输出。

输入样例:
10 80 5
[email protected] 78
[email protected] 87
[email protected] 65
[email protected] 96
[email protected] 39
[email protected] 87
[email protected] 80
[email protected] 88
[email protected] 80
[email protected] 70

输出样例:
360
1 [email protected] 96
2 [email protected] 88
3 [email protected] 87
3 [email protected] 87
5 [email protected] 80
5 [email protected] 80

这道题用到了C++里面的快速排序的方法:

  • 排结构体是需要在比较函数里面声明为结构体类型,比较数值时直接返回即可;比较字符串时,需要借用字符串库函数里面的strcmp()。
  • 注意输出的序号变化。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
typedef struct node
{
	char s[20];
	int n;
};
int cmp(node a, node b)
{
	if (a.n == b.n) return strcmp(a.s, b.s)<0 ? 1 : 0;//1,>. 0,=. -1,<.
	return a.n>b.n;
}
int main()
{
	int t, sum = 0, r = 1, l = 0;
	int g, k;
	node p[10010];
	scanf("%d %d %d", &t, &g, &k);
	for (int i = 0; i<t; i++)
	{
		getchar();
		scanf("%s %d", p[i].s, &p[i].n);
	}
	sort(p, p + t, cmp);
	for (int i = 0; i < t; i++)
	{
		if (p[i].n >= g && p[i].n <= 100) sum += 50;
		if (p[i].n >= 60 && p[i].n < g) sum += 20;
	}
	printf("%d\n", sum);
	for (int i = 0; i < t&&r<=k; i++)
	{
		if (p[i].n == p[i-1].n)
		{
			printf("%d %s %d\n", r, p[i].s, p[i].n);
			l++;
		}
		else
		{
			r += l;
			if (r>k) break;
			printf("%d %s %d\n", r, p[i].s, p[i].n);
			l = 1;
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44017102/article/details/88789135