跳到正文

科技·工程

CYaRon Is All You Need! | 使用 CYaRon 制造数据

YWD2023约 34 分钟
原文
文章信息与版本

文章信息

发布
2026年9月30日
收录
2026年10月1日
更新
2026年10月2日
篇幅
约 34 分钟

版本

  1. v2当前
  2. v1

你还在被 Datagen 困扰吗?

需要一棵树、一张没有自环和重边的连通图、几组区间操作?还要让标程自动生成输出。放进同一套对拍?

让我们使用 CYaRon 吧!(肯定和 CYaRon! 没有关系!)

英明的你谷想到了这一点。你谷的 CYaRon 把这些环节放在了一组接口中,极大方便了数据生成和测试的流程!CYaRon 正是用来处理这些重复工作的!(当然,它不能替你写 std),但可以让你造结构、写文件、运行程序和比较输出连起来!

注:发挥大注意力注意到疑似没有完整介绍 CYaRon 的文章,作此篇,兼怀子由。

开始前注意
  1. 你需要会 Python 的基础使用。
  2. 请通过 pip install cyaron 提前安装西外诶而欧恩。
  3. 为了方便,大部分示例使用 from cyaron import *(虽然这样似乎不太像工程规范)。如无特殊说明都采用这种写法。
  4. 我们注意到 VectorRandomMode 不在默认导出,所以被单独导入了。

Example

第一次使用时,先生成几组 .in/.out 文件。

这里提供一个示例。

Python
from cyaron import *

point_counts = ati([0, 5, 20, 100])
edge_counts = ati([0, 4, 30, 300])

for case_id in range(1, 4):
    io = IO(file_prefix="data", data_id=case_id)
    n = point_counts[case_id]
    m = edge_counts[case_id]

    io.input_writeln(n, m)
    graph = Graph.graph(
        n,
        m,
        weight_limit=(1, 100),
        self_loop=False,
        repeated_edges=False,
    )
    io.input_writeln(graph.to_str(shuffle=True))
    io.output_gen("std.exe")

好了,你已经会写数据器了!(会写 int main(){return 0;} 了!)

我们注意到:

  • IO 管理输入、输出文件。
  • Graph.graph() 生成结构。
  • input_writeln() 写入输入。
  • output_gen() 运行 std 并生成输出。

ati() 会把可迭代对象逐项转成 int。数据规模写成 1e4、2e5 时,可以用它转回整数。

让我们 import

一般写一行即可。

Python
from cyaron import *

它会导出这些:

代码
Compare  Edge  Graph  IO  Merger
Polygon  Sequence  String  Vector
注

PyPI 版似乎没有 RangeQuery,但如果你查看 GitHub 源码会发现是有的。(这是为什么?)

Python random 中常用的 choice、randint、random、randrange 和 uniform 也会一并导出。(你谷贴心的让你可以直接写 randint 什么的,不需要导入)

但是!But!这个需要单独导入!

Python
from cyaron.vector import VectorRandomMode
其他

如果你非常有兴趣去翻代码的话还会发现一个 visual.py 和 visualize(),不过并不能使用。

不知道是干什么的。

IO 管理文件和标程

让我们使用 IO 吧!

它可以非常方便的管理文件。图、序列和字符串最终通过它写进文件,标程生成输出和程序对拍也会使用它。

创建文件

让我们创建文件!

Python
from cyaron import *

IO("a.in", "a.out")
IO(file_prefix="data")
IO(file_prefix="data", data_id=3)
IO("data{}.in", "data{}.out", data_id=3)
IO(file_prefix="hack/case", data_id=7, make_dirs=True)
IO(file_prefix="only_input", disable_output=True)
IO()

这些写法分别对应以下场景。

  • IO("a.in", "a.out") 直接指定两个文件名。
  • IO(file_prefix="data") 生成 data.in 和 data.out。
  • 带 data_id=3 时,前缀模式会生成 data3.in 和 data3.out。
  • 文件名中的 {} 会被 data_id 替换。
  • make_dirs=True 会创建不存在的中间目录。
  • disable_output=True 只创建输入文件。
  • 不传参数时会创建临时文件,一般适合对拍。

可以使用 with 让文件在离开 with 块后关闭。

Python
from cyaron import *

