getchar读入优化
inline int getint()
{
char ch;
int p=0,t;
for(ch=getchar();ch!='-' && !isdigit(ch);ch=getchar());
if(ch=='-'){
t=-1;
}
else{
t=1;
}
for(;!isdigit(ch);ch=getchar());
for(;isdigit(ch);ch=getchar()){
p=p*10+ch-48;
}
return t*p;
}
fread读入优化
char buf[MAXSIZE];int bufpos;
void init(){
#ifdef LOCAL
freopen("in.in","r",stdin);
#endif
buf[fread(buf,1,MAXSIZE,stdin)]='\0';
bufpos=0;
}
inline int readint(){
bool isneg;
int val=0;
for(;!isdigit(buf[bufpos]) && buf[bufpos]!='-';bufpos++);
bufpos+=(isneg=buf[bufpos]=='-');
for(;isdigit(buf[bufpos]);bufpos++)
val=val*10+buf[bufpos]-'0';
return isneg?-val:val;
}
MAXSIZE尽量大,如50000007
实测fread速度远快于getchar
看到一个很好的写法
缓冲区满了之后重新fread
空间较小,而且因为避免了 C a t c h M i s s CatchMiss CatchMiss 时间也变快了
inline char read() {
static const int IN_LEN = 1000000;
static char buf[IN_LEN], *s, *t;
return (s==t?t=(s=buf)+fread(buf,1,IN_LEN,stdin),(s==t?-1:*s++):*s++);
}
template<class T>
inline void read(T &x) {
static bool iosig;
static char c;
for (iosig=false, c=read(); !isdigit(c); c=read()) {
if (c == '-') iosig=true;
if (c == -1) return;
}
for (x=0; isdigit(c); c=read()) x=((x+(x<<2))<<1)+(c^'0');
if (iosig) x=-x;
}
const int OUT_LEN = 10000000;
char obuf[OUT_LEN], *ooh = obuf;
inline void print(char c) {
if (ooh == obuf + OUT_LEN) fwrite(obuf, 1, OUT_LEN, stdout), ooh = obuf;
*ooh++ = c;
}
template<class T>
inline void print(T x) {
static int buf[30], cnt;
if (x == 0) print('0');
else {
if (x < 0) print('-'), x = -x;
for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 + 48;
while (cnt) print((char)buf[cnt--]);
}
}
inline void flush() { fwrite(obuf, 1, ooh - obuf, stdout); }
结束后调用 f l u s h flush flush 刷新缓冲区