{ }codelper
记录记录列表自定义排序P0067

成绩排名表

第一行给出学生人数 n,接下来 n 行每行给出 "姓名 语文 英语 数学",用单个空格分隔。
求出每个学生三科的总分并输出排名表。
总分高的学生在前;总分相同时按姓名的字符编码顺序(ASCII:大写字母在小写字母之前;若一个姓名是另一个的开头,短的在前)。
每行输出 "名次 姓名 总分"。
名次为 1 +(总分比自己高的学生人数),因此总分相同的学生名次相同,下一个名次相应跳过(例:1, 1, 3)。

输入
1 ≤ n ≤ 1000,0 ≤ 分数 ≤ 100(整数)。
姓名为 1 到 10 个英文大小写字母,互不相同
输出
n 行,每行名次、姓名、总分用单个空格分隔
样例 1 · stdin
5
mina 90 85 100
Jun 80 95 100
alex 70 60 50
seo 100 100 75
Bora 60 60 60
stdout
1 Jun 275
1 mina 275
1 seo 275
4 Bora 180
4 alex 180
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

把一个学生(姓名, 总分)打包成一个整体的方法因语言而异:Python @dataclass(或元组),Java record Student(String name, int total),C# record Student(string Name, int Total),C・C++ struct,JS・TS 用对象 { name, total }(TS 用 interface 描述结构)。
Craykon 没有类,所以每个学生用一个 字典()(s["name"]、s["total"])放进列表,再像 students.排序(按总分) 这样传入比较函数名。
三个陷阱:① 姓名列表和总分列表分开存放(平行列表)、只对总分排序,配对就会错乱——要对打包后的记录排序。
② 在 Python 中把 (总分, 姓名) 用 reverse=True 排序,姓名也会倒过来(用 key=lambda s: (-s.total, s.name))。
③ 姓名比较:JS localeCompare 按人类词典顺序,"amy" 会排在 "Bob" 前面;C# 默认的字符串比较也可能遵循区域文化规则。
字符编码顺序是 JS <、C# StringComparer.Ordinal、Java compareTo、C strcmp、C++ <。
名次不是位置 i + 1,只有总分与前一个学生不同时才改为 i + 1。

