C++卡常

1.读入优化(*)

低阶版:

inline int read()
{
	int x=0,f=1;
	char ch=getchar();
	for(;ch<'0'||ch>'9';ch=getchar())
		if(ch=='-') f=-1;
	for(;ch>='0'&&ch<='9';x=(x<<3)+(x<<1)+(ch^48),ch=getchar());
	return x*f;
}


高阶版:

inline char getc()
{ 
    static char buf[1<<18],*fs,*ft;
    return(fs==ft&&(ft=(fs=buf)+fread(buf,1,1<<18,stdin)),fs==ft)?EOF:*fs++;
}
inline int read()
{ 
    char ch=getc(),f=1;
    int x=0;
    for(;!isgraph(ch);ch=getc());
    if(ch=='-') f=-1,ch=getc();
    for(;isdigit(ch);ch=getc())
        x=((x+(x<<2))<<1)+(ch^0x30);
    return x*f;
}
注意用上 #include<ctype.h>



2.输出优化

低阶版:

void print(int x)
{
    if(x<0)
    {
        putchar('-');
        x=-x;
    }
    if(x>9) print(x/10);
    putchar(x%10+'0');
}


高阶版:

static const int BUF=50000000;
char buf[BUF],*h=buf;
inline void put(char ch)
{
    h==buf+BUF?(fwrite(buf,1,BUF,stdout),h=buf):0;
    *h++=ch;
}
inline void putint(int num)
{
    static char _buf[30];
    sprintf(_buf,"%d",num);
    for(char *s=_buf;*s;s++)put(*s);
}
inline void finish()
{
    fwrite(buf,1,h-buf,stdout);
}

注意:put输出字符类型的,putint输出整数类型的。并且在主程序结束前打上finish();



3.register

举个例子for(int i=1;i<=n;i++)   =>   for(register int i=1;i<=n;i++)



4.inline

举个例子int add(int x,int y){return x+y;}   =>   inline int add(int x,int y){return x+y;}



5.位运算(*)

举个例子x*=2   =>   x<<=1



6.减少使用STL(*)

STL是一个常数非常大的东西。



7.用上define

define比赋值要快!!!



只要你的“暴力”不是很“暴力”,TLE1~2个点时,应该够用了。

带*号的真的很有用!!!

最后,感谢LJY大佬对我卡常知识的指导!!!

猜你喜欢

转载自blog.csdn.net/zsyz_zzy/article/details/79961324