Saturday, June 14, 2014

Fast I/O in C++

 
Most of the competitions require non negative numbers.
The following code works perfectly well for them 
 
#define LL long long int 
#define gc getchar_unlocked()  
inline void inp(LL &x) 
{
    register LL c = gc ;
    x = 0;
    for(; ((c<48 || c>57)); c = gc );
    for(; c>47 && c<58 ; c = gc )x = (x<<1) + (x<<3) + c - 48;
}
 
However, if negative numbers are also allowed, 
 
#define LL long long int 
#define gc getchar_unlocked()   
inline void inp(LL &x)
 {
    register LL c = gc , neg=0;
    x = 0;
    for(; ((c<48 || c>57) && c != '-'); c = gc );
    if(c=='-') {neg = 1;c = gc();}
    for(; c>47 && c<58 ; c = gc )x = (x<<1) + (x<<3) + c - 48;
    if(neg)x = -x;
} 
 
Note: Define your variable as "long long int" otherwise, this will show an error. 

For strings,

#define gc getchr_unlocked();
inline void inpl(char *str)
{
    register char c = 0;
    register int i = 0;
    while (c < 33)c = gc ;
    while (c != '\n') {
        str[i] = c;
        c = gc ;
        i = i + 1;
    }
    str[i] = '\0';
}

No comments:

Post a Comment