东方博宜OJ 2262:谁考了第k名 ← 结构体 + 结构体排序

​【题目来源】
https://oj.czos.cn/p/2262

【题目描述】
在一次考试中,每个学生的成绩都不相同,现知道了每个学生的学号和成绩,求考第 k 名学生的学号和成绩。

【输入格式】
第一行有两个整数,分别是学生的人数 n(1≤n≤100),和求第 k 名学生的 k(1≤k≤n)。
其后有 n 行数据,每行包括一个学号(整数)和一个成绩(浮点数),中间用一个空格分隔。

【输出格式】
输出第 k 名学生的学号和成绩,中间用空格分隔。

【输入样例】
5 3
90788001 67.8
90788002 90.3
90788003 61
90788004 68.4
90788005 73.9​​​​​​​

【输出样例】
90788004 68.4

【数据范围】
1≤n≤100,
1≤k≤n。

【算法分析】
本题的坑点在于输出:有的含一位小数,有的是整数。

if(stu[k].score-(int)stu[k].score<1e-6) {
    cout<<(int)stu[k].score;
} else printf("%.1lf",stu[k].score);

所以,需要利用上述代码特判。

【算法代码】

#include <bits/stdc++.h>
using namespace std;

const int maxn=105;
struct Student {
    int idx;
    float score;
} stu[maxn];

bool cmp(Student a,Student b) {
    return a.score>b.score;
}

int main() {
    int n,k;
    cin>>n>>k;
    for(int i=1; i<=n; i++) {
        cin>>stu[i].idx>>stu[i].score;
    }
    sort(stu+1,stu+1+n,cmp);

    cout<<stu[k].idx<<" ";
    if(stu[k].score-(int)stu[k].score<1e-6) {
        cout<<(int)stu[k].score;
    } else printf("%.1lf",stu[k].score);

    return 0;
}

/*
in:
5 3
90788001 67.8
90788002 90.3
90788003 61
90788004 68.4
90788005 73.9

out:
90788004 68.4
*/





【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/156489323
https://blog.csdn.net/hnjzsyjyj/article/details/156488957
https://blog.csdn.net/hnjzsyjyj/article/details/156479934
https://blog.csdn.net/hnjzsyjyj/article/details/156466035

 

​

posted @ 2026-01-05 18:44  Triwa  阅读(77)  评论(0)    收藏  举报