UOJ Logo tendency的博客

博客

io库

2018-09-02 22:59:59 By tendency

做oj的时候,开始后我总发现自己的代码为什么比大神们慢这么多。

后来发现因为你用了cincout!!讲真,这个iostream库就是渣渣,性能有点问题,大型的项目都得自己写io库的。 scanfprintf是快很多,但还是比不上自己写的io库的啦~。

总而言之,不自己写io,你的代码在uoj上是无法跑到最快的。(很惭愧,本人就一次提交全站最快,说不定已经被人超了)

不废话了,我们来写写自己的io库,以后就可以复制粘贴啦:

namespace io {
const int MAXBUF = 1 << 20;
inline char get() {
    static char buf[MAXBUF],*p1,*p2;
    if(p1==p2) {
        p2 = (p1=buf)+fread(buf,1,MAXBUF,stdin);
        if (p1 == p2) return EOF;
    }
    return *p1++;
}

inline void read(int &x) {
   x = 0;
   bool is_neg = false;
    char ch =get();
    while(!(ch >='0' && ch <= '9') && ch != '-') ch = get();
   if (ch == '-') is_neg = true, ch = get();
    while((ch >='0' && ch <= '9')) x = x * 10 + ch  - '0',ch = get();
   if (is_neg) x = -x;
}

inline void read(float &x) {
   x = 0;
   bool is_neg = false;
    char ch =get();
   float basic = 1;
    while(!(ch >='0' && ch <= '9') && ch != '-') ch = get();
   if (ch == '-') is_neg = true, ch = get();
    while((ch >='0' && ch <= '9')) x = x * 10 + ch  - '0',ch = get();
   if (ch == '.') {
      ch = get();
   }
   while((ch >='0' && ch <= '9')) basic *= 0.1, x = x + basic * (ch  - '0'),ch = get();
   if (is_neg) x = -x;
}
}// namespacec io

自己的io库快的原因就是做了一些假设,不考虑各种错误情况(系统给的测试数据格式当然不会错啦),面对上百万的数据量自然省下不少运行时间。如果不检查是否为负数,那速度就更快啦。

评论

fucker
1. 请善用 `cin.sync_with_stdio(false); cin.tie(0);` 用 '\n' 代替 endl,在 noilinux 亲测比什么scanf快到不知道哪里去了,和 getchar() 读优五五开 2. 回复有 Markdown 吗?(((

发表评论

可以用@mike来提到mike这个用户,mike会被高亮显示。如果你真的想打“@”这个字符,请用“@@”。