Skip to content

示例教程与实践

此文档列出多个实战示例,展示如何用 STAR_CPP 生成测试数据并在本地运行验证。示例分为:简单示例、生成大规模输入、用于算法测试的组合生成。

示例 1:生成简单图并写文件

#include <fstream>
#include "STAR_CPP.h"
using namespace STAR_CPP;
int main(){
    auto edges = Graph::erdos_renyi(100, 0.02, 2026);
    IO io("in.txt", "out.txt");
    io.write_atomic("graph.txt", Graph::to_edge_list_string(edges));
    return 0;
}

运行上述程序后,文件 graph.txt 将包含边列表,可直接供其他程序读取。

示例 2:生成排序算法的测试集

using namespace STAR_CPP;
IO io("arr_in.txt", "arr_out.txt");
// 生成 1000 个近乎有序元素
auto v = Sequence::nearly_sorted(1000, 0, 10000, 0.01, 31415);
std::ostringstream ss;
for (auto x: v) ss << x << ' ';
io.write_atomic("arr_in.txt", ss.str());

示例 3:组合生成带权图并运行外部验证程序

using namespace STAR_CPP;
auto w = Graph::random_weighted_graph(200, 500, 1.0, 100.0, 7);
std::ostringstream ss;
for (auto &t: w) ss << std::get<0>(t) << ' ' << std::get<1>(t) << ' ' << std::get<2>(t) << '\n';
IO io("input.txt", "output.txt");
io.write_atomic("input.txt", ss.str());
// 若有本地验证程序,可用 io.createof("./solver") 运行并将输出写入 output.txt

示例 4:使用 Water Reservoir 从大型流中采样

using namespace STAR_CPP;
Random rng(42);
std::vector<int> big;
for (int i=0;i<1000000;++i) big.push_back(i);
auto sample = rng.reservoir_sample<int>(big.begin(), big.end(), 1000);
// 此时 sample 包含 1000 个均匀采样的元素

建议:每次生成用于评测的大样本时记录种子,便于复现问题与回归测试。