with IO(file_prefix="data", data_id=1) as io:
    io.input_writeln(1, 2, 3)

写入内容

input_write()、input_writeln() 写输入文件,output_write()、output_writeln() 写输出文件。

带 ln 的函数会补换行,不带就不补。

Python
from cyaron import *

io = IO("demo.in", "demo.out")
io.input_writeln(3, 5)
io.input_writeln([1, 4, 9])
io.input_write("hello")
io.input_write("world", separator=",")
io.input_writeln()
io.output_writeln("8")
输出

demo.in:

代码
3 5
1 4 9
hello,world

demo.out:

代码
8

写入的默认分隔符是空格,列表和元组会递归展开(所以你可以注意到例子里列表的方括号没有写进文件)

需要其他分隔符时传入 separator。

Python
from cyaron import *

with IO("comma.in", disable_output=True) as io:
    io.input_writeln(
        Sequence(lambda i, previous: i - 1).get(1, 10),
        separator=",",
    )

input_clear_content(pos=0) 和 output_clear_content(pos=0) 可以截断文件。flush_buffer() 会刷新输入缓冲区。程序需要立刻读取刚写入的内容时,这个方法能帮助排查缓冲问题。

Run std

Python
from cyaron import *

with IO(file_prefix="sum", data_id=1) as io:
    io.input_writeln(5)
    io.input_writeln(1, 2, 3, 4, 5)
    io.output_gen("std.exe")

output_gen() 会把当前输入文件交给标程,将标准输出写进对应的 .out 文件。

常用参数包括 shell_cmd、单位为秒的 time_limit(你可以让标程 TLE?)和控制换行的 replace_EOL。

输出已经关闭的 IO 对象不能调用 output_gen()。

Graph 生成图

图是 CYaRon 最常用的一部分。随机图、树、连通图和 DAG 都可以直接使用,手工构造则从 Graph 本身开始。

手工建图和输出

Python
from cyaron import *

graph = Graph(4, directed=True)
graph.add_edge(1, 2, weight=7)
graph.add_edge(2, 4, weight=3)
graph.add_edge(1, 3, weight=9)

print(graph.edge_count())
print(graph)
输出
代码
3
1 2 7
1 3 9
2 4 3

点默认从 1 开始编号。无向图调用一次 add_edge(1, 2) 就够了,内部会保存反向边,iterate_edges() 和字符串输出只会把这条无向边输出一次。

str(graph) 等价于 graph.to_str()。无权图可以换用 Edge.unweighted_edge。

Python
from cyaron import *

graph = Graph.graph(5, 6, self_loop=False, repeated_edges=False)
print(graph.to_str(output=Edge.unweighted_edge))
输出

注:输出的边顺序可能会因为随机重映射而变化,因此是随机的,这里仅给出一种情况。

代码
1 5
1 2
2 3
2 5
3 5
3 4

to_str(shuffle=True) 会随机重映射点号,同时打乱输出,影响点号和边的输出顺序。可以让构造规律不出现在点号中。

邻接矩阵

Python
from cyaron import *

graph = Graph(3, True)
graph.add_edge(1, 3, weight=3)
graph.add_edge(2, 3, weight=7)
graph.add_edge(2, 3, weight=4)

print(graph.to_matrix())
print(graph.to_matrix(default=0))
print(graph.to_matrix(default=0, merge=lambda old, edge: max(old, edge.weight)))
输出
代码
-1 -1 3
-1 -1 4
-1 -1 -1
0 0 3
0 0 4
0 0 0
0 0 3
0 0 7
0 0 0

默认情况下,不存在的边记为 -1。多重边会以后一次写入的权值覆盖前一次。merge(old_value, edge) 能改成取最大值、最小值或其他规则。

树和森林

Python
from cyaron import *

chain = Graph.chain(6, weight_limit=(1, 10))
flower = Graph.flower(6, weight_limit=10)
random_tree = Graph.tree(10)
mostly_chain = Graph.tree(10, chain=1)
mostly_flower = Graph.tree(10, flower=1)
mixed_tree = Graph.tree(10, chain=0.4, flower=0.3)
forest = Graph.forest(20, 4, weight_limit=10)

chain() 生成链,flower() 生成菊花图,tree() 用于随机树,forest(total_points, tree_count) 生成指定连通块数的森林。

