信息学奥赛一本通 1176:谁考了第k名 | OpenJudge NOI 1.10 01:谁考了第k名

【题目链接】

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;
}
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值