今日学到的小知识点:

1.快读:当用cin和scanf都不能满足要求的读入速度时,可以用getchar手写一个快读函数

C++代码:

inline int read() {
	int flag = 1;//判断符号位
	int res = 0;
	char ch= getchar();
	while (ch < '0' || ch>'9') {//若不为数字,则判断符号
		if (ch == '-')//若为负数,符号位变成-1;
			flag = -1;
		ch = getchar();
	}
	while (ch >= '0' && ch<='9') {
		res = res * 10 + ch - '0';//读入一位之后移位
		//res = (res << 1) + (res << 3) + (ch ^ 48);
		ch = getchar();
	}
	return res * flag;//最后返回读入的数
}

快读的使用:

n = read();
k = read();
for (ll i = 1; i <= n; i++) {
	A[i] = read();
}

2.nth_element()函数:将数组中第K小的数排出来,nth_element(数组名,数组名+K,数组大小);

需要的头文件:#include<algorithm>

测试代码:(快读是上面的知识点)

#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>

typedef long long ll;
const int N = 5000000+5;
using namespace std;

inline int read() {
	int flag = 1;//判断符号位
	int res = 0;
	char ch= getchar();
	while (ch < '0' || ch>'9') {//若不为数字,则判断符号
		if (ch == '-')//若为负数,符号位变成-1;
			flag = -1;
		ch = getchar();
	}
	while (ch >= '0' && ch<='9') {
		res = res * 10 + ch - '0';//读入一位之后移位
		//res = (res << 1) + (res << 3) + (ch ^ 48);
		ch = getchar();
	}
	return res * flag;//最后返回读入的数
}
ll A[N];
int main() {
	ll n,k;
	n = read();
	cout << "输出查询第几位小的数字"<<endl;
	k = read();
	for (ll i = 1; i <= n; i++) {
		A[i] = read();
	}
	nth_element(A+1, A + k+1, A +1+ n);
	cout << "输出第k小的数字" << endl;
	cout << A[k]<<endl;
	cout << "输出排序后的数字" << endl;
	for (int i = 1; i <= n; i++) {
		cout << A[i]<<' ';
	}	
	return 0;
}

输出结果:

  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值