Pythonmain.py · 23 行
import sysfrom dataclasses import dataclass  @dataclassclass Student:    name: str    total: int  lines = sys.stdin.read().split("\n")n = int(lines[0])students = []for line in lines[1:n + 1]:    name, *scores = line.split()    students.append(Student(name, sum(map(int, scores)))) students.sort(key=lambda s: (-s.total, s.name))rank = 0for i, s in enumerate(students):    if i == 0 or s.total != students[i - 1].total:        rank = i + 1    print(rank, s.name, s.total)
JavaScriptmain.js · 16 行
const lines = require("fs").readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);const students = [];for (let i = 1; i <= n; i++) {  const [name, ...scores] = lines[i].trim().split(" ");  students.push({ name, total: scores.reduce((sum, x) => sum + Number(x), 0) });}// 이름은 글자 코드 순(< 비교). localeCompare는 대소문자를 사람 사전처럼 섞는다students.sort((a, b) => b.total - a.total || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));const out = [];let rank = 0;students.forEach((s, i) => {  if (i === 0 || s.total !== students[i - 1].total) rank = i + 1;  out.push(`${rank} ${s.name} ${s.total}`);});console.log(out.join("\n"));
TypeScriptmain.ts · 22 行
import { readFileSync } from "node:fs"; interface Student {  name: string;  total: number;} const lines: string[] = readFileSync(0, "utf8").split("\n");const n: number = Number(lines[0]);const students: Student[] = [];for (let i = 1; i <= n; i++) {  const [name, ...scores] = lines[i].trim().split(" ");  students.push({ name, total: scores.reduce((sum, x) => sum + Number(x), 0) });}students.sort((a, b) => b.total - a.total || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));const out: string[] = [];let rank = 0;students.forEach((s, i) => {  if (i === 0 || s.total !== students[i - 1].total) rank = i + 1;  out.push(`${rank} ${s.name} ${s.total}`);});console.log(out.join("\n"));
JavaMain.java · 31 行
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Comparator;import java.util.List; public class Main {    record Student(String name, int total) {}     public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(in.readLine().trim());        List<Student> students = new ArrayList<>();        for (int i = 0; i < n; i++) {            String[] p = in.readLine().trim().split(" ");            int total = Integer.parseInt(p[1]) + Integer.parseInt(p[2]) + Integer.parseInt(p[3]);            students.add(new Student(p[0], total));        }        // String.compareTo는 글자 코드 순이다(대문자가 소문자보다 먼저)        students.sort(Comparator.comparingInt(Student::total).reversed().thenComparing(Student::name));        StringBuilder out = new StringBuilder();        int rank = 0;        for (int i = 0; i < n; i++) {            Student s = students.get(i);            if (i == 0 || s.total() != students.get(i - 1).total()) rank = i + 1;            out.append(rank).append(' ').append(s.name()).append(' ').append(s.total()).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 27 行
using System;using System.Collections.Generic;using System.Linq; record Student(string Name, int Total); class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine());        var students = new List<Student>();        for (int i = 0; i < n; i++)        {            string[] p = Console.ReadLine().Trim().Split(' ');            students.Add(new Student(p[0], p.Skip(1).Sum(int.Parse)));        }        // 기본 문자열 비교는 문화권 규칙을 따를 수 있어 글자 코드 순(Ordinal)을 밝혀 준다        var sorted = students.OrderByDescending(s => s.Total).ThenBy(s => s.Name, StringComparer.Ordinal).ToList();        int rank = 0;        for (int i = 0; i < sorted.Count; i++)        {            if (i == 0 || sorted[i].Total != sorted[i - 1].Total) rank = i + 1;            Console.WriteLine($"{rank} {sorted[i].Name} {sorted[i].Total}");        }    }}
C++main.cpp · 30 行
#include <algorithm>#include <iostream>#include <string>#include <vector> struct Student {    std::string name;    int total;}; int main() {    int n;    std::cin >> n;    std::vector<Student> students;    for (int i = 0; i < n; i++) {        std::string name;        int k, e, m;        std::cin >> name >> k >> e >> m;        students.push_back({name, k + e + m});    }    std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {        if (a.total != b.total) return a.total > b.total;        return a.name < b.name;    });    int rank = 0;    for (int i = 0; i < n; i++) {        if (i == 0 || students[i].total != students[i - 1].total) rank = i + 1;        std::cout << rank << ' ' << students[i].name << ' ' << students[i].total << '\n';    }}
Cmain.c · 32 行
#include <stdio.h>#include <stdlib.h>#include <string.h> struct Student {    char name[11];    int total;}; static int by_total_then_name(const void *pa, const void *pb) {    const struct Student *a = pa, *b = pb;    if (a->total != b->total) return b->total - a->total;    return strcmp(a->name, b->name); /* 글자 코드 순 */} int main(void) {    static struct Student s[1000];    int n;    scanf("%d", &n);    for (int i = 0; i < n; i++) {        int k, e, m;        scanf("%10s %d %d %d", s[i].name, &k, &e, &m);        s[i].total = k + e + m;    }    qsort(s, n, sizeof s[0], by_total_then_name);    int rank = 0;    for (int i = 0; i < n; i++) {        if (i == 0 || s[i].total != s[i - 1].total) rank = i + 1;        printf("%d %s %d\n", rank, s[i].name, s[i].total);    }    return 0;}
Craykonmain.cray · 36 行
// 크레이콘에는 클래스가 없어서 학생 한 명을 사전 하나(이름·합계)로 묶는다n = 控制台.读行().转数字();students = [];循环 (i = 0; i < n; i++){    p = 控制台.读行().去空白().分割();    s = 字典();    s["name"] = p[0];    s["total"] = p[1].转数字() + p[2].转数字() + p[3].转数字();    students.添加(s);}students.排序(합계순);rank = 0;循环 (i = 0; i < n; i++){    s = students[i];    如果 (i == 0 || s["total"] != students[i - 1]["total"])    {        rank = i + 1;    }    控制台.输出(rank + " " + s["name"] + " " + s["total"]);} // 합계가 큰 것 먼저, 같으면 이름의 글자 코드 순합계순(앞, 뒤){    如果 (앞["total"] != 뒤["total"])    {        返回 뒤["total"] - 앞["total"];    }    如果 (앞["name"] < 뒤["name"])    {        返回 -1;    }    返回 1;}