一个关于快读快写的问题

P1908 逆序对

X_yugg123 @ 2023-07-10 16:18:03

这个题中,为什么使用快速快写代码读取输出数据会全部TLE,而使用正常的scanf、printf就正常AC了,难道是因为快读快写代码没有scanf、printf快吗? (快读快写代码是csdn某博客借鉴来的,实测可行×)

快读快写的代码:

#include<bits/stdc++.h>
using namespace std;
const int N = 5e5+10;
typedef long long ll;
ll a[N], b[N], ans;
ll read()
{
    ll x = 0, f = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9') if(ch == '-') f = -1, ch = getchar();
    while(ch > '0' && ch < '9') x = x * 10 + ch - '0', ch = getchar();
    return x * f;
}
void write(ll x)
{
    char F[200];
    ll tmp = x > 0 ? x : -x, cnt = 0;
    if(x < 0) putchar('-');
    while(tmp) F[cnt++] = tmp % 10 + '0', tmp /= 10;
    while(cnt) putchar(F[--cnt]);
}
void Merge(ll l, ll mid, ll r)
{
    ll i = l, j = mid + 1, t = 0;
    while(i <= mid && j <= r){
        if(a[i] > a[j]){
            b[t++] = a[j++];
            ans += mid - i + 1;
        }
        else b[t++] = a[i++];
    }
    while(i <= mid) b[t++] = a[i++];
    while(j <= r) b[t++] = a[j++];
    for(int i = 0; i < t; i++) a[l + i] = b[i];
}
void Mergesort(ll l, ll r)
{
    if(l < r){
        ll mid = (l + r) >> 1;
        Mergesort(l, mid);
        Mergesort(mid + 1, r);
        Merge(l, mid, r);
    }
}
int main()
{
    ll n = read();
    for(int i = 1; i <= n; i++) a[i] = read();
    Mergesort(1, n);
    write(ans);
    return 0; 
}

正常代码:

#include<bits/stdc++.h>
using namespace std;
const int N = 5e5+10;
typedef long long ll;
ll a[N], b[N], ans;
void Merge(ll l, ll mid, ll r)
{
    ll i = l, j = mid + 1, t = 0;
    while(i <= mid && j <= r){
        if(a[i] > a[j]){
            b[t++] = a[j++];
            ans += mid - i + 1;
        }
        else b[t++] = a[i++];
    }
    while(i <= mid) b[t++] = a[i++];
    while(j <= r) b[t++] = a[j++];
    for(int i = 0; i < t; i++) a[l + i] = b[i];
}
void Mergesort(ll l, ll r)
{
    if(l < r){
        ll mid = (l + r) >> 1;
        Mergesort(l, mid);
        Mergesort(mid + 1, r);
        Merge(l, mid, r);
    }
}
int main()
{
    ll n; scanf("%lld", &n);
    for(int i = 1; i <= n; i++) scanf("%lld", &a[i]);
    Mergesort(1, n);
    printf("%lld", ans);
    return 0; 
}

by OldDriverTree @ 2023-07-10 16:21:43

@X_yugg123 这快读不太对吧,第二个 while 应该是 ch>='0'&&ch<='9'


by Broken_Light @ 2023-07-10 16:22:20

你说有没有一种可能,你快读有问题

程序第10行……?


by Broken_Light @ 2023-07-10 16:23:52

楼上正确

目测第10行while (s < '0' || s > '9')后面的东西要加括号,不然好像一直打空格会炸


by X_yugg123 @ 2023-07-10 16:27:01

实测了一下,好像是这个问题,5555555555555


by X_yugg123 @ 2023-07-10 16:27:49

感谢各位大佬眼尖,小弟刚学快读快写代码,一不小心就写错了。。。。


|