OI卡常小技巧

· · 个人记录

前言

我的同学小F与我的代码思路一模一样,我拿了50TLE,而他,拿了70TLE,正好这里给大家整理一下卡常优化小技巧

超级快读/快写

namespace IO{
    int len=0;
    char ibuf[(1<<20)+1],*iS,*iT,out[(1<<26)+1];
#define gh() (iS==iT?iT=(iS=ibuf)+fread(ibuf,1,(1<<20)+1,stdin),(iS==iT?EOF:*iS++):*iS++)
#define reg register
    inline int read(){
        reg char ch=gh();
        reg int x=0;
        reg char t=0;
        while(ch<'0'||ch>'9')   t|=ch=='-',ch=gh();
        while(ch>='0'&&ch<='9') x=x*10+(ch^48),ch=gh();
        return t?-x:x;
    }
    inline void putc(char ch){
        out[len++]=ch;
    }
    template<class T>
    inline void write(T x){
        if(x<0)putc('-'),x=-x;
        if(x>9)write(x/10);
        out[len++]=x%10+48;
    }
    inline void flush(){
        fwrite(out,1,len,stdout);
        len=0;
    }
}
using IO::read;
using IO::write;
using IO::flush;
using IO::putc;

使用read()函数读入,write()函数输出,putc('\n')换行,flush()结尾。

注意: 一定要flush()!!!

关于Register

将变量存储到CPU寄存器里,能加快10~100倍访问速度。

用法::

register <Type> <Name>;

坑

register 不能使用取地址符 & (也无法输入)。

register 在 C++17 中已经废弃!

关于Inline

将函数插入到代码中,减少系统栈开销。

用法:

inline <type> <name>(<arguments>){
    <dosomething>
}

坑

inline 仅适用非递归函数,否则可能适得其反。

inline 只是指示,编译器不一定采纳。

::::info[如何强制启用 inline?]

将 inline 替换成 inline __attribute__((always_inline))。

::::

关于空间缓存优化

尽量将某一组数据整合起来,加快访问速度。

数组稍稍开大也会加快速度。

例如:

int w[N],v[N];

变成

struct {
  int v;
  int w;
}a[N+30];

强制开启优化

#pragma GCC optimize(参数);

例如O2优化

#pragma GCC optimize(2);

或O3

#prgama GCC optimize(3,"Ofast");

堆空间

将某些容器或变量等设为局部,可以加快访问速度。小心爆掉

bitset

如果你使用了状态压缩,用 bitset 代替状压后的 int 能快 32 倍,long long 能快 64 倍。

用法:

#include<bitset>
bitset<大小>名称;

例:

bitset<100010>a;

::::info[冷知识]

bitset 支持位运算!

::::

位运算优化

优化前 优化后
!= ^
&& &
\|\| \|
%2 &1

:::::warning[卡常卡到甲沟炎] ::::error[错误示范]

dp[i]=(a[i]^a[i+1]);

::::

::::success[正确示范]

dp[i]=(a[i]!=a[i+1]);
::::