求助为什么用scanf时最后两个不会tle,而快排次cincout tle了

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

TGXZZ @ 2024-03-30 20:00:51

#include <cstdio>
#include <algorithm>

const int N = 5e6 + 10;
int q[N];
void quick_sort(int q[], long long l, long long r)
{
    if (l >= r) return;
    int i = l - 1, j = r + 1, x = q[l + r >> 1];
    while(i < j)
    {
        do i ++; while(q[i] < x);
        do j --; while(q[j] > x);
        if (i < j){
            int c = q[i];
                q[i] = q[j];
                q[j] = c;
        }
    }
    quick_sort(q, l, j);
    quick_sort(q, j + 1, r);
}
int main()
{
    long long n, m;
    scanf("%lld %lld", &n, &m);

    for (long long i = 0; i < n; i ++) scanf("%lld", &q[i]);

    quick_sort(q, 0, n - 1);

    printf("%lld ", q[m]);

    return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 5e6 + 10;
int q[N];
void quick_sort(int q[], long long l, long long r)
{
    if (l >= r) return ;
    int i = l - 1, j = r + 1, x = q[l + r >> 1];
    while(i < j)
    {
        do i ++; while(q[i] < x);
        do j --; while(q[j] > x);
        if (i < j) swap(q[i], q[j]);
    }
    quick_sort(q, l, j);
    quick_sort(q, j + 1, r);
}
int main()
{
    long long n, m;
    cin >> n >> m;

    for (long long i = 0; i < n; i ++) cin >> q[i];

    quick_sort(q, 0, n - 1);

    cout << q[m] << '\n';

    return 0;
}

by kevinZ99 @ 2024-03-30 20:29:27

@TGXZZ

我觉得您应该知道不加速的 cinscanf 慢吧 , 请您加上 ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);


by gloomy_ @ 2024-03-30 20:52:10

scanf和printf比cin cout快得多

const int N = 5e6 + 10;

范围这么大的情况下,算法主体部分已经花了很长时间了。要让非主体部分的运行速度尽量最快,才不会超时


by TGXZZ @ 2024-04-01 20:33:02

@TGXZZ 已解决 谢谢佬们


|