问题描述
小明刚经过了一次数学考试,老师由于忙碌忘记排名了,于是老师把这个光荣的任务交给了小明,小明则找到了聪明的你,希望你能帮他解决这个问题。
输入格式
第一行包含一个正整数N,表示有个人参加了考试。接下来N行,每行有一个字符串和一个正整数,分别表示人名和对应的成绩,用一个空格分隔。
输出格式
输出一共有N行,每行一个字符串,第i行的字符串表示成绩从高到低排在第i位的人的名字,若分数一样则按人名的字典序顺序从小到大。
样例输入
3
aaa 47
bbb 90
ccc 70
样例输出
bbb
ccc
aaa 【数据规模和约定】
人数<=100,分数<=100,人名仅包含小写字母。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student
{
char name[100];
int score;
};
int cmp(const void *a, const void *b)
{
struct Student sa = *(struct Student *)a;
struct Student sb = *(struct Student *)b;
if (sa.score > sb.score)
return -1;
else if (sa.score < sb.score)
return 1;
else
return strcmp(sa.name, sb.name);
}
int main()
{
int N;
struct Student list[105];
scanf("%d", &N);
for (int i = 0; i < N; ++i)
scanf("%s %d", list[i].name, &list[i].score);
qsort(list, N, sizeof(struct Student), cmp);
for (int i = 0; i < N; ++i)
printf("%s\n", list[i].name);
return 0;
}
*(struct Student *)a可能有的同学会不理解。
题目中声明来了:
int cmp(const void *a, const void *b)
那么cmp函数有两个无类型的形参 *a, *b。
(struct Student *)的意思是将a和b强制类型转换为结构体指针类型,例如:float a ——> (int )a
强制类型转换完成后
struct Student sa = *a;
将结构体的首地址复制给指针a。