跳到正文

个人记录

如何写出适合自己的缺省源?

ywcw约 8 分钟
原文
文章信息与版本

文章信息

收录
2026年3月14日
更新
2026年4月23日
篇幅
约 8 分钟

版本

  1. v1当前

C++ 竞赛缺省源构建指南

在算法竞赛中,随着题目难度上升,思考时间往往远超编码时间,而低效的调试方式更会雪上加霜。一套顺手、高效的缺省源能帮你节省宝贵时间,让你专注于解题思路。本文将手把手带你打造一个适合你自己的 C++ 缺省源,并提供完整的参考模板。

👉 我的完整模板


基础优化

确保你的 .cpp 文件使用了万能头 #include <bits/stdc++.h>。

1. 关闭 I/O 同步

关闭 C++ 标准流与 C 标准流的同步,可大幅提升 cin/cout 的速度。

C++
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
// 或简写为
cin.tie(0)->sync_with_stdio(0);
警告

关闭同步后,切勿混用 scanf/printf 与 cin/cout,否则会导致未定义行为。

2. 使用 '\n' 代替 endl

endl 会强制刷新输出缓冲区,在大量输出时严重影响性能。用 '\n' 替代即可,如需手动刷新可使用 fflush(stdout)。

C++
#define endl '\n'

3. 简化循环书写

为常用的循环定义简写,提高编码速度。

C++
// 闭区间 [l, r]
#define rep(i, l, r) for(int i = (l); i <= (r); ++i)
#define per(i, r, l) for(int i = (r); i >= (l); --i)

4. 类型别名与常用常量

C++
using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;

const int INF = 0x3f3f3f3f;          // 足够大且不易溢出
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const int MOD = 1e9 + 7;             // 根据题目修改
const double EPS = 1e-9;

5. 容器遍历与大小

C++
#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()

6. 取最值辅助函数

C++
template<class T> bool chmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; }
template<class T> bool chmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; }

实用工具

1. 快速打印数组

用于调试时快速输出数组内容。

C++
// 用法:aprint(arr, 100)  输出形如 arr=1, 2, 3, ...
#define aprint(a, len) do { \
    cout << #a << " = "; \
    for(int i = 0; i < (len); ++i) cout << (a)[i] << ", "; \
    cout << endl; \
} while(0)

2. 文件输入输出重定向

在本地测试或正式比赛时方便切换。

C++
// 用法:file("problem_name")
#define file(x) freopen(x".in", "r", stdin), freopen(x".out", "w", stdout)

3. 强大的调试宏

支持任意数量参数、表达式、STL 容器输出。

C++
namespace Debug {
    template<class T>
    void _debug(const char *s, T x) { cout << s << "=" << x << endl; }

    template<class T, class... Args>
    void _debug(const char *s, T x, Args... args) {
        int paren = 0;
        while (*s != ',' || paren) {
            if (*s == '(') ++paren;
            if (*s == ')') --paren;
            cout << *s++;
        }
        cout << "=" << x << ",";
        _debug(s + 1, args...);
    }

    template<class T>
    ostream& operator<<(ostream &os, const vector<T> &v) {
        os << "[";
        for (auto it = v.begin(); it != v.end(); ++it)
            os << *it << (next(it) != v.end() ? ", " : "");
        return os << "]";
    }
    // 可根据需要添加对其他容器(如 set, map)的重载
}

#define debug(...) Debug::_debug(#__VA_ARGS__, __VA_ARGS__)

使用示例:

C++
int a = 42;
double b = 3.14;
string c = "hello";
vector<int> v = {1, 2, 3};

debug(a);                  // a=42
debug(a, b, c);             // a=42,b=3.14,c=hello
debug((a + b) * 2);         // (a+b)*2=90.28
debug(v);                   // v=[1, 2, 3]

4. 快速读入(当关闭同步仍嫌慢时)

基于 fread 的快速读入模板,适用于输入规模极大的题目。

C++
namespace FastIO {
    static char buf[1 << 20], *p1 = buf, *p2 = buf;
    #define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 20, stdin), p1 == p2) ? EOF : *p1++)

    template<typename T>
    T read() {
        T x = 0, f = 1;
        char ch = getchar();
        while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
        while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
        return x * f;
    }

    template<typename T>
    void write(T x) {
        if (x < 0) putchar('-'), x = -x;
        if (x > 9) write(x / 10);
        putchar(x % 10 + '0');
    }
    #undef getchar
}
using namespace FastIO;
// 用法:int n = read<int>(); write(n);

5. 随机数生成器

基于 mt19937 的高质量随机数,适合对拍或随机化算法。

C++
#include <chrono>
#include <random>

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int randint(int l, int r) {
    return uniform_int_distribution<int>(l, r)(rng);
}

完整模板示例

将以上内容组合起来,形成一份可随时复制使用的缺省源文件。具体代码可参考文章开头提供的链接。


后记

GenAI使用声明

本文在撰写过程中使用了 GenAI 辅助润色语言和整理代码示例,但核心内容及代码均由作者提供并审核。作者对文章内容负全部责任,并已仔细核查 GenAI 生成部分,确保其准确无误。

原文