nth_element用法
生活随笔
收集整理的這篇文章主要介紹了
nth_element用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
引言
今天在做acwing時看到一個不用排序找中位數的實現方法,便是nth_element,于是找到oj第k小數(不是主席樹)用了一下,感覺很有用,即使數據加強過也能過。
介紹
nth_element(first,你要的有序的第幾個數,end);
舉個栗子:
第k小的數(數據加強版)
Description
現有一個包含n個整數(1<=n<=20000000)的無序序列(保證序列內元素各不相同),輸入一個整數k(1<=k<=n),請用較快的方式找出該序列的第k小數并輸出。
Input
多組輸入。(代表輸入只有一個T)
首先輸入一個數據組數T(1<=T<=100)
接下來是T組數據。
每組數據有兩行。
第一行先輸入兩個整數,n和k。
接下來是一行輸入n個由空格分開的互不相同的整數num(1<=num<=90000000)。
Output
對于每組數據,輸出該組數據中第k小的數num。
Sample
Input?
1 6 4 3 2 5 1 4 6Output?
4 #include <iostream> #include <cstring> #include <cstdio> #include <cmath> #include <cstdlib> #include <algorithm> #include <set> #include <map> #include <vector> #include <queue> #include <stack> #define ll long long using namespace std; const int inf = 0x3f3f3f3f; int n,m,t,k,a[20000009]; void solve(){while(~scanf("%d",&t)){scanf("%d%d",&n,&k);for(int i=1;i<=n;++i)scanf("%d",&a[i]);nth_element(a+1,a+k,a+1+n);//你需要的第k小數printf("%d\n",a[k]);} } int main() { //printf("%lld\n",1<<21);solve();return 0; }以后忘了就來這看一下= =
總結
以上是生活随笔為你收集整理的nth_element用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js实现倒计时,定时器--完成时间倒计时
- 下一篇: 甲骨文公司