60、80分求助!

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

lby_commandBlock @ 2023-01-05 16:05:10

我买了《深入浅出程序设计竞赛》,今天来做第八章的所有题目。

我发现,这道题我用了两种排序方法都还是没有通过!你们看看怎么办?

代码:

(1)

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

int a[100000001];
void s(int l, int r)
{
    int i, j, mid, temp;
    i = l;
    j = r;
    mid = a[(l + r) / 2];
    while (i <= j)
    {
        while (a[i] < mid) i++;
        while (a[j] > mid) j--;
        if (i <= j)
        {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i++;
            j--;
        }
    }
    if (l < j) s(l, j);
    if (i < r) s(i, r);
}
int main()
{
    int n, k;
    cin >> n >> k;
    for (int i = 0; i <= n; i++)
        cin >> a[i];
    s(0, n - 1);
    cout << a[k];
    return 0;
}

(2)

#include<bits/stdc++.h>
using namespace std;
int n, a[10000005], r[10000005], k;
//long long ans = 0;
void msort(int s, int t)
{
    if(s>=t)return;
    int mid = (s + t) / 2;
    msort(s, mid); msort(mid + 1, t);
    int i = s, j = mid + 1, k = s;
    while(i<=mid && j<=t){
        if(a[i]<=a[j])
            r[k++] = a[i++];
        else{
            r[k++] = a[j++];
//          ans += mid - i + 1;
        }
    }
    while(i <= mid) r[k++] = a[i++];
    while(j <= t) r[k++] = a[j++];
    for(int i = s; i <= t; i++)a[i]=r[i];
}

int main()
{
    scanf("%d %d",&n,&k);
    for(int i = 0; i < n; i++)scanf("%d",&a[i]);
    msort(0,n-1);
//  printf("%lld",ans);
    printf("%d",a[k]);
    return 0;
}

请问,为什么总是得不了满分???

(个人首页)


by Yuzilihhh @ 2023-01-05 16:14:00

nth_element写呗


by Yuzilihhh @ 2023-01-05 16:26:33

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

|