Fast Input/Output

Can Anyone explain how to use fast input/output methods in c++ very large input and output values…??

Most of the source codes are open in Codechef.

1 Like

Most of the methods mainly rely on the fact that reading in blocks from the disk is cheaper. This is because you avoid a lot of seek time which IO does. Hence firstly, read from the disk in blocks.
After getting characters in bytes you can use simple translations into numbers etc. The standard libraries do lot of error checking which can be avoided in our case because we know that the judge would not feed in arbitrary inputs.
Finally you can also use use getchar_unlocked functions. The IO has to lock mutex etc so as to prevent simultaneous reads from different threads. This can be avoided as there is only a single thread.

Here is some code,

#define BUF 4096 // block size on my disk is 4KBs
char ibuf[BUF];
int ipt = BUF;
int read_uint() {
while (ipt < BUF && ibuf[ipt] < '0') ipt++;
if (ipt == BUF) {
    fread(ibuf, 1, BUF, stdin);
    ipt = 0;
    while (ipt < BUF && ibuf[ipt] < '0') ipt++;
}
int n = 0;
while (ipt < BUF && ibuf[ipt] >= '0') n = (n*10)+(ibuf[ipt++]-'0');
if (ipt == BUF) {
    fread(ibuf, 1, BUF, stdin);
    ipt = 0;
    while (ipt < BUF && ibuf[ipt] >= '0') n = (n*10)+(ibuf[ipt++]-'0');
}
return n;
}

The same points are valid for output too.

7 Likes

Thanks bro…!!

But with this code,the input function doesn’t end after enter

kriateive said all that was needed perfectly…

However, as far as I have seen… When they warn us, contestants to use fast I/O methods in C++, it’s usually a matter of replacing cin/cout with scanf and printf…

Note however, that this is only valid for some problems… As a well-designed algorithm can pass all time limits even with cin/cout…

Bruno

2 Likes

supply the input from a file. As I said it tries to buffer all the input so it wont take the input till it gets a end of file character. type your input to a file and run as
./a.out < input_file_name
Any how if you are typing on terminal after all the input is over press ctrl+D.
In anycase, on the judge input is supplied through file and wont be a problem.

1 Like