悬赏关注x1,救救孩子!

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

oldsix_2 @ 2023-04-09 16:45:13

sort为什么会超时?!

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

by luogudoudou @ 2023-04-09 16:58:02


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

虽然不符合题意(不能用nth_element),但是可以AC

by lzyqwq @ 2023-04-09 16:58:05

@oldsix_2 在输入前加入:

cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);

by Pengzt @ 2023-04-09 16:59:23

@oldsix_2

读入 n, kscanf("%d%d", &n, &k);

读入数组 \{a\}

for (int i = 1; i <= n; i++)
    scanf("%d", &a[i]);

by oldsix_2 @ 2023-04-09 17:02:32

@yizhiming 蒟蒻真的很菜不要这么暴力QAQ


by oldsix_2 @ 2023-04-09 17:04:13

#include<iostream>
#include<cstdio>
using namespace std;
int a[11451400],n,k;
int main(){
    cin>>n>>k;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    //sort(a,a+n);
    nth_element(a,a+k,a+n);
    cout<<a[k];
    return 0;
}

@luogudoudou 这样行吗


by diandian2020 @ 2023-04-09 17:06:04

@oldsix_2 可以,但是nth_elementinclude<algorithm>


by oldsix_2 @ 2023-04-09 17:07:15

@diandian2020 还是TLE QAQ


by ___Yang__ @ 2023-04-09 17:10:11

@oldsix_2

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
long long a[11451400],n,k;
int main(){
    scanf("%d%d",&n,&k); 
    for(int i=0;i<n;i++){
        scanf("%d",&a[i]); 
    }
    nth_element(a,a+k,a+n);
    printf("%d",a[k]);
    return 0;
}

这样就可以AC,你可以学习一下printf与scanf


by oldsix_2 @ 2023-04-09 17:10:32

@蒟蒻·廖子阳

看不懂++;

by ___Yang__ @ 2023-04-09 17:12:35

@oldsix_2 那是关闭cin与scanf之间的同步,使cin的读入的速度更快


上一页 | 下一页