Graph.tree() 的 chain 和 flower 都在 0 到 1 之间(试一试一起开会不会炸?)控制树形偏向,精确控制父亲时则使用 father_gen(cur)。

Python
from cyaron import *

graph = Graph.tree(
    10,
    weight_gen=lambda: randint(100, 200),
    father_gen=lambda current: max(1, current - randint(1, 3)),
)

二叉树由 binary_tree() 生成。

Python
from cyaron import *

graph = Graph.binary_tree(15, left=0.35, right=0.35, weight_limit=(1, 5))

left 和 right 都必须位于 [0, 1],二者之和不能超过 1。

一般图、连通图和 DAG

Python
from cyaron import *

graph = Graph.graph(
    8,
    12,
    directed=False,
    self_loop=False,
    repeated_edges=False,
    weight_limit=(1, 20),
)

Graph.graph() 默认允许自环和重边。题目要求简单图时,务必显式写出 self_loop=False, repeated_edges=False。

无向连通图使用 UDAG()。

Python
from cyaron import *

graph = Graph.UDAG(
    10,
    18,
    self_loop=False,
    repeated_edges=False,
    weight_limit=100,
)

边数必须至少为 point_count - 1。UDAG() 仍默认允许自环,简单图同样要明确关闭自环和重边。

Python
from cyaron import *

graph = Graph.DAG(
    10,
    20,
    self_loop=False,
    repeated_edges=False,
    weight_limit=(1, 9),
)

DAG() 在 loop=False 时按点号约束方向,通常可以保证无环。将 loop=True 打开后,接口不再强制 u < v,结果未必还是严格意义上的 DAG。

Graph.connected() 只是统一入口。directed=False 时调用 UDAG(),directed=True 时调用 DAG()。

特殊图

作为万恶的出题或数据,想必是要让:

关于 SPFA 它死了。

CYaRon 贴心的为你提供了 hack_spfa()。

Python
from cyaron import *

graph = Graph.hack_spfa(
    30,
    directed=True,
    extra_edge=4,
    weight_limit=(1, 100),
)

hack_spfa() 提供一份偏向卡 SPFA 的内置构造。虽然不一定能卡所有,但也可以让选手感到十分开心。

from_degree_sequence() 可以按度数序列生成图。

Python
from cyaron import *

undirected = Graph.from_degree_sequence((2, 2, 1, 1, 1, 1))
directed = Graph.from_degree_sequence(((1, 2), (1, 1), (1, 0)))

无向图传入整数序列,有向图传入 (in_degree, out_degree) 序列。

self_loop、repeated_edges、weight_limit、weight_gen、n_iter 和 iter_limit 都可以进一步控制生成过程。

Vector 批量生成参数

Vector 适合生成点集、坐标、操作参数和随机数对。

Python
from cyaron import *

points = Vector.random(5, [(1, 10), (1, 20)])
print(points)

position_range 中的一项代表一个维度。单个整数 x 表示 [0, x],二元组 (left, right) 表示闭区间 [left, right]。

Python
Vector.random(5, [10])
Vector.random(5, [(1, 10)])

前者生成范围为 0 到 10 的一维数,后者从 1 到 10。

Vector.random() 有三种模式。

Python
from cyaron import *

unique_points = Vector.random_unique_vector(5, [(1, 10), (1, 10)])
repeatable_points = Vector.random_repeatable_vector(5, [(1, 10), (1, 10)])
float_points = Vector.random_float_vector(5, [(0, 1), (0, 1)])

默认模式为 unique。唯一模式下,向量数量超过整个取值空间时会抛出 ValueError。

Python
from cyaron import *

n = 8
m = 5
array = Vector.random(n, [(1, 100)])
operations = Vector.random_repeatable_vector(
    m,
    [(1, n), (1, n), (1, 100)],
)

这类写法比连续写多个 randint() 更容易检查维度和范围。

String 生成随机文本

Python
from cyaron import *

lowercase = String.random(10)
custom = String.random(12, charset="abc")
mixed = String.random(20, charset=ALPHABET + NUMBERS)

默认字符集是 ALPHABET_SMALL。当 charset 是列表或元组时,String.random() 会从中选一个完整元素。(并不是字符哦!)

