c++代码实现总结

卡常

内存

缓存命中

其一:内存访问连续性

其二:能开短类型的尽量开短类型(例如 0/1 用 bool/char/__int8_t 存)。

扁平化内存池

把结构体套 vector,转为结构体套 int*,再开一个全局数组作为内存池。

dfs 重标号

需要多次对一棵树递归时(尤其是树上 DP 等),可以按 dfs/bfs 序重标号,这样省去递归、dp 数组访问 cache miss 时间。

链式前向星存图

将邻接表(vector<int>[])改为链式前向星。

运算

不取模 gcd

参考本文。

数据结构

线段树单点查改

可以开一个数组记录每个下标对应的叶子,然后循环处理。

线段树套离散化

对线段树上父节点的每个数,记录子节点中离散化编号,这样每次访问从二分/哈希表查询变为数组访问 \(\mathcal{O}(1)\)。

zkw 线段树

即非递归线段树。

重要应用:作为“竞赛树”,替代可删堆,时间快于二叉堆,空间优于优先队列。例题。

// 小根堆
int val[N];
struct Heap{
    int tr[N<<1];// 最小值位置
    bool cmp(int x,int y){
        if(val[x]!=val[y]) return val[x]<val[y];
        return x<y;
    }
    void build(int n){
        for(int i=1;i<=n;i++) tr[n+i-1]=i;
        for(int i=n-1;i>=1;i--){
            if(cmp(tr[i<<1],tr[i<<1|1])) tr[i]=tr[i<<1];
            else tr[i]=tr[i<<1|1];
        }
    }
    void update(int x){
        for(x+=n-1;x>>1;x>>=1){
            if(tr[x>>1]==tr[x^1]) break;
            if(cmp(tr[x],tr[x^1])) tr[x>>1]=tr[x];
            else tr[x>>1]=tr[x^1];
        }
    }
    void erase(int x){
        val[x]=infll;
        update(x);
    }
    int top(){
        int x=tr[1];
        if(val[x]==infll) return -1;
        return x;
    }
};

编译选项

  • -Wall -Wextra:报告“所有”Warning。
  • -fsanitize=undefined,address:在运行时检测未定义行为和寻址溢出,叠加 -g 可以报告错误行号。
  • -Wconversion:在编译期报告程序中类型窄化。注意对头文件内类型窄化无效(例如 pair<int,int>{(ll)x,(ll)y})。
  • -Wsystem-headers:显示所有头文件内的 Warning,叠加 -Wconversion 可以检测头文件内类型窄化,可以看 xxx: required from here 找到代码中错误位置。

计时器

chrono::high_resolution_clock 或 chrono::steady_clock

核心函数:

chrono::high_resolution_clock::time_point chorno::high_resolution_clock::now(); 返回当前时间。

chrono::high_resolution_clock::duration operator-(chrono::high_resolution_clock::time_point a,chrono::high_resolution_clock::time_point b); 返回时间差。

chrono::duration_cast<chrono::milliseconds>(duration D); 将 D 转换为毫秒为单位的 duration。

unsigned long long duration::count(); 输出 duration 的大小。

组合:

#include<bits/stdc++.h>
using namespace std;
int main(){
    using namespace chrono;
    using clk=high_resolution_clock;
    clk::time_point t1=clk::now();
    for(int i=1;i<=1e6;i++) fprintf(stderr,"hello\n");
    clk::time_point t2=clk::now();
    printf("%lld\n",duration_cast<milliseconds>(t2-t1).count());
    return 0;
}

__rdtsc

unsigned long long __rdtsc(); 返回 CPU 时钟周期数,可用于计时。

posted @ 2026-09-07 20:03  SmpaelFx  阅读(10)  评论(0)    收藏  举报