华为OD机试 - 智能成绩表( Python & C & C++ & Java&Go & JS & PHP)

题目描述

小明是一名新老师,他需要将学生按考试总分或单科分数进行排名。学生的信息包括姓名、科目和对应的分数。帮助小明完成这个任务吧!

输入描述

  1. 第一行包含两个整数 n 和 m,分别代表学生人数和科目数量。

    • 0 < n < 100
    • 0 < m < 10
  2. 第二行包含 m 个科目名称,用空格隔开。

    • 科目名称只包含英文字母,长度不超过10个字符。
    • 科目的出现顺序和后续输入的学生成绩一一对应。
    • 不会出现重复的科目名称。
  3. 接下来的 n 行,每行包含一个学生的姓名和该生 m 个科目的成绩(用空格隔开)。

    • 学生不会重名。
    • 学生姓名只包含英文字母,长度不超过10个字符。
    • 成绩是0~100的整数,依次对应第二行输入的科目。
  4. 第 n+2 行输入用作排名的科目名称。如果科目不存在,则按总分进行排序。

输出描述

输出一行,按成绩排序后的学生名字,用空格隔开。如果成绩相同,则按学生姓名的字典顺序排序。

示例

华为OD机试 - 智能成绩表( Python & C & C++ & Java&Go & JS & PHP)_第1张图片

题目解析

本题的核心在于动态排序规则的应用。排序规则可能基于特定科目的成绩,也可能基于总分。排序过程需要考虑两个因素:

  1. 排序规则:根据最后一行输入的科目名称确定。如果科目存在,则按该科目成绩排序;如果不存在,则按总分排序。

  2. 排序细节:在成绩相同的情况下,需要按学生姓名的字典顺序进行排序。

C++代码实现

#include 
#include 
#include 
#include 

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>() {
            @Override
            public 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 List

class 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 = -1
        for i, subject in enumerate(subjects):
            if subject == sort_subject:
                sort_index = i
                break
        students.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 
#include 
#include 

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 main

import (
	"fmt"
	"io"
	"strings"
	"sort"
)

// 学生信息结构体
type Student struct {
	name  string
	scores []int
	totalScore 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.Reader
	reader = os.Stdin

	var n, m int
	fmt.Fscanf(reader, "%d %d", &n, &m)

	var subjects []string
	for i := 0; i < m; i++ {
		var subject string
		fmt.Fscanf(reader, "%s", &subject)
		subjects = append(subjects, subject)
	}

	students := make([]Student, n)
	for i := 0; i < n; i++ {
		var name string
		fmt.Fscanf(reader, "%s", &name)
		students[i].name = name
		students[i].scores = make([]int, m)
		students[i].totalScore = 0
		for j := 0; j < m; j++ {
			fmt.Fscanf(reader, "%d", &students[i].scores[j])
			students[i].totalScore += students[i].scores[j]
		}
	}

	var sortSubject string
	fmt.Fscanf(reader, "%s", &sortSubject)

	// 确定排序索引,如果科目不存在,则索引为-1,表示按总分排序
	sortIndex := -1
	for i, subject := range subjects {
		if subject == sortSubject {
			sortIndex = i
			break
		}
	}

	// 根据排序索引进行排序
	sort.Slice(students, func(i, j int) bool {
		return compareStudents(students[i], students[j], sortIndex)
	})

	// 输出排序后的学生名字
	for _, student := range students {
		fmt.Println(student.name)
	}
}

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);
});

你可能感兴趣的:(华为od,python,c语言,c++,java,面经,秋招)