全网首发 Python3 实现快读(按字符读入(省内存专用

发布时间 2023-11-03 22:46:16作者: RainPPR

全网首发 Python3 实现快读(按字符读入(省内存专用

来源:https://www.luogu.com.cn/discuss/724761

此题卡内存,如果按照 Python 常用的 input().split() 方法会 MLE。

因为 input() 一次读入大量字符串,占用内存极大。

于是打算按照 C++ 的快读逻辑写一个 Python3 的快读。

然而并没有那么简单。但是我也实现了,全网首发!

思路就是,利用 sys.stdin.read 的读入若干个字符功能,实现类似 C++ 的 getchar() 的功能,其余的与 C++ 类似啦。

from sys import stdin
def gc():
    return stdin.read(1)
def digit(c):
    if c == '':
        return False
    return ord(c) >= ord('0') and ord(c) <= ord('9')
def read():
    n, f, c = 0, 0, gc()
    while not digit(c):
        f, c = f | (c == '-'), gc()
    while digit(c):
        n, c = n * 10 + ord(c) - ord('0'), gc()
    if f:
        return -n;
    return n

如果您发现在此之前有人写出类似的程序,请私聊我(侵删。