题目描述
小明是一名新老师,他需要将学生按考试总分或单科分数进行排名。学生的信息包括姓名、科目和对应的分数。帮助小明完成这个任务吧!
输入描述
-
第一行包含两个整数 n 和 m,分别代表学生人数和科目数量。
- 0 < n < 100
- 0 < m < 10
-
第二行包含 m 个科目名称,用空格隔开。
- 科目名称只包含英文字母,长度不超过10个字符。
- 科目的出现顺序和后续输入的学生成绩一一对应。
- 不会出现重复的科目名称。
-
接下来的 n 行,每行包含一个学生的姓名和该生 m 个科目的成绩(用空格隔开)。
- 学生不会重名。
- 学生姓名只包含英文字母,长度不超过10个字符。
- 成绩是0~100的整数,依次对应第二行输入的科目。
-
第 n+2 行输入用作排名的科目名称。如果科目不存在,则按总分进行排序。
输出描述
输出一行,按成绩排序后的学生名字,用空格隔开。如果成绩相同,则按学生姓名的字典顺序排序。
示例
题目解析
本题的核心在于动态排序规则的应用。排序规则可能基于特定科目的成绩,也可能基于总分。排序过程需要考虑两个因素:
-
排序规则:根据最后一行输入的科目名称确定。如果科目存在,则按该科目成绩排序;如果不存在,则按总分排序。
-
排序细节:在成绩相同的情况下,需要按学生姓名的字典顺序进行排序。
C++代码实现
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>using namespace std;// 学生信息结构体
struct Student {string name;vector<int> scores;int totalScore;
};// 自定义比较函数,用于排序
bool compareStudents(const Student& a, const Student& b, int sortIndex) {// 如果排序索引指向总分,则比较总分if (sortIndex == -1) {return (a.totalScore < b.totalScore) || (a.totalScore == b.totalScore && a.name < b.name);}// 否则,比较指定科目的成绩return (a.scores[sortIndex] < b.scores[sortIndex]) || (a.scores[sortIndex] == b.scores[sortIndex] && a.name < b.name);
}int main() {int n, m;cin >> n >> m;vector<string> subjects(m);for (int i = 0; i < m; ++i) {cin >> subjects[i];}vector<Student> students(n);for (int i = 0; i < n; ++i) {cin >> students[i].name;students[i].scores.resize(m);students[i].totalScore = 0;for (int j = 0; j < m; ++j) {cin >> students[i].scores[j];students[i].totalScore += students[i].scores[j];}}string sortSubject;cin >> sortSubject;// 确定排序索引,如果科目不存在,则索引为-1,表示按总分排序int sortIndex = -1;for (int i = 0; i < m; ++i) {if (subjects[i] == sortSubject) {sortIndex = i;break;}}// 根据排序索引进行排序sort(students.begin(), students.end(), [&](const Student& a, const Student& b) {return compareStudents(a, b, sortIndex);});// 输出排序后的学生名字for (const auto& student : students) {cout << student.name << " ";}cout << endl;return 0;
}
Java代码实现
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import java.util.Vector;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int n, m;n = scanner.nextInt();m = scanner.nextInt();Vector<String> subjects = new Vector<>();for (int i = 0; i < m; ++i) {subjects.add(scanner.next());}Student[] students = new Student[n];for (int i = 0; i < n; ++i) {students[i] = new Student();students[i].name = scanner.next();students[i].scores = new int[m];students[i].totalScore = 0;for (int j = 0; j < m; ++j) {students[i].scores[j] = scanner.nextInt();students[i].totalScore += students[i].scores[j];}}String sortSubject = scanner.next();int sortIndex = -1;for (int i = 0; i < m; ++i) {if (subjects.get(i).equals(sortSubject)) {sortIndex = i;break;}}Arrays.sort(students, new Comparator<Student>() {@Overridepublic int compare(Student a, Student b) {return compareStudents(a, b, sortIndex);}});for (Student student : students) {System.out.print(student.name + " ");}System.out.println();}public static boolean compareStudents(Student a, Student b, int sortIndex) {// 如果排序索引指向总分,则比较总分if (sortIndex == -1) {return (a.totalScore < b.totalScore) || (a.totalScore == b.totalScore && a.name.compareTo(b.name) < 0);}// 否则,比较指定科目的成绩return (a.scores[sortIndex] < b.scores[sortIndex]) || (a.scores[sortIndex] == b.scores[sortIndex] && a.name.compareTo(b.name) < 0);}
}
Python代码实现
import sys
from collections import Counter
from typing import Listclass Main:def main(self):n, m = map(int, input().split())subjects = list(map(str, input().split()))students = []for i in range(n):students.append({"name": input(), "scores": list(map(int, input().split())), "totalScore": sum(students[-1]["scores"])})sort_subject = input()sort_index = -1for i, subject in enumerate(subjects):if subject == sort_subject:sort_index = ibreakstudents.sort(key=lambda x: (-x["totalScore"], x["name"]) if sort_index == -1 else (-x["scores"][sort_index], x["name"]))for student in students:print(student["name"], end=" ")print()if __name__ == "__main__":Main().main()
C代码实现
#include <stdio.h>
#include <stdbool.h>
#include <string.h>typedef struct {char name[20];int scores[100];int totalScore;
} Student;int compare(const void *a, const void *b) {Student *students = (Student *)a;Student *other = (Student *)b;int sort_index = -1;for (int i = 0; i < students[0].scores[0]; i++) {if (strcmp(students[0].scores[i + 1], sort_subject) == 0) {sort_index = i + 1;break;}}if (sort_index == -1) {return (-students[0].totalScore == -other[0].totalScore) ? strcmp(students[0].name, other[0].name) : -1;} else {return (-students[0].scores[sort_index] == -other[0].scores[sort_index]) ? strcmp(students[0].name, other[0].name) : -1;}
}int main() {int n, m;scanf("%d %d", &n, &m);char sort_subject[20];scanf("%s", sort_subject);Student students[n];for (int i = 0; i < n; i++) {scanf("%s", students[i].name);for (int j = 0; j < m; j++) {scanf("%d", &students[i].scores[j]);}students[i].totalScore = 0;for (int j = 0; j < m; j++) {students[i].totalScore += students[i].scores[j];}}qsort(students, n, sizeof(students[0]), compare);for (int i = 0; i < n; i++) {printf("%s", students[i].name);if (i < n - 1) {printf(" ");}}printf("\n");return 0;
}
Go代码实现
package mainimport ("fmt""io""strings""sort"
)// 学生信息结构体
type Student struct {name stringscores []inttotalScore int
}// 自定义比较函数,用于排序
func compareStudents(a, b Student, sortIndex int) bool {// 如果排序索引指向总分,则比较总分if sortIndex == -1 {return (a.totalScore < b.totalScore) || (a.totalScore == b.totalScore && a.name < b.name)}// 否则,比较指定科目的成绩return (a.scores[sortIndex] < b.scores[sortIndex]) || (a.scores[sortIndex] == b.scores[sortIndex] && a.name < b.name)
}func main() {var reader io.Readerreader = os.Stdinvar n, m intfmt.Fscanf(reader, "%d %d", &n, &m)var subjects []stringfor i := 0; i < m; i++ {var subject stringfmt.Fscanf(reader, "%s", &subject)subjects = append(subjects, subject)}students := make([]Student, n)for i := 0; i < n; i++ {var name stringfmt.Fscanf(reader, "%s", &name)students[i].name = namestudents[i].scores = make([]int, m)students[i].totalScore = 0for j := 0; j < m; j++ {fmt.Fscanf(reader, "%d", &students[i].scores[j])students[i].totalScore += students[i].scores[j]}}var sortSubject stringfmt.Fscanf(reader, "%s", &sortSubject)// 确定排序索引,如果科目不存在,则索引为-1,表示按总分排序sortIndex := -1for i, subject := range subjects {if subject == sortSubject {sortIndex = ibreak}}// 根据排序索引进行排序sort.Slice(students, func(i, j int) bool {return compareStudents(students[i], students[j], sortIndex)})// 输出排序后的学生名字for _, student := range students {fmt.Println(student.name)}
}
PHP代码实现
<?php
$n = 0;
$m = 0;
$subjects = [];
$students = [];
$sortSubject = '';// 学生信息结构体
class Student {public $name;public $scores;public $totalScore;public function __construct($name, $scores, $totalScore) {$this->name = $name;$this->scores = $scores;$this->totalScore = $totalScore;}
}// 自定义比较函数,用于排序
function compareStudents($a, $b, $sortIndex) {// 如果排序索引指向总分,则比较总分if ($sortIndex == -1) {return $a->totalScore < $b->totalScore || ($a->totalScore == $b->totalScore && $a->name < $b->name);}// 否则,比较指定科目的成绩return $a->scores[$sortIndex] < $b->scores[$sortIndex] || ($a->scores[$sortIndex] == $b->scores[$sortIndex] && $a->name < $b->name);
}function main() {$stdin = STDIN;fscanf($stdin, "%d %d", $n, $m);for ($i = 0; $i < $m; ++$i) {fscanf($stdin, "%s", $subjects[$i]);}for ($i = 0; $i < $n; ++$i) {fscanf($stdin, "%s", $students[$i]->name);$students[$i]->scores = array_fill(0, $m, 0);$students[$i]->totalScore = 0;for ($j = 0; $j < $m; ++$j) {fscanf($stdin, "%d", $students[$i]->scores[$j]);$students[$i]->totalScore += $students[$i]->scores[$j];}}fscanf($stdin, "%s", $sortSubject);// 确定排序索引,如果科目不存在,则索引为-1,表示按总分排序$sortIndex = -1;for ($i = 0; $i < $m; ++$i) {if ($subjects[$i] == $sortSubject) {$sortIndex = $i;break;}}// 根据排序索引进行排序usort($students, function($a, $b) use ($sortIndex) {return compareStudents($a, $b, $sortIndex);});// 输出排序后的学生名字foreach ($students as $student) {echo $student->name . " ";}echo PHP_EOL;
}main();
JS代码实现
const { Your_function } = require(‘Your_script’);// 学生信息结构体
class Student {constructor(name, scores) {this.name = name;this.scores = scores;this.totalScore = this.calculateTotalScore();}calculateTotalScore() {let totalScore = 0;for (let score of this.scores) {totalScore += score;}return totalScore;}
}// 自定义比较函数,用于排序
function compareStudents(a, b, sortIndex) {// 如果排序索引指向总分,则比较总分if (sortIndex === -1) {return (a.totalScore < b.totalScore) || (a.totalScore === b.totalScore && a.name < b.name);}// 否则,比较指定科目的成绩return (a.scores[sortIndex] < b.scores[sortIndex]) || (a.scores[sortIndex] === b.scores[sortIndex] && a.name < b.name);
}async function main() {const [n, m] = await readLine();const subjects = await readLine().join('').split(' ');const students = await Promise.all(Array.from({ length: n }, async (_, i) => {const [name] = await readLine();const scores = await readLine().map(Number);return new Student(name, scores);}));const sortSubject = await readLine().join('');const sortIndex = subjects.indexOf(sortSubject);students.sort((a, b) => {return compareStudents(a, b, sortIndex);});console.log(students.map(student => student.name).join(' '));
}main().catch(error => {console.error(error);process.exit(1);
});