蓝桥杯 ADV-291 算法提高 成绩排序2

算法提高 成绩排序2

时间限制:1.0s   内存限制:256.0MB

问题描述

  给出n个学生的成绩,将这些学生按成绩排序,排序规则:总分高的在前;总分相同,数学成绩高的在前;总分与数学相同,英语高的在前;总分数学英语都相同,学号小的在前

输入格式

  第一行一个正整数n,表示学生人数
  接下来n行每行3个0~100的整数,第i行表示学号为i的学生的数学、英语、语文成绩

输出格式

  输出n行,每行表示一个学生的数学成绩、英语成绩、语文成绩、学号
  按排序后的顺序输出

样例输入

2
1 2 3
2 3 4

样例输出

2 3 4 2
1 2 3 1

数据规模和约定

  n≤100

#include <stdio.h>
#include <stdlib.h>

struct Student
{
    int chinese;
    int math;
    int english;
    int id;
};

int cmp(const void *a, const void *b)
{
    struct Student sa = *(struct Student *)a;
    struct Student sb = *(struct Student *)b;

    int total_a = sa.math + sa.english + sa.chinese;
    int total_b = sb.math + sb.english + sb.chinese;

    if (total_a > total_b)
        return -1;
    else if (total_a < total_b)
        return 1;
    else
    {
        if (sa.math > sb.math)
            return -1;
        else if (sa.math < sb.math)
            return 1;
        else
        {
            if (sa.english > sb.english)
                return -1;
            else if (sa.english < sb.english)
                return 1;
            else
                return sa.id > sb.id;
        }
    }
}

int main()
{
    int n;
    struct Student list[105];

    scanf("%d", &n);
    for (int i = 0; i < n; ++i)
    {
        scanf("%d %d %d", &list[i].math, &list[i].english, &list[i].chinese);
        list[i].id = i + 1;
    }

    qsort(list, n, sizeof(struct Student), cmp);

    for (int i = 0; i < n; ++i)
        printf("%d %d %d %d\n", list[i].math, list[i].english, list[i].chinese, list[i].id);

    return 0;
}
发布了317 篇原创文章 · 获赞 44 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/liulizhi1996/article/details/104329605