输入输出优化

输入输出优化:

最近遇到一个题,照我的思路差100ms才能过,于是想尽一切办法做微小优化试图卡过去,最后虽然过去了,但要是会优化输入就更好了,于是学习一下这个模板备用

以下模板,具体讲解参考参考文章

代码:

#include <iostream>
#include <cctype>
void read(int& x)//普通版
{
    int f = 1;
    x = 0;
    char s = getchar();
    while(s<'0'||s>'9')
    {
        if(s=='-')
        {
            f = -1;
        }
        s = getchar();
    }
    while(s>='0'&&s<='9')
    {
        x=x*10+s-'0';
        s = getchar();
    }
    x = x*f;
}
void read_1(int& x)//简洁版
{
    int f = 1;x = 0;char s = getchar();
    while(s<'0'||s>'9'){if(s=='-1')f=-1;s=getchar();}
    while(s>='0'||s<='9'){x=x*10+s-'0';s=getchar();}
    x*=f;
}
void read_2(int& x)//紧凑版
{
    char ch;bool flag = 0;
    while(!isdigit(ch=getchar()))
        (ch=='-')&&(flag=true);
    for(x=ch-'0';isdigit(ch=getchar());x=x*10+ch-'0');
    (flag)&&(x=-x);
}
inline int read_3()//整数输入模板
{
    int X=0,w=0; char ch=0;
    while(!isdigit(ch)) {w|=ch=='-';ch=getchar();}
    while(isdigit(ch)) X=(X<<3)+(X<<1)+(ch^48),ch=getchar();
    return w?-X:X;
}
inline double dbread()//实数输入模板
{
    double X=0,Y=1.0; int w=0; char ch=0;
    while(!isdigit(ch)) {w|=ch=='-';ch=getchar();}
    while(isdigit(ch)) X=X*10+(ch^48),ch=getchar();
    ch=getchar();//¶ÁÈëСÊýµã
    while(isdigit(ch)) X+=(Y/=10)*(ch^48),ch=getchar();
    return w?-X:X;
}
void print(int x)//输出优化
{
    if(x<0)
    {
        putchar('-');
        x=-x;
    }
    if(x>9)
    {
        print(x/10);
    }
    putchar(x%10+'0');
}
int main()
{
    return 0;
}

参考文章:

Felix-Lee,C++ 读入优化与输出优化 模板,https://blog.csdn.net/liyizhixl/article/details/54412459

∞∑,读入优化&输出优化,https://blog.csdn.net/C20190102/article/details/69710341

原文地址:https://www.cnblogs.com/zhanhonhao/p/11274834.html