天天看點

【模闆】快速讀入/讀入優化

蒟蒻輸入成長史

放個闆子在這

測試了幾個輸入方法,發現幾種輸入方法的速度大緻為: c i n &lt; &lt; s c a n f &lt; c i n ( 關 閉 流 同 步 ) &lt; r e a d &lt; &lt; f r e a d cin&lt;&lt;scanf&lt;cin(關閉流同步)&lt;read&lt;&lt;fread cin<<scanf<cin(關閉流同步)<read<<fread

  • 入門教的是用 c i n cin cin
cin>>x
           
  • noip普及組時才知道用 s c a n f scanf scanf(有些聯賽題說要用高效的讀入方式,用這個就好)
  • 有人會接觸到 c i n cin cin的關閉流同步,不過這玩意兒好像在NOI中不能用?而且關閉流同步後就不能讀入 s t r i n g string string類型了
ios::sync_with_stdio(false);  
cin>>x;
           
  • 再後來省選,聽dalao們說有種東西叫做讀入優化 r e a d read read,原理是将數字按照數位一個個讀進來(比如數字 327 327 327 就會依次讀入 3 , 2 , 7 3,2,7 3,2,7,每次将數字乘 10 10 10 再加目前數字)(代碼的

    template <...

    是為了能同時讀入多種類型變量 ( u n s i g n e d ) i n t , l o n g l o n g , s h o r t (unsigned)int,longlong,short (unsigned)int,longlong,short 都行)
template <typename _tp> inline _tp read(_tp&x){
	char ch=getchar(),sgn=0;x=0;
	while(ch^'-'&&!isdigit(ch))ch=getchar();if(ch=='-')ch=getchar(),sgn=1;
	while(isdigit(ch))x=x*10+ch-'0',ch=getchar();if(sgn)x=-x;return x;
}

int main(){b=read(a);}
           
  • 準備全國賽時發現一道正解被卡成 25 p t s 25pts 25pts,資料量達 2 × 1 0 6 2\times 10^6 2×106, f r e a d fread fread 表現優秀(這裡和上頭差不多,隻不過是一次性讀入一大串字元, g c ( ) gc() gc() 函數每調用一次傳回一個字元,相當于樓上的 g e t c h a r ( ) getchar() getchar())
struct ios {
    inline char gc(){
        static const int IN_LEN=1<<18|1;
        static char buf[IN_LEN],*s,*t;
        return (s==t)&&(t=(s=buf)+fread(buf,1,IN_LEN,stdin)),s==t?-1:*s++;
    }

    template <typename _Tp> inline ios & operator >> (_Tp&x){
        static char ch,sgn; ch = gc(), sgn = 0;
        for(;!isdigit(ch);ch=gc()){if(ch==-1)return *this;sgn|=ch=='-';}
        for(x=0;isdigit(ch);ch=gc())x=x*10+(ch^'0');
        sgn&&(x=-x); return *this;
    }
} io;

int main(){io>>a>>b;}
           

繼續閱讀