【题目链接】
ybt 1176:谁考了第k名
OpenJudge NOI 1.10 01:谁考了第k名
【题目考点】
1. 结构体 排序
2. printf %g输出
为简洁输出,如果输出的数字有小于等于6位有效数字,则直接输出,没有小数点末尾的0。如果有效数字多于6位,则以科学计数法形式输出。
直接cout输出浮点型量,即为以printf("%g")形式输出浮点型量
double a;
cin >> a;
cout << a << endl;
printf("%g", a);//两种输出的效果完全一样
【解题思路】
结构体对象排序时,比较的是对象的成员变量,交换的是对象整体。
该题为降序排序。
【题解代码】
解法1:冒泡排序
#include<bits/stdc++.h>
using namespace std;
struct Stu//学生类
{
int num;//学号
double score;//分数
};
int main()
{
int n, k;
Stu stu[105];
cin >> n >> k;
for(int i = 1; i <= n; ++i)
cin >> stu[i].num >> stu[i].score;
for(int i = 1; i <= n-1; ++i)//冒泡排序
for(int j = 1; j <= n-i; ++j)
if(stu[j].score < stu[j+1].score)
swap(stu[j], stu[j+1]);
cout << stu[k].num << ' ' << stu[k].score;
return 0;
}
解法2:插入排序
#include<bits/stdc++.h>
using namespace std;
struct Stu//学生类
{
int num;//学号
double score;//分数
};
int main()
{
int n, k;
Stu stu[105];
cin >> n >> k;
for(int i = 1; i <= n; ++i)
{
cin >> stu[i].num >> stu[i].score;
for(int j = i; j > 1; j--)
{
if(stu[j].score > stu[j-1].score)
swap(stu[j], stu[j-1]);
else
break;
}
}
cout << stu[k].num << ' ' << stu[k].score;
return 0;
}
解法3:使用STL sort函数
- 使用数组,重载小于号运算符
#include<bits/stdc++.h>
using namespace std;
struct Stu//学生类
{
int num;//学号
double score;//分数
bool operator < (const Stu &b) const
{
return score > b.score;
}
};
int main()
{
int n, k;
Stu stu[105];
cin >> n >> k;
for(int i = 1; i <= n; ++i)
cin >> stu[i].num >> stu[i].score;
sort(stu+1, stu+1+n);
cout << stu[k].num << ' ' << stu[k].score;
return 0;
}
- 使用vector,写比较函数
#include<bits/stdc++.h>
using namespace std;
struct Stu//学生类
{
int num;//学号
double score;//分数
};
bool cmp(Stu a, Stu b)
{
return a.score > b.score;
}
int main()
{
int n, k;
vector<Stu> stu;
Stu a;
cin >> n >> k;
for(int i = 1; i <= n; ++i)
{
cin >> a.num >> a.score;
stu.push_back(a);
}
sort(stu.begin(), stu.end(), cmp);
cout << stu[k-1].num << ' ' << stu[k-1].score;//vector下标从0开始
return 0;
}