fread快速讀入+fwrite快速輸出大法好。
實測比普通讀入優化快一倍,輸出不知道高到哪里去了。
/* * 快速讀入輸出模板 Au: Hatsune Miku * 用法: * 1. 在打開文件后立即調用init()函數初始化緩沖區。 * 2. 讀入時請使用 read()讀入,可以讀入字符串(僅限字母)與數字。 * 3. 輸出時請使用 print()輸出到緩沖區,可以輸出字符串、數字與字符。 * 4. 在關閉文件前使用 flush()刷新緩存區(真正輸出到文件中)。 * 函數返回值: * 1. 所有輸入操作均有返回值,返回真表示讀入成功,變量已被修改,返回假表示讀不到指定類型的數據,變量被清零; * 2. 所有輸出操作均無返回值,緩沖區自動刷新。 * 3. 初始化函數無返回值,如果超出緩沖區會RE。 * 玩得愉快! */ #include<cstdio> #include<cctype> #include<cstdlib> #include<assert.h> using namespace std; const int InputBufferSize = 67108864;//輸入緩沖區大小 const int OutputBufferSize = 67108864;//輸出緩沖區大小 namespace input { char buffer[InputBufferSize],*s,*eof; inline void init() { assert(stdin!=NULL); s=buffer; eof=s+fread(buffer,1,InputBufferSize,stdin); } inline bool read(int &x) { x=0; int flag=1; while(!isdigit(*s)&&*s!='-')s++; if(eof<=s)return false; if(*s=='-')flag=-1,s++; while(isdigit(*s))x=x*10+*s++-'0'; x*=flag; return true; } inline bool read(char* str) { *str=0; while(isspace(*s))s++; if(eof<s)return false; while(!isspace(*s))*str=0,*str=*s,str++,s++; *str=0; return true; } } namespace output { char buffer[OutputBufferSize]; char *s=buffer; inline void flush() { assert(stdout!=NULL); fwrite(buffer,1,s-buffer,stdout); s=buffer; fflush(stdout); } inline void print(const char ch) { if(s-buffer>OutputBufferSize-2)flush(); *s++=ch; } inline void print(char* str) { while(*str!=0)print(char(*str++)); } inline void print(int x) { char buf[25]= {0},*p=buf; if(x<0)print('-'),x=-x; if(x==0)print('0'); while(x)*(++p)=x%10,x/=10; while(p!=buf)print(char(*(p--)+'0')); } } using namespace input; using namespace output; int num; int main() { freopen("data.in","rb",stdin);//請根據題目修改文件名 freopen("data2.out","wb",stdout);//請根據題目修改文件名 init(); /* ... 此處應有代碼。 ... 下面的代碼示例讀入一個數列,然后輸出這個數列。 `````````````````````````````````````` ` int a; ` ` while(read(a))print(a),print(' '); ` `````````````````````````````````````` */ while(read(num))print(num),print(' '); flush(); return 0; }