技巧——快读快写

快读

正数快读

inline int read()  
{
    int s=0;
    char c=getchar();
    while (c<'0' || c>'9') c=getchar();
    while (c>='0' && c<='9') s=s*10+c-'0',c=getchar();
    return s;
}

输入方式

int main()
{
    n=read(),x=read();
        ......
}

正负皆可的快读

template <typename T>
inline void read(T& x)
{
    char ch=getchar();
    bool sign=true;
    while(!isdigit(ch))
    {
        if(ch=='-')sign=false;
        ch=getchar();
    }
    for(x=0; isdigit(ch); ch=getchar())x=x*10+ch-'0';
    if(!sign)x=-x;
}

输入方式

int main()
{
    read(n),read(x);
        ......
}

 急速快读

inline char nc(){
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline int rd(){
    char ch=nc();int sum=0;
    while(!(ch>='0'&&ch<='9'))ch=nc();
    while(ch>='0'&&ch<='9')sum=sum*10+ch-48,ch=nc();
    return sum;
}

输入方式

int main()
{
    n=rd();
     ......
}

注:使用fread之后你的程序将不能手动输入数据,且与多个输入输出方式不兼容,所以除非为大数据,不建议使用

比较

下为普通getchar快读,上为fread快读

快写


代码

#define I_int int
char F[ 200 ] ;
inline void write( I_int x )
{
    I_int tmp = x > 0 ? x : -x ;
    if( x < 0 ) putchar( '-' ) ;
    int cnt = 0 ;
    while( tmp > 0 )
    {
        F[ cnt ++ ] = tmp % 10 + '0' ;
        tmp /= 10 ;
    }
    while( cnt > 0 ) putchar( F[ -- cnt ] ) ;
}
#undef I_int

输出方式

int main()
{
    ......
    write(n);
}
原文地址:https://www.cnblogs.com/CXYscxy/p/11164953.html