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;
}
输出结果: