60分求助,后两个点TLE,用的nth_element,T—T。

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

Limul @ 2021-02-19 20:44:48

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

哪位大神能告诉我这个萌新TLE是什么错误(狗头保命)


by xtracer @ 2021-02-19 20:59:14

@wxr13956463677 用scanfprintf,保证通过


by KarL05 @ 2021-02-19 22:10:34

ios::syncwithstdio


by metaphysis @ 2021-02-20 09:05:13

@wxr13956463677

主要是输入量较大导致超时。您用C++的话,可以将输入流与输出流解绑定,同时取消C++的流同步,可以提高输入的效率。如果需要更高的输入效率,可以考虑使用缓存区技巧。


by metaphysis @ 2021-02-20 09:05:42

#include<bits/stdc++.h>
using namespace std;
long long n,x,a[5000010];
int main()
{
    cin.tie(0), cout.tie(0), ios::sync_with_stdio(false);
    cin>>n>>x;
    for(int i=0;i<n;i++)
        cin>>a[i];
    nth_element(a,a+x,a+n);
    cout<<a[x];
}

by metaphysis @ 2021-02-20 09:07:42

利用缓存区提高输入效率的代码片段:

const int LENGTH = (1 << 20);

inline int nextChar()
{
    static char buffer[LENGTH], *p = buffer, *end = buffer;
    if (p == end) {
        if ((end = buffer + fread(buffer, 1, LENGTH, stdin)) == buffer) return EOF;
        p = buffer;
    }
    return *p++;
}

inline bool nextInt(int &x)
{
    static char negative = 0, c = nextChar();
    negative = 0, x = 0;
    while ((c < '0' || c > '9') && c != '-')
    { if (c == EOF) return false; c = nextChar(); }
    if (c == '-') { negative = 1; c = nextChar(); }
    do x = (x << 3) + (x << 1) + c - '0'; while ((c = nextChar()) >= '0');
    if (negative) x = -x;
    return true;
}

int main(int argc, char *argv[])
{
    int n;
   nextInt(n);
   char c;
   c = nextChar();
   return 0;
}

by Limul @ 2021-02-20 15:15:44

@metaphysis 谢谢大神指点。


by int233 @ 2021-04-18 19:54:53

#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<string>
using namespace std;
int main(){
    ios::sync_with_stdio(0);
    int n,k;
    cin>>n>>k;
    int a[n];
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    nth_element(a,a+k,a+n);
    cout<<a[k];
    return 0;
} 

要写:ios::sync_with_stdio(0);


|