Python
from cyaron import *

token = String.random(None, charset=["YES", "NO", "MAYBE"])

这会得到三个单词中的一个。

Python
from cyaron import *

sentence = String.random_sentence(
    8,
    word_length_range=(2, 6),
    first_letter_uppercase=True,
    charset="abcde",
    word_separators=" ",
    sentence_terminators=".",
)

paragraph = " ".join(
    String.random_sentence(
        randint(6, 10),
        charset=["aaa", "bbb", "ccc"],
        sentence_terminators=".",
    )
    for _ in range(5)
)

random_sentence() 可以控制词数、词长、首字母、字符集、词间分隔符和句末符。当前 PyPI 版本的 random_paragraph() 与 word_count_range 一起使用似乎会炸掉,所以你可以注意到上面的写法比较诡异(并没有使用 word_count_range)。

满足格式约束的字符串还可通过正则生成。

Python
from cyaron import *

identifier = String.random_regular(r"[0-9]+\w_.{0,9}", limit=5)

limit 控制生成长度上界,默认值为 10。传入多个 pattern 时会随机选择其中一个。

Sequence 写递推数列

Python
from cyaron import *

arithmetic = Sequence(lambda i, previous: 2 * i + 1)
print(arithmetic.get(1))
print(arithmetic.get(1, 5))

fibonacci = Sequence(
    lambda i, previous: previous(i - 1) + previous(i - 2),
    [0, 1],
)
print(fibonacci.get(2, 10))

formula(i, previous) 中的 i 是当前下标,previous 用于访问前面的项。初值可以是列表、元组或字典。

Python
from cyaron import *

sequence = Sequence(lambda i, previous: previous(i - 1) + 3, {5: 100})
print(sequence.get(5))
print(sequence.get(6))

get(i) 取单项,get(left, right) 返回闭区间 [left, right] 的列表。内部带缓存,递推数列不需要反复计算已求出的项。

Polygon 处理几何数据

Python
from cyaron import *

polygon = Polygon([[0, 0], [1, 0], [1, 1], [0, 1]])
print(polygon.perimeter())
print(polygon.area())

显然这是一个正方形。

perimeter() 返回周长,area() 返回面积。

Python
from cyaron import *

hull = Polygon.convex_hull(
    20,
    fx=lambda x: int(x * 1000),
    fy=lambda y: int(y * 1000),
    strict=True,
)

points = Vector.random_unique_vector(30, [(0, 1000), (0, 1000)])
simple = Polygon.simple_polygon(points)

convex_hull() 先在接近 [0, 1] 的区域生成点,再通过 fx、fy 映射到目标坐标。strict=True 会倾向避免共线边界点。simple_polygon() 用给定点集构造不自交的简单多边形。

Compare 对拍和比较输出

数据生成后,可以让 CYaRon 直接运行程序并比较结果。

比较现成输出

Python
from cyaron import *

standard = IO("dummy.in", "std.out")
standard.output_writeln("114514")
Compare.output("another.out", std=standard)

std 可以是文件路径,也可以是 IO 对象。默认评测器是 DEFAULT_GRADER 的 NOIPStyle。

运行程序后比较

Python
from cyaron import *

io = IO()
io.input_writeln(4)
io.input_writeln(1, 2, 3, 4)

Compare.program(
    "my.exe",
    input=io,
    std_program="std.exe",
)

同一份输入会先后交给待测程序和标程,再由指定评测器比较输出。可以同时传入多个待测程序。

Python
from cyaron import *

io = IO()
io.input_writeln("hello")

Compare.program(
    "prog1.exe",
    "prog2.exe",
    "prog3.exe",
    input=io,
    std_program="std.exe",
)

NOIPStyle 会统一换行符,去掉每行行尾空白和结尾多余空行。FullText 对完整文本计算 SHA-256,任何字符差异都会判为不同。(除非你想体验恶心 Presentation Error\textcolor{orange}{\text{Presentation Error}} 不然还是 NOIPStyle 吧)

Python
from cyaron import *

io = IO()
io.input_writeln(1)

Compare.program(
    "my.exe",
    input=io,
    std_program="std.exe",
    grader="FullText",
)

待测程序可以写成 (command, timeout),超时单位为秒。

Python
from cyaron import *

