OpenJudge-1.10.01:谁考了第k名

一、题目链接

http://noi.openjudge.cn/ch0110/01/

二、解题思路(Java)

三、解题思路(C++)

四、Java程序

import java.util.Arrays;
import java.util.Scanner;

class Student implements Comparable<Student> { // 学生信息类,实现Comparable接口
    int id; // 标记学号
    double score; // 标记成绩

    // 构造方法,用于初始化一个学生对象
    public Student(int id, double score) {
        this.id = id;
        this.score = score;
    }

    /* 重写Comparable接口的compareTo方法,实现按照成绩降序排序的规则 */
    @Override
    public int compareTo(Student o) {
        if (o.score == this.score) {
            return 0;
        }
        return o.score > this.score ? 1 : -1;
    }

    /* 重写Object类的toString方法,实现按照题目要求的输出格式 */
    @Override
    public String toString() {
        return id + String.format(" %.1f", score);
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        int k = input.nextInt();
        Student[] students = new Student[n];
        int id;
        double score;
        for (int i = 0; i < n; i++) {
            id = input.nextInt();
            score = input.nextDouble();
            students[i] = new Student(id, score);
        }
        Arrays.sort(students); // 调用Arrays类的sort方法实现对students数组的排序
        System.out.print(students[k - 1].toString()); // 第k名的下标为k - 1
    }
}

五、C++程序

#include <iostream>
#include <algorithm>
using namespace std;

struct student // 定义student结构体,用于描述学生信息
{
    int id; // 标记学号
    double score; // 标记成绩
};

int compare(student x, student y) // 排序规则
{
    return x.score > y.score; // 按照score属性从大到小降序排列
}

int main()
{
    int n; // 学生人数
    int k;
    cin >> n;
    cin >> k;
    student stu[n]; // 结构体数组,存储所有的学生信息
    for (int i = 0; i < n; i++)
    {
        cin >> stu[i].id;
        cin >> stu[i].score;
    }
    sort(stu, stu + n, compare); // 对stu数组进行自定义规则的排序
    printf("%d %.1f", stu[k - 1].id, stu[k - 1].score); // 第k名的下标为k - 1
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江苏科技大学_计算机学院_潘磊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值