60分求助,最后俩点TLE

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

sxms_tanjialei @ 2023-09-30 20:54:50

代码:

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

by gotocspandbetter @ 2023-09-30 20:57:46

sort会爆,要写快排


by gotocspandbetter @ 2023-09-30 20:58:34

@sxms_tanjialei

其实我也是60分


by ZackofZHOU @ 2023-09-30 21:04:17

答案 , 仅供参考!

#include<stdio.h>
#include<algorithm>
using namespace std;
int a[5000010],n,k;
void qsort(int l,int r)
{
    int i = l,j=r,mid=a[(l+r)/2];
    do
    {
        while(a[j]>mid)
            j--;
        while(a[i]<mid)
            i++;
        if(i<=j)
        {
            swap(a[i],a[j]);
            i++;
            j--;
        }
    }
    while(i<=j);
    if(k<=j)
        qsort(l,j);
    else if(i<=k)
        qsort(i,r);
    else
    {
        printf("%d",a[j + 1]);
        return;
    }
}
int main()
{
    scanf("%d %d",&n,&k);
    for(int i = 0;i < n;i++)
        scanf("%d",&a[i]);
    qsort(0,n - 1);
    return 0;
}

by Beacon_wolf @ 2023-09-30 23:05:16

@sxms_tanjialei O2优化是个好东西


by sxms_tanjialei @ 2023-10-01 15:39:51

@fire_wolf O2开了还是过不去的


by Beacon_wolf @ 2023-10-01 15:44:39

@sxms_tanjialei ?但是我过了


by sxms_tanjialei @ 2023-10-01 18:46:37

@fire_wolf 啊?


by Ssim_on_wxs @ 2023-10-05 23:32:43

@sxms_tanjialei

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

AC源码(需要开O2,不然会TLE)


by sxms_tanjialei @ 2023-10-06 19:08:23

@Ssim_on_wxs 大佬,scanf是比cin快吗?


by sxms_tanjialei @ 2023-10-06 19:24:31

我用scanf就过了,cin过不了


| 下一页