AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

读入输出优化

作者: 作者的头像   countryhope ,  2019-09-07 09:32:27 ,  所有人可见 ,  阅读 1119


3


1

读入优化:
原理是 getchar() 读入单个字符比读入整型要快(具体原理我也不懂);

inline int read()
{
    int x = 0 , w = 1;
    char ch = 0;
    while(ch<'0'||ch>'9')
    {
        if(ch=='-') w = -1;
        ch = getchar();
    }
    while(ch>='0'&&ch<='9')
    {
        x = (x<<1)+(x<<3)+(ch-'0');
        ch = getchar();
    }
    return x*w;
}

更为通用的读入优化,可以适用于各种类型的读入(其实也不常用);

template<typename T>
inline T read()
{
    T x = 0,w = 1;
    char ch = 0;
    while(ch<'0'||ch>'9')
    {
        if(ch=='-') w = -1;
        ch = getchar();
    }
    while(ch>='0'&&ch<='9')
    {
        x = (x<<1)+(x<<3)+(ch-'0');
        ch = getchar();
    }
    return x*w;
}

输出优化:
众所周知putchar(),单个输出一个字符也要比输出整型快(我还是不知道为什么。。。)
因为大多数人都说递归较慢,所以我们写栈实现的;

inline void write(int x)
{
    if(x<0) x=-x , putchar('-');
    static int sta[35];
    int top = 0;
    do{
        sta[top++] = x % 10 , x /= 10;
    }while(x);
    while(top) putchar(sta[--top]+'0');
}

通用版本和读入的就差不多了,记得调大栈。
OK,更新完成,2019 rp++;

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息