为什么全部tle

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

laowangwaimaidian @ 2024-12-13 17:40:49

#include <stdio.h>

int Partition(int a[],int low,int high){
    a[0]=a[low];
    while(low<high){
        while(low<high&&a[high]>a[0]) high--;
        a[low]=a[high];
        while(low<high&&a[low]<a[0]) low++;
        a[high]=a[low];
    }
    a[low]=a[0];
    return low;
}

void Qsort(int a[],int low,int high){
    if(low<high){
        int pivotloc=Partition(a,low,high);
        Qsort(a,pivotloc+1,high);
        Qsort(a,low,pivotloc-1);
    }
}
int main(){
    int n,m;
    scanf("%d %d",&n,&m);
    int a[5000005];
    int i;
    for(i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    Qsort(a,1,n);
    printf("%d",a[m+1]);
    return 0;
}

by niuniudundun @ 2024-12-13 18:53:52

@laowangwaimaidian试试自带的排序函数 sort


by zhaoyonghao @ 2024-12-15 15:40:47

@laowangwaimaidian 收写sort尽量用左闭右开的写法

#include <bits/stdc++.h>
using namespace std;

int x[5000005], k;

void qsort(int l, int r)
{
    int i = l, j = r, mid = x[(l + r) / 2];
    do
    {
        while (x[j] > mid)
            j--;
        while (x[i] < mid)
            i++;
        if (i <= j)
        {
            swap(x[i], x[j]);
            i++;
            j--;
        }
    }
    while (i <= j);
    if (k <= j) qsort(l, j);
    else if (i <= k) qsort(i, r);
    else
    {
        cout << x[j + 1] << "\n";
        exit(0);
    }
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n;
    cin >> n >> k;
    for(int i = 0; i < n; i++)
        cin >> x[i];
    qsort(0, n - 1);
}

by zhaoyonghao @ 2024-12-15 15:42:07

当然,自带的排序函数sort也很好用

#include <bits/stdc++.h>
#define int long long
using namespace std;

int a[5000005];

signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n, k;
    cin >> n >> k;
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    sort(a + 1, a + n + 1);
    cout << a[k + 1] << "\n";
}

by zhaoyonghao @ 2024-12-15 15:42:40

记得开long long


|