Compare.program(
    (("python", "wa.py"), 1),
    input=IO(),
    std_program=("python", "std.py"),
)

Compare.output() 和 Compare.program() 都支持 max_workers、job_pool。默认 max_workers=-1 不会自动创建线程池。需要并行时,显式传 None 或非负整数。

Merger 拼接多张图

Python
from cyaron import *

first = Graph.tree(5, weight_limit=10)
second = Graph.graph(4, 5, self_loop=False, repeated_edges=False, weight_limit=10)

merged = Merger(first, second)
merged.add_edge((0, 3), (1, 2), weight=114)
print(merged)

Merger(first, second, ...) 会重新编排各图的点号。add_edge((graph_index, vertex), (graph_index, vertex), weight=...) 用于跨图连边。底层大图保存在 merged.G,str(merged) 和 merged.to_str() 都能直接输出结果。

Merger.component() 虽然存在于源码中,当前实现仍使用 Python 2 的 xrange。在 Python 3 环境中可能直接报错,使用前必须自行验证。

常量、数学函数和小工具

默认导出的常量包括以下内容。

代码
PI  E
ALPHABET_SMALL  ALPHABET_CAPITAL  ALPHABET  NUMBERS
SENTENCE_SEPARATORS  SENTENCE_TERMINATORS  DEFAULT_GRADER

数论和组合相关函数包括 is_prime()、miller_rabin()、factor()、prime_sieve()、exgcd()、mod_inverse()、phi()、miu()、fibonacci()、binomial() 和 catalan_number()。生成带数论性质的数据时,它们可以直接复用。

utils.py 中常见的小工具有 ati()、list_like()、int_like()、strtolines()、make_unicode()、process_args() 和 escape_path()。不再一一介绍。

process_args() 识别 --randseed=,可用固定种子复现数据。

Python
from cyaron import *

process_args()
print(randint(1, 100))
Bash
python gen.py --randseed=114514

日志详细程度可由 log.set_quiet()、log.set_normal() 和 log.set_verbose() 控制。

模板

这里写一份模板(可以 Ctrl/Command-C-V)。你也可以写一份自己的模板以便使用。(或者让能工智人生成?)

Python
from cyaron import *

for case_id in range(1, 1001):
    io = IO()
    n = randint(1, 30)
    q = randint(1, 30)

    io.input_writeln(n, q)
    io.input_writeln(Vector.random_repeatable_vector(n, [(1, 100)]))
    io.input_writeln(random_ranges(q, n))

    try:
        Compare.program(
            "my.exe",
            input=io,
            std_program="bf.exe",
            grader="NOIPStyle",
        )
    except Exception:
        print(f"Failed on case {case_id}")
        print(f"Input saved at: {io.input_filename}")
        raise

注意

  1. Graph.graph() 默认允许自环和重边。简单图必须明确写出 self_loop=False, repeated_edges=False。
  2. Vector.random() 的整数范围是 [0, x],RangeQuery.random() 的整数范围是 [1, x]。
  3. Graph.to_str(shuffle=True) 会重映射点号。
  4. String.random() 的 charset 为列表或元组时,返回一个完整元素。
  5. chain() 和 flower() 的当前默认方向是无向的,但似乎没有人注意到这一点。

实战

让我们使用 CYaRon 来试一试吧!

实战部分

随机生成发现几组都几乎一样?没有子任务限制?或者……

“根据最新消息,敌军摧毁了第45号、171号据点,我军依然顽强抗争,修复了据点37、98。现在可以反攻吗?”

“不可以,总司令。”

“敌军摧毁了第33号据点到42号据点的虫洞,现在可以反攻吗?”

“不可以,总司令。”

“我方修复了第42号据点,可以反攻吗?”

“不可以,总司令。”

“我方……”

“不可以,总司令。”

“同志,你只是一直在回答‘不可以’吗?你到底有没有好好判断形势?现在是关乎国家危亡的时刻……”

“总司令,您知道我不太聪明,没找到快速而正确地计算出结果的办法,但是据某项统计,我一直回答‘NO’的话,在一次战役中判断完全正确的概率是45%。”

“那……”

“不可以,总司令。”

显然你需要先想清楚 Subtask,想清楚准备卡掉哪种假算法。到处 randint 已经把选手半夜笑醒了。

