【教程】C++ 造数据一条龙教程Ⅰ

· · 科技·工程

【教程】C++ 造数据一条龙教程Ⅱ

0 前言:为什么你需要学会「造数据」?

在算法竞赛(OI / ACM)中,「造数据」(Data Generation / Test Case Generation)是一项被严重低估的核心技能。很多初学者能够熟练地写出解题代码,却在面对以下场景时束手无策:

本教程旨在为你提供一套系统化、可复用的 C++ 造数据方法论。无论你是刚入门的 OIer,还是希望提升测试能力的开发者,这篇教程都将是你案头必备的参考手册。

:::warning[观前提示]{open}

:::

1 随机数的基石

造数据的核心是「随机」,但「随机」并不等于「随便」。C++ 的随机数生成经历了从 C 风格到现代 C++ 标准的巨大演变。理解这一演变,是写出高质量造数据程序的前提。

1.1 为什么不应该再用 rand()

在许多老旧的教程中,你依然能看到 srand(time(0)) 配合 rand() 的用法。但在现代 C++ 造数据中,请彻底抛弃这种做法。原因如下:

1.2 现代 C++ 生成随机数:<random> 库

C++11 引入的 <random> 库提供了工业级的随机数生成设施。它由两部分组成:引擎(Engine) 和分布(Distribution)。

1.2.1 梅森旋转引擎 mt19937^{[1]}

这是目前造数据的事实标准。它的周期长达 2^{19937}-1,通过了几乎所有严格的统计测试套件,且性能优异。

#include <random> // mt19937 头文件
#include <chrono> // 获取时间戳所需头文件
using namespace std;

mt19937 rng1(114514); // 创建生成器并设置固定种子(固定种子生成固定随机序列)
mt19937 rng2(random_device{}()); // 使用真随机设备初始化种子
mt19937 rng3(chrono::steady_clock::now().time_since_epoch().count()); // 使用当前时间戳初始化种子

:::info[重要原则:可复现性]{open}

对拍造数据时,永远优先使用固定种子。\ 当你发现某组数据能让选手的程序出错时,你必须能够精确地重新生成这组数据来调试。如果使用随机种子,一旦数据丢失就再也找不回来了。\ 建议在生成器的注释或输出文件名中记录当前使用的种子值。

:::

1.2.2 引擎对比

::cute-table{tuack} | 引擎 | 周期 | 生成 10^8 个随机数用时(开启 O2 优化) | 适用场景 | | :-: | :-: | :-: | :-: | | mt19937 | 2^{19937}-1 | 0.2803 \text{s} | 通用造数据、算法竞赛首选 | | mt19937_64 | ^ | 0.3244 \text{s} | 需要 64 位随机数时 | | minstd_rand | 2^{31}-2 | 0.3618 \text{s} | 对质量要求不高的简单测试 | | ranlux24 | (2^{24} - 1) \times 2^{10} - 1 | 5.916 \text{s} | 一般高精度模拟 | | ranlux48 | ^ | 17.75 \text{s} | 统计模拟、高质量需求 |

1.2.3 均匀分布 uniform_int_distribution 和 uniform_real_distribution

彻底解决模偏差问题。

// 生成 [l, r] 内的随机 int
mt19937 rng(666);
int rand_int(int l, int r) {
    return uniform_int_distribution<int>(l, r)(rng);
}

1.2.4 其他分布

1.2.5 基本模板

:::success[点我展开]

#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); // 或使用固定种子
// rand_ll(l, r):生成 [l, r] 内的随机 long long(int)
long long rand_ll(long long l, long long r) {
    return uniform_int_distribution<long long>(l, r)(rng);
}
// rand_ull(l, r):生成 [l, r] 内的随机 unsigned long long(unsigned)
unsigned long long rand_ull(unsigned long long l, unsigned long long r) {
    return uniform_int_distribution<unsigned long long>(l, r)(rng);
}
// rand_double(l, r):生成 [l, r) 内的随机 double
double rand_double(double min, double max) {
    return uniform_real_distribution<double>(min, max)(rng);
}
// rand_char(s):从 s 中随机选择一个字符返回
char rand_char(string s) {
    int idx = rand_ll(0, s.size() - 1);
    return s[idx];
}
// rand_string(len, s):生成长度为 len 的字符串(字符来自 s)
string rand_string(int len, string s) {
    if (len == 0)
        return "";
    string res = "";
    for (int i = 0; i < len; i++)
        res += rand_char(s);
    return res;
}
// rand_shuffle(begin, end):随机打乱 [begin, end)
template <typename RandomIt>
void rand_shuffle(RandomIt begin, RandomIt end) {
    shuffle(begin, end, rng); // 此函数是 STL 函数,根据传入的随机数引擎打乱区间
}

// 写得不习惯的话给函数起个别名
auto& rand_int = rand_ll;
auto& rand_unsigned = rand_ull;

:::

:::info[关于生成效率]{open}

你可能会担心以上介绍的造数据方法效率没有 rand() 高,但这是完全没必要的。\ 实测生成 10^8 个 [1,10^9] 的随机数,mt19937 配合分布 1.688 \text{s},rand() 3.026 \text{s}(均开启 O2 优化)。

:::

2 序列数据的构造

2.1 随机序列

// rand_array(n, l, r):生成长度为 n 的随机数组,元素在 [l, r] 内
vector<long long> rand_array(int n, long long l, long long r) {
    vector<long long> a(n + 1);
    for(int i = 1; i <= n; i++)
        a[i] = rand_ll(l, r);
    return a;
}
vector<double> rand_array(int n, double l, double r) {
    vector<double> a(n + 1);
    for(int i = 1; i <= n; i++)
        a[i] = rand_double(l, r);
    return a;
}

2.2 随机排列(Permutation)

// rand_permutation(n):生成长度为 n 的随机排列
vector<int> rand_permutation(int n) {
    vector<int> p(n + 1);
    iota(p.begin() + 1, p.end(), 1); // 填充 1, 2, ..., n
    rand_shuffle(p.begin() + 1, p.end());
    return p;
}

2.3 特殊序列

造数据不仅仅是生成随机数据,更重要的是生成有针对性的数据:

这里给出生成块状数据的示例:

// rand_block_array(n, l, r, minl, maxl):生成长度为 n 的块状数组,元素在 [l, r] 内,块大小在 [minl, maxl] 内(最后一块为散块)
vector<int> rand_block_array(int n, int l, int r, int minl, int maxl) {
    vector<int> a(n + 1);
    for(int i = 1; i <= n; i++) {
        int len = rand_ll(minl, maxl), val = rand_ll(l, r);
        for(int j = i; j <= i + len - 1 && j <= n; j++)
            a[j] = val;
        i += len - 1;
    }
    return a;
}

有时,序列的约束不像上面这么简单,比如「相邻元素不同」、「前缀和不超过 k」,此时有以下几种方法:

此时需要根据实际情况,采用合适的算法构造。

3 字符串数据的构造

字符串数据的构造有其独特性,因为字符串的结构复杂度远高于数值序列。

3.1 随机字符串

4 图论数据的构造

图论数据的构造是造数据中最具挑战性的部分之一。错误的生成方式可能导致生成的不是合法图、连通性不符合预期、或者数据分布严重偏离目标。

4.1 树的生成

5 高级数据构造技巧

Ex 注释