跳到正文

个人记录

OI卡常小技巧

lonys约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年3月2日
收录
2026年5月6日
更新
2026年11月15日
篇幅
约 4 分钟
获赞
1

版本

  1. v2当前
  2. v1

前言

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


超级快读/快写

C++
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倍访问速度。

用法::

C++
register <Type> <Name>;

坑

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

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

关于Inline

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

用法:

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

坑

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

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

如何强制启用 inline?

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

关于空间缓存优化

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

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

例如:

C++
int w[N],v[N];

变成

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

强制开启优化

C++
#pragma GCC optimize(参数);

例如O2优化

C++
#pragma GCC optimize(2);

或O3

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

堆空间

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

bitset

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

用法:

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

例:

C++
bitset<100010>a;
冷知识

bitset 支持位运算!

位运算优化

优化前优化后
!=^
&&&
|||
%2&1
卡常卡到甲沟炎
错误示范
C++
dp[i]=(a[i]^a[i+1]);
正确示范
C++
dp[i]=(a[i]!=a[i+1]);
原文