CYaRon 可以直接非常方便就把基础结构迅速造出来。 但是题目要求存在性、唯一性、合法操作序列这类性质,需要自己解决。

测试点

一般每个 Subtask 通常不只是把 nn 的上界逐档调大。边数、权值、字符串总长、操作种类都可能跟着变。所以是不能直接 if 完事的。

拿一道 DAG 题目举例,假设三档数据分别限制 n,m,win,m,w_i。

测试点nnmmwiw_i
1-51≤n≤10001\le n\le 1000n−1≤m≤2000n-1\le m\le 20001≤wi≤3001\le w_i\le 300
6-101≤n≤200001\le n\le 20000n−1≤m≤50000n-1\le m\le 500001≤wi≤5001\le w_i\le 500
11-201≤n≤1061\le n\le 10^6n−1≤m≤5×106n-1\le m\le 5\times10^61≤wi≤5001\le w_i\le 500

十秒钟找出所有坑?

  1. 测试点 1 到 5 的权值上界是 300300,全填 500500 显然不可以。

  2. mm 的下界依赖 nn,不是独立常数。

  3. CYaRon 的简单 DAG 最多只有 n(n−1)2\dfrac{n(n-1)}{2} 条不同边。

找出坑了?那写一下?

Python
from cyaron import *

for case_id in range(1, 21):
    io = IO(file_prefix="dag_", data_id=case_id)

    if case_id <= 5:
        max_n, max_m, max_w = 1000, 2000, 300
    elif case_id <= 10:
        max_n, max_m, max_w = 20000, 50000, 500
    else:
        max_n, max_m, max_w = 10**6, 5 * 10**6, 500

    # 这里就是你自己设计的了,这个示例是选择 1 号测最小规模,5、10、20 号测最大 n
    if case_id == 1:
        n = 1
    elif case_id in (5, 10, 20):
        n = max_n
    else:
        n = randint(500, max_n)

    max_edges = n * (n - 1) // 2
    upper_m = min(max_m, max_edges)
    lower_m = n - 1
    if lower_m > upper_m:
        raise ValueError(f"case {case_id}: no feasible edge count for n={n}")

    m = upper_m if case_id in (5, 10, 20) else randint(lower_m, upper_m)
    if case_id in (5, 10, 20):
        weight_gen = lambda: max_w
    else:
        weight_gen = lambda: randint(1, max_w)
    graph = Graph.DAG(
        n,
        m,
        weight_gen=weight_gen,
        repeated_edges=False,
    )

    # 检查一下,当然你不检查也不是不行
    assert 1 <= n <= max_n
    assert lower_m <= m <= upper_m

    io.input_writeln(n, m)
    io.input_writeln(graph)
    io.output_gen("std.exe")

当然,除了满足题目要求还要注意一些小问题。

  1. 最小值和边界值。 给小规模、最大规模以及关键参数端点留出确定的测试点。随机显然是测不出来上界炸掉的边缘问题的。
  2. 结构性质。 子任务如果限制了树形、字符集、权值或操作类型,也是需要单独编写的。
  3. 结构形态差异。 同样规模的 nn 和 mm,既能生成链,也能生成星图、稀疏图、稠密图或随机树。如果选手口胡做法只在深链上爆,或者在稠密图里 Time Limit Exceeded\textcolor{purple}{\text{Time Limit Exceeded}},光把规模调大不一定能卡掉。
  4. 分布。 无解与有解、答案为 00 与极大值、可行解是否唯一显然都是需要你自己手动加入的。

顺序

如果有多种性质,也是有解决顺序要求的。 例如先选 nn,再算 mmin⁡=n−1m_{\min}=n-1、mmax⁡=min⁡(M,n(n−1)/2)m_{\max}=\min(M,n(n-1)/2),最后才在交集里取 mm。

区间操作先选左端点,再选不小于它的右端点,保证 1≤l≤r≤n1\le l\le r\le n。(为什么?随机 ll 和 rr 不一定合法呀!)

具体的注意事项不再一一列举了(不然也写不完……)不过需要注意的是怎样从答案性质反推构造,避免整份测试数据都被 NO 或 -1 占满。(依旧不可以,总司令!)

(没有写完)

欲知后事如何,请看下回分解

原文