60分求救!!!

P1923 【深基9.例4】求第 k 小的数

midsummer_zyl @ 2023-07-05 21:20:15

大佬帮帮忙,谢谢!

#include <bits/stdc++.h>
using namespace std;
long long a[100000005];
int main() {
    long long n, k, i;
    cin >> n >> k;
    for (i = 0; i < n; i++)
        cin >> a[i];
    sort(a, a + n, less<int>());
    cout << a[k];
    return 0;
}

by Humble_oath @ 2023-07-05 21:25:58

这题是卡暴力的,题目里说了但是可以用 STL 里的 nth_element 做


by midsummer_zyl @ 2023-07-05 21:29:38

@Humble_oath

怎么用 STL 里的 nth_element 做题啊?


by Humble_oath @ 2023-07-05 21:31:35

for(int i=0;i<n;++i)
{
    scanf("%d",&a[i]);
}
nth_element(a,a+k,a+n);

然后直接输出 a_k 即可。

但是应该尽量别用


by duanxiaobing @ 2023-07-05 21:33:05

#include <bits/stdc++.h>
using namespace std;
int a[5000005];
int main() {
    int n, k, i;
    scanf("%d%d",&n,&k);
    for (i = 0; i < n; i++)
        scanf("%d",&a[i]);
    sort(a, a + n);
    printf("%d",a[k]);
}

AC代码(要开O2)


by midsummer_zyl @ 2023-07-06 17:51:31

@Humble_oath

#include <bits/stdc++.h>
using namespace std;
int a[1000005];
int main() {
    int n, k, i;
    scanf("%d%d", &n, &k);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);
    nth_element(a, a + k, a + n);
    printf("%d", a[k]);
    return 0;
}

为啥还是60分呢?


by 123456zzr @ 2023-07-08 15:31:02

@midsummer_zyl 数组要开到5000001


by midsummer_zyl @ 2023-07-08 17:18:03

@123456zzr

ok!


|