读入、输出优化

关闭流同步

std::ios::sync_with_stdio(false);

关闭输入输出流与标准输入输出(scanf printf)的同步,加快流速度,但关闭后不可混用。

整形快读

从标准输入流读入一个 int

#include<cctype>
#include<cstdio>
inline int read(){
    int x=0,w=0;char c=getchar();
    while(!isdigit(c)) w|=c=='-',c=getchar();
  while(isdigit(c)) x=x*10+c-'0',c=getchar(); 
  return w?-x:x; 
}

template 形式读入整形。

template <typename T>
inline T read(){
    T x=0;int w=1;char c=getchar();
    while(!isdigit(c)){if(c=='-')w=-1;c=getchar();}
    while(isdigit(c))x=(x<<1)+(x<<3)+(c^48),c=getchar();
    return x*w;
}
int main(){
    long long a;
    while(a=read<long long>())printf("%lld\n",a);
    return 0;
}

fread 快读

fread 快的原因好像是一次将一大堆东西压入输入流中然后利用指针读入。

char buf[1<<21],*p1=buf,*p2=buf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
inline int read(){
    int x=0,w=0;char c=getchar();
    while(!isdigit(c)) w|=c=='-',c=getchar();
    while(isdigit(c)) x=x*10+c-'0',c=getchar();
    return w?-x:x;
}

注意,因为是一次性读入,在调试手动输入数据的时候记得加 Ctrl+Z 结束。

整形快输

输出一个整形

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

fwrite 快输

char pbuf[1 << 20], *pp = pbuf;

inline void push(const char &c) {
  if (pp - pbuf == 1 << 20) fwrite(pbuf, 1, 1 << 20, stdout), pp = pbuf;
  *pp++ = c;
}

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

注意:与 fread 快读相同的原因,并不会实时输出。

posted @ 2020-06-07 11:43  Star_Cried  阅读(221)  评论(0编辑  收藏  举报