80tps求助

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

jianghaochen117 @ 2024-10-14 19:39:41

我用的归并排序,结果超时了

#include <bits/stdc++.h>
using namespace std;
const int N = 5e6 + 10;
int n , mid , a[N] , tmp[N];
void merge(int left , int mid , int right)
{
    int i = left , j = mid + 1 , k = left;
    while(i <= mid && j <= right)
    {
        if(a[i] <= a[j])
        {
            tmp[k] = a[i];
            i++;
            k++;
        }
        else
        {
            tmp[k] = a[j];
            j++;
            k++;
        }
    }
    while(i <= mid)
    {
        tmp[k++] = a[i++];
    }
    while(j <= right)
    {
        tmp[k++] = a[j++];
    }
    for(int i = left;i <= right;i++)
    {
        a[i] = tmp[i];
    }
}
void merge_(int left,int right){
    if (left >= right)
    {
        return;
    }
    int mid = (left + right) >> 1;
    merge_(left , mid);
    merge_(mid + 1 , right);
    merge(left , mid , right);
}
int main()
{
    int n , k;
    scanf("%d%d" , &n , &k);
    for(int i = 1;i <= n;i++)
    {
        scanf("%d" , &a[i]);
    }
    merge_(1 , n);
    printf("%d" , tmp[k + 1]);
    return 0;
}

by _Regenbogen_ @ 2024-10-14 20:01:39

nlogn 过不了 @jianghaochen117


by jianghaochen117 @ 2024-10-15 17:20:44

感谢大佬


by jianghaochen117 @ 2024-10-15 17:26:57

我用二分再试试


by niuniudundun @ 2024-10-19 14:19:15

@jianghaochen117

可以试试自带 `sort` 能过。 ```cpp #include<iostream> #include<algorithm> using namespace std; int n,k; int a[5000001]; int main(){ scanf("%d %d",&n,&k); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); } sort(a+1,a+n+1); printf("%d\n",a[k+1]); return 0; } ```

by jianghaochen117 @ 2024-10-19 14:30:18

感谢大佬们的帮助


by jianghaochen117 @ 2024-10-19 14:30:54

我已通过


|