(STL)nth_element

· · 个人记录

nth_element是stl中自带的一个函数。

它可以在不需排序的条件下,快速地访问第k小的值,时间复杂度是线性的。

有的时候非常方便。

使用(数组的下标从0开始):

nth_element(a,a+k,a+n)

函数把下标为k的元素放在了正确位置,对其它元素并没有排序,同时使得k左边元素都小于等于它,右边元素都大于等于它。

这样我们只需访问a[k]就能得到想要的元素。

应用:

求区间第k小值:P1923 【深基9.例4】求第 k 小的数

code:
#include<bits/stdc++.h>
//#define int long long
#define reg register
using namespace std;
const int maxn=5e6+5;
const int mod=1e9+7;
const int INF=2e9;
inline int read()
{
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0' || ch>'9')
    {
        if(ch=='-')
        f=-1;
        ch=getchar();
    }
    while(ch>='0' && ch<='9')
    {
        x=x*10+ch-'0';
        ch=getchar();
    }
    return x*f;
}
int a[maxn];
int n,k;
signed main()
{
    n=read(),k=read();
    for(int i=0;i<n;i++)
    a[i]=read();
    nth_element(a,a+k,a+n);
    printf("%d\n",a[k]);
    return 0;
}
/*
10 4
5 4 3 4 2 2 3 2 6 1 7 
*/