Ronzii's Blog

Just your average geek's blog

Fast Input SPOJ

Recently, I have gotten into solving problems in SPOJ. Here is a snippet, I often use to get fast input. This has helped me get AC in several problems that I was previously getting time limit exceeded.

#include <iostream>
#include <cstdio>
namespace IO
{
const int SIZE = 1 << 19;
char buff[SIZE], *p = buff + SIZE;

char read_char()
{
    if( p == buff + SIZE )
    {
        fread( buff, 1, SIZE, stdin );
        p = buff;
    }
    return *(p++);
}

inline int read_int()
{
    char c;

    while( !isdigit( c = read_char() ) );

    int r = c-'0';
    while( isdigit( c = read_char() ) ) r = 10*r + c - '0';

    return r;
}
}
using namespace IO;
using namespace std;

int main()
{
    int t;
    t = read_int();
    cout<<t;
    return 0;
}

Advertisements

July 7, 2011 - Posted by | C++ | , ,

3 Comments »

  1. You can make read_char() as inline function to have better performance.

    Comment by Aamir Khan | November 1, 2011 | Reply

    • Hi,
      Nice! I think it is worth to use a slightly heavier version
      in which one can handle EOF:
      bool read_char( char& c )
      {
      if( p == buff + SIZE )
      {
      if( ! fread( buff, 1, SIZE, stdin ) )
      {
      c = -1 ; return false ;
      }
      p = buff;
      }
      c = *(p++);
      return true ;
      }
      Of course functions depending on read_char must be rewrited.
      ncs

      Comment by asa czylabson | December 13, 2011 | Reply

  2. I have started coding on SPOJ. After a few simple ones, now i get runtime exceeded for most of them. How would i know what to do for each problem to optimise it ? Should i follow an order while solving spoj problems?…

    The issue might be with your algorithm time complexity. But what I experienced on SPOJ was that a lot of questions required Input-Output Optimization (like using printf-scanf in place of cout-cin in C++) for the solution to be within the stated time li…

    Trackback by Quora | July 16, 2012 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s