ADV-288 试题 算法提高 成绩排名

问题描述

  小明刚经过了一次数学考试,老师由于忙碌忘记排名了,于是老师把这个光荣的任务交给了小明,小明则找到了聪明的你,希望你能帮他解决这个问题。

输入格式

  第一行包含一个正整数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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值