跳到正文

题解

题解:P3186 [HNOI2007] 所罗门的咒语

CuteMurasame约 88 分钟
原文
文章信息与版本

文章信息

发布
2026年12月2日
收录
2026年12月2日
更新
2026年12月2日
篇幅
约 88 分钟
题目
P3186

版本

  1. v1当前

题意简述

给定一个 H×LH \times L(5≤L,H≤1005 \le L, H \le 100)的灰度亮度矩阵,元素为 [0,255][0, 255] 内的整数。矩阵中较亮的像素组成一个长度在 11 到 99 之间的字符串,字符从左到右大致排成一行,字符集为 0–9 以及 A, D, E, L, X 共 1515 种。由于噪声和光照影响,部分像素亮度存在误差。要求输出识别出的字符串长度及内容。

思路

本题要解决三个相互耦合的问题:图像存在噪点和不均匀背景,怎样稳定地提取前景;字符之间没有固定间隔且可能粘连,怎样同时决定切分位置、字符内容和咒语长度;单个候选区域分辨率很低,怎样准确区分 1515 种字符并拒绝拼在一起的多字符或切坏的笔画。

下面分五部分说明:预处理与前景提取、小型卷积网络打分、动态规划联合解码、多视角集成,以及模型训练与权重压缩。

去噪、背景校正与前景提取

原图存在两类常见干扰:孤立的极亮或极暗坏点,以及大范围的光照梯度或局部亮斑。如果直接对原图做全局二值化,局部背景亮度可能高于另一侧字符的笔画亮度,导致漏字或大片背景被误判为前景。

程序先做一次脉冲噪点抑制:对每个像素 (x,y)(x, y),求其 88-邻域的最小值 lolo 和最大值 hihi,将当前亮度裁剪到 [lo−22,hi+22][lo - 22, hi + 22]。这种做法只削平孤立坏点,不会像大窗口平滑那样把 1∼21 \sim 2 像素宽的细笔画抹掉。

之后,从去噪图衍生出三个灰度场共同参与后续识别:

  1. 原始去噪图本身,适用于背景均匀的图像;
  2. 形态学开运算去背景图:取半径 r=clamp⁡(min⁡(L,H)/7,2,7)r = \operatorname{clamp}(\min(L, H)/7, 2, 7),做可分离的一维先腐蚀后膨胀(开运算)估计低频背景 BB,计算 I−0.86BI - 0.86B,用来压制大块局部亮斑;
  3. 二次曲面光照校正图:将坐标归一化到 u,v∈[−1,1]u, v \in [-1, 1],用基函数 {1,u,v,u2,uv,v2}\{1, u, v, u^2, uv, v^2\} 拟合背景亮度曲面。为了不让亮前景把拟合曲面拉高,采用 99 轮非对称重加权最小二乘(IRLS),残差 r>0r > 0(偏亮)时取权重 0.23/max⁡(4,∣r∣)0.23 / \max(4, |r|),r≤0r \le 0(偏暗)时取权重 0.77/max⁡(4,∣r∣)0.77 / \max(4, |r|),每轮用高斯消元解 6×66 \times 6 方程组,最后从原图中减去曲面相对中心的变化量。

对每个灰度场,先用 Otsu 算法求出最大类间方差对应的暗部均值 dd 和亮部均值 bb,得到基准阈值 T=(d+b)/2T = (d + b)/2 和对比度 C=max⁡(1,b−d)C = \max(1, b - d)。为避免单次阈值偏高(断笔)或偏低(粘连),在 T+sCT + sC(s∈{0,−0.15,+0.12}s \in \{0, -0.15, +0.12\})三个阈值下分别提取前景,共形成 3×3=93 \times 3 = 9 个候选视图。

在单个视图中,先对亮度不小于阈值的像素求 88-连通块,滤除面积小于 min⁡(7,max⁡(2,largest/45))\min(7, \max(2, \text{largest}/45)) 的零星噪块,保留核心前景 core\text{core}。按连通块面积加权,取累计面积达到总面积 60%60\% 时的高度作为典型字高 h0h_0。接着构造连续的软前景图 ink\text{ink}:令 spread=max⁡(12,0.92C)\text{spread} = \max(12, 0.92C),每个像素的软亮度为

v(x,y)=clamp⁡(0.5+I(x,y)−T′spread,0,1).v(x, y) = \operatorname{clamp}\left(0.5 + \frac{I(x, y) - T'}{\text{spread}}, 0, 1\right).

核心像素直接取 v(x,y)v(x, y),与核心像素 88-相邻的外围像素取 min⁡(v(x,y),0.48)\min(v(x, y), 0.48),其余置 00。保留边缘的连续灰度比硬二值图更能保留低分辨率笔画的形状信息。同时记录每列核心前景的上下边界 top[x],bottom[x]\text{top}[x], \text{bottom}[x]、列质量 mass[x]=∑yink(x,y)\text{mass}[x] = \sum_y \text{ink}(x, y),以及相邻两列之间的粘连强度

link[c]=∑y:core(c−1,y)∧core(c,y)min⁡(ink(c−1,y),ink(c,y)).\text{link}[c] = \sum_{y : \text{core}(c-1,y) \land \text{core}(c,y)} \min(\text{ink}(c-1, y), \text{ink}(c, y)).

小型卷积网络与非字符类打分

对于任意候选列区间 [l,r][l, r],取区间内核心前景的纵向上下界 [t,b][t, b],将 ink\text{ink} 在矩形 [l,r]×[t,b][l, r] \times [t, b] 内的像素双线性重采样到 14×1414 \times 14,放进 16×1616 \times 16 画布中央(四周留 11 像素零边框)。由于拉伸会丢失宽高比信息,另计算 log_aspect=clamp⁡(ln⁡(w/h),−3.0,1.5)\text{log\_aspect} = \operatorname{clamp}(\ln(w / h), -3.0, 1.5) 一并输入网络。

网络由两层卷积和两层全连接组成,共 3218432184 个参数:第一层 4×44 \times 4 卷积(步长 22、填充 11、输出 1616 通道)将 16×16×116 \times 16 \times 1 变为 8×8×168 \times 8 \times 16;第二层同样配置的 4×44 \times 4 卷积(输出 2424 通道)将其变为 4×4×244 \times 4 \times 24,展平为 384384 维后与 log_aspect\text{log\_aspect} 拼接成 385385 维;随后经 385→64385 \to 64 全连接(ReLU)和 64→1664 \to 16 全连接输出 1616 维 logit。

输出设 1616 类而不是 1515 类是切分正确的关键。前 1515 类对应题目允许的字符,第 1616 类专门表示非字符区域,训练时喂入拼在一起的多个字符、切坏的局部笔画和随机噪点团块。推理时只在前 1515 类中取最大 logit 对应的字符 c∗c^*,但 softmax 分母包含全部 1616 类(温度系数 1.101.10):

prob=zc∗−zmax⁡1.10−ln⁡∑k=015exp⁡(zk−zmax⁡1.10).\text{prob} = \frac{z_{c^*} - z_{\max}}{1.10} - \ln \sum_{k=0}^{15} \exp\left(\frac{z_k - z_{\max}}{1.10}\right).

这样一来,如果候选区间把两个字符拼在了一起,或者只截到了半个笔画,第 1616 类的 logit 会很高,使得所有合法字符的 prob\text{prob} 都很低,后续动态规划就会自然避开这种错误切分。

动态规划联合切分与多视角投票

拿到前景统计量和分类器后,用动态规划同时决定切分位置、每个字符的内容以及咒语总长度。设 dp[x][n]dp[x][n] 表示处理完前 xx 列、已识别出 nn(0≤n≤90 \le n \le 9)个字符时的最大得分,初始 dp[0][0]=0dp[0][0] = 0,其余为 −∞-\infty。

转移有两种。第一是跳过第 ll 列,从 dp[l][n]dp[l][n] 转移到 dp[l+1][n]dp[l+1][n],得分扣除 4.6⋅mass[l]/h04.6 \cdot \text{mass}[l] / h_0。空白列几乎没有代价,包含前景笔画的列会被重罚,防止漏掉字符。第二是从左端点 ll 向右枚举右端点 rr,把 [l,r][l, r] 作为一个候选字符。枚举时跳过明显不合法的区间:内部最大连续空列超过 max⁡(2,⌊h0/3⌋)\max(2, \lfloor h_0/3 \rfloor) 或宽度超过 max⁡(4,⌊1.9h0⌋)\max(4, \lfloor 1.9 h_0 \rfloor) 时直接停止;高度小于 max⁡(3,⌊0.42h0⌋)\max(3, \lfloor 0.42 h_0 \rfloor) 或宽度超过 1.72h+0.51.72h + 0.5 时跳过。

当图像较宽(L>46L > 46)时,枚举所有 [l,r][l, r] 会调用过多次卷积网络,因此先用 select_cuts 筛出候选切分点:保留首尾边界、所有与空白列相邻的边界,再按 link[x]+0.16(mass[x−1]+mass[x])\text{link}[x] + 0.16(\text{mass}[x-1] + \text{mass}[x])(若 link[x]\text{link}[x] 是局部极小值则乘 0.80.8)排序,取前 4242 个最容易切开的列。

对合法区间 [l,r][l, r],用卷积网络算出最佳字符及对数概率 prob\text{prob},再结合固定字符数偏置、高度不匹配惩罚、切口粘连惩罚和内部空隙惩罚,得到该字符的总得分:

score(l,r)=prob−0.48−2.1max⁡(0,0.78−hh0)−2.1(link[l]+link[r+1])h0−gap_pen,\text{score}(l, r) = \text{prob} - 0.48 - 2.1 \max\left(0, 0.78 - \frac{h}{h_0}\right) - \frac{2.1(\text{link}[l] + \text{link}[r+1])}{h_0} - \text{gap\_pen},

其中当区间内部存在空列 gap>0\text{gap} > 0 时 gap_pen=min⁡(0.48,2.4⋅gap/h0)\text{gap\_pen} = \min(0.48, 2.4 \cdot \text{gap} / h_0),否则为 00。随后更新 dp[r+1][n+1]←dp[l][n]+score(l,r)dp[r+1][n+1] \leftarrow dp[l][n] + \text{score}(l, r) 并记录前驱和字符。

DP 结束后,在 n∈[1,9]n \in [1, 9] 中选出 dp[L][n]dp[L][n] 最大的长度 nn,将最终得分按 dp[L][n]/(n+0.35)dp[L][n] / (n + 0.35) 归一化,回溯还原字符串。对同一个灰度场的 33 个阈值偏移结果,以 s=0s = 0 时的总消耗前景质量 M0M_0 为基准,若某个高阈值版本消耗的质量 MM 低于 0.74M00.74 M_0,则施加 1.1(0.74−M/M0)1.1(0.74 - M / M_0) 的过腐蚀惩罚。最后合并全部 99 个候选结果,每多一个视图给出相同字符串就为该候选加 0.050.05 分,取总分最高者输出。

合成数据训练与权重压缩

模型用合成数据离线训练。选取系统自带的常规无衬线字体(如 Inter、Liberation Sans、DejaVu Sans、Noto Sans、Nimbus Sans、URW Gothic、FreeSans、Carlito 的 Regular 至 Bold 非斜体字重),针对题目中的字形特点做几项专门处理:数据中的 1 是一根没有顶钩和底横的纯竖线,因此训练时对 1 统一程序绘制纯竖条;对 7 补充竖干较直与斜干变体;对 3 同时覆盖圆顶与平顶写法;对 6 补充窄体直干变体;第 1616 类则由随机两字符拼接(含轻微重叠)、宽字符的残缺切片以及随机噪点团块生成。

每张合成字形依次施加小角度旋转(±9∘\pm 9^\circ)、错切(±0.14\pm 0.14)、横向缩放、低分辨率下采样(字高 10∼1910 \sim 19 像素)、高斯模糊、随机背景与线性光照梯度、高斯噪声、孤立脉冲坏点以及 25%25\% 概率的顶/底边缘亮条(模拟边角亮斑拉长包围盒的情形),最后用与 C++ 端完全一致的软前景与双线性缩放流程提取 16×1616 \times 16 样本和 log_aspect\text{log\_aspect}。因为网络只有 3218432184 个参数,直接用纯 NumPy 实现 im2col 前反向传播和 Adam 优化器即可在 CPU 上数十秒内完成训练。

训练完成后,将 88 组参数张量各自按最大绝对值对称量化到 [−127,127][-127, 127] 的 int8(存储时加 128128 变为 1∼2551 \sim 255),共 3218432184 字节。若直接 Base64 编码,仅权重字符串就超过 4290042900 字符,加上代码会超出洛谷 5120051200 字符上限。由于量化后大量权重集中在 00 附近,字节熵约 6.0 bits6.0\text{ bits},因此先做限长(≤15 bit\le 15\text{ bit})范式霍夫曼编码,将 256256 个 4-bit4\text{-bit} 码长打包在前 128128 字节,后接码流,体积降到约 2420024200 字节;再用 ASCII 4242(*)到 126126(~)的 Base85 编码(每 44 字节编为 55 字符,该字符集不含 ) 和 ",放进 R"(...)" 无需转义),权重串缩减到约 3030030300 字符,整份压缩提交代码仅约 4356843568 字符。

复杂度分析

设输入矩阵宽为 LL、高为 HH,像素总数 N=LH≤104N = LH \le 10^4。

预处理阶段,脉冲滤波、可分离极值滤波和 99 轮 6×66 \times 6 IRLS 拟合均为 O(N)O(N);单次 Otsu 阈值与连通块 BFS 也为 O(N)O(N)。

解码阶段,宽图经 select_cuts 剪枝后候选切分点数 K≤46K \le 46,最多枚举 O(K2)O(K^2) 个候选区间(实际受最大字宽与内部空隙限制远小于 K2/2K^2/2)。单个候选区间的卷积前向传播固定为 O(1)O(1) 次乘加(约 1.3×1051.3 \times 10^5 次浮点运算)。99 个视图全部执行完毕的总运行时间通常在几十毫秒以内。

模型解码时还原 3218432184 个权重耗时约 3 ms3\text{ ms}。空间上仅保存少量与图像同尺寸的数组、DP 表和网络权重,总空间复杂度为 O(LH)O(LH)。

训练与压缩脚本

脚本仅依赖 Python 3 与 numpy、pillow、scipy(pip install numpy pillow scipy),运行后读取系统无衬线字体,从零完成数据合成、训练、量化与霍夫曼 + Base85 压缩,输出 exported_weights.inc 中的 model_scales 与 model_data。

Python
import collections
import glob
import heapq
import math
import os
import random
import time

import numpy as np
from PIL import Image, ImageDraw, ImageFilter, ImageFont
from scipy.ndimage import binary_dilation

np.random.seed(2026)
random.seed(2026)

ALPHABET = "0123456789ADELX"
NUM_CLASSES = 16
SIDE = 16
C1, C2, HIDDEN = 16, 24, 64


def load_sans_fonts():
    all_fonts = sorted(
        glob.glob("/usr/share/fonts/**/*.ttf", recursive=True)
        + glob.glob("/usr/share/fonts/**/*.otf", recursive=True)
    )
    preferred = [
        "Inter-Regular", "Inter-Medium", "Inter-SemiBold", "Inter-Bold",
        "NimbusSans-Regular", "NimbusSans-Bold",
        "NimbusSansNarrow-Regular", "NimbusSansNarrow-Bold",
        "URWGothic-Book", "URWGothic-Demi",
        "LiberationSans-Regular", "LiberationSans-Bold",
        "DejaVuSans.ttf", "DejaVuSans-Bold.ttf",
        "NotoSans-Regular", "NotoSans-Medium", "NotoSans-SemiBold", "NotoSans-Bold",
        "FreeSans.ttf", "FreeSansBold.ttf",
        "Carlito-Regular", "Carlito-Bold",
    ]
    selected = sorted(set(
        f for f in all_fonts
        if any(p.lower() in os.path.basename(f).lower() for p in preferred)
        and "italic" not in os.path.basename(f).lower()
        and "oblique" not in os.path.basename(f).lower()
    ))
    font_objs = []
    for fp in selected:
        try:
            for sz in (18, 24, 30, 36):
                font_objs.append(ImageFont.truetype(fp, sz))
        except Exception:
            pass
    assert font_objs, "未找到可用无衬线字体,请手动提供本地 .ttf/.otf 路径"
    return font_objs


FONT_OBJS = load_sans_fonts()


def normalize_box(ink, l, r, t, b):
    shape = np.zeros((16, 16), dtype=np.float32)
    h_box, w_box = b - t + 1, r - l + 1
    ys = np.clip(t - 0.5 + (np.arange(14, dtype=np.float32) + 0.5) * h_box / 14.0, float(t), float(b))
    xs = np.clip(l - 0.5 + (np.arange(14, dtype=np.float32) + 0.5) * w_box / 14.0, float(l), float(r))
    y0, x0 = ys.astype(np.int32), xs.astype(np.int32)
    y1, x1 = np.minimum(y0 + 1, b), np.minimum(x0 + 1, r)
    dy, dx = (ys - y0)[:, None], (xs - x0)[None, :]
    v00, v10 = ink[y0[:, None], x0[None, :]], ink[y0[:, None], x1[None, :]]
    v01, v11 = ink[y1[:, None], x0[None, :]], ink[y1[:, None], x1[None, :]]
    a = v00 + (v10 - v00) * dx
    btm = v01 + (v11 - v01) * dx
    shape[1:15, 1:15] = a + (btm - a) * dy
    return shape


def render_plain_one():
    w, h = 52, 52
    img = Image.new("L", (w, h), 0)
    draw = ImageDraw.Draw(img)
    bar_h = random.randint(22, 36)
    bar_w = random.randint(max(3, bar_h // 9), max(6, bar_h // 4))
    x0, y0 = (w - bar_w) // 2, (h - bar_h) // 2
    draw.rectangle([x0, y0, x0 + bar_w - 1, y0 + bar_h - 1], fill=255)
    return np.asarray(img, dtype=np.uint8)


def render_procedural_seven():
    w, h = 52, 52
    img = Image.new("L", (w, h), 0)
    draw = ImageDraw.Draw(img)
    gh = random.randint(24, 36)
    gw = random.randint(int(gh * 0.34), int(gh * 0.72))
    sw = random.randint(max(3, gh // 8), max(6, gh // 4))
    x0, y0 = (w - gw) // 2, (h - gh) // 2
    x1, y1 = x0 + gw, y0 + gh
    draw.rectangle([x0, y0, x1, y0 + sw - 1], fill=255)
    bottom_x = random.uniform(x0 + gw * 0.12, x1 - sw * 0.20)
    draw.line([(x1 - sw / 2.0, y0 + sw / 2.0), (bottom_x, y1)], fill=255, width=sw)
    return np.asarray(img, dtype=np.uint8)


def render_procedural_flat_three():
    w, h = 52, 52
    img = Image.new("L", (w, h), 0)
    draw = ImageDraw.Draw(img)
    gh = random.randint(24, 36)
    gw = random.randint(int(gh * 0.44), int(gh * 0.68))
    sw = random.randint(max(3, gh // 8), max(6, gh // 4))
    x0, y0 = (w - gw) // 2, (h - gh) // 2
    x1, y1 = x0 + gw, y0 + gh
    mid_y = y0 + int(gh * random.uniform(0.42, 0.50))
    draw.rectangle([x0 + 1, y0, x1, y0 + sw - 1], fill=255)
    draw.line([(x1 - sw / 2.0, y0 + sw / 2.0), (x0 + gw * 0.42, mid_y)], fill=255, width=sw)
    draw.arc([x0, mid_y - sw // 2, x1, y1], start=260, end=155, fill=255, width=sw)
    return np.asarray(img, dtype=np.uint8)


def render_procedural_six():
    w, h = 52, 52
    img = Image.new("L", (w, h), 0)
    draw = ImageDraw.Draw(img)
    gh = random.randint(24, 36)
    gw = random.randint(int(gh * 0.42), int(gh * 0.65))
    sw = random.randint(max(3, gh // 8), max(6, gh // 4))
    x0, y0 = (w - gw) // 2, (h - gh) // 2
    x1, y1 = x0 + gw, y0 + gh
    top_x = random.uniform(x0 + sw * 0.4, x0 + gw * 0.55)
    draw.line([(top_x, y0 + sw / 2.0), (x0 + sw / 2.0, y0 + gh * 0.55)], fill=255, width=sw)
    if random.random() < 0.65:
        draw.line([(top_x, y0 + sw / 2.0), (x1 - sw * 0.3, y0 + sw * 0.8)], fill=255, width=max(2, sw - 1))
    mid_y = y0 + int(gh * random.uniform(0.40, 0.52))
    draw.ellipse([x0, mid_y, x1, y1], outline=255, width=sw)
    return np.asarray(img, dtype=np.uint8)


def render_char(ch):
    if ch == "1":
        return render_plain_one()
    if ch == "7" and random.random() < 0.55:
        return render_procedural_seven()
    if ch == "3" and random.random() < 0.35:
        return render_procedural_flat_three()
    if ch == "6" and random.random() < 0.35:
        return render_procedural_six()
    font = random.choice(FONT_OBJS)
    w, h = 52, 52
    img = Image.new("L", (w, h), 0)
    draw = ImageDraw.Draw(img)
    bbox = draw.textbbox((0, 0), ch, font=font)
    tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
    draw.text(((w - tw) // 2 - bbox[0], (h - th) // 2 - bbox[1]), ch, fill=255, font=font)
    return np.asarray(img, dtype=np.uint8)


def render_junk():
    mode = random.random()
    if mode < 0.55:
        # 拼在一起的两个字符
        c1, c2 = random.choice(ALPHABET), random.choice(ALPHABET)
        def tight(a):
            ys, xs = np.where(a > 30)
            return a[ys.min():ys.max() + 1, xs.min():xs.max() + 1] if len(ys) else a
        t1, t2 = tight(render_char(c1)), tight(render_char(c2))
        H = max(t1.shape[0], t2.shape[0]) + 10
        gap = random.randint(-2, 4)
        W = t1.shape[1] + t2.shape[1] + max(0, gap) + 12
        canvas = np.zeros((H, W), dtype=np.uint8)
        y1, y2 = (H - t1.shape[0]) // 2, (H - t2.shape[0]) // 2
        x1, x2 = 6, max(6, 6 + t1.shape[1] + gap)
        canvas[y1:y1 + t1.shape[0], x1:x1 + t1.shape[1]] = np.maximum(
            canvas[y1:y1 + t1.shape[0], x1:x1 + t1.shape[1]], t1)
        canvas[y2:y2 + t2.shape[0], x2:x2 + t2.shape[1]] = np.maximum(
            canvas[y2:y2 + t2.shape[0], x2:x2 + t2.shape[1]], t2)
        return canvas
    if mode < 0.80:
        # 切坏的局部笔画
        ch = random.choice("02345689ADEX")
        a = render_char(ch)
        ys, xs = np.where(a > 30)
        if not len(ys):
            return a
        x0, x1 = xs.min(), xs.max()
        cut = x0 + int((x1 - x0 + 1) * random.uniform(0.38, 0.65))
        b = a.copy()
        if random.random() < 0.5:
            b[:, cut:] = 0
        else:
            b[:, :cut] = 0
        ys2, xs2 = np.where(b > 30)
        if len(xs2) > 0 and (xs2.max() - xs2.min() + 1) <= 3:
            b[ys2.min():ys2.min() + 3, max(0, xs2.min() - 3):min(b.shape[1], xs2.max() + 4)] = 200
        return b
    # 随机噪点团块
    w, h = 52, 52
    img = Image.new("L", (w, h), 0)
    draw = ImageDraw.Draw(img)
    for _ in range(random.randint(1, 3)):
        x0, y0 = random.randint(10, 32), random.randint(10, 32)
        draw.ellipse([x0, y0, x0 + random.randint(3, 14), y0 + random.randint(3, 14)],
                     fill=random.randint(140, 255))
    return np.asarray(img, dtype=np.uint8)


def degrade_and_extract(img_arr, allow_edge_glare=True):
    h, w = img_arr.shape
    pil = Image.fromarray(img_arr, mode="L")
    if random.random() < 0.15:
        pil = pil.filter(ImageFilter.MaxFilter(3))

    angle = random.uniform(-9.0, 9.0)
    shear = random.uniform(-0.14, 0.14)
    sx = random.uniform(0.78, 1.22)
    rad = math.radians(angle)
    ca, sa = math.cos(rad), math.sin(rad)
    cx, cy = w / 2.0, h / 2.0
    a, b = ca / sx, (sa + shear * ca) / sx
    d, e = -sa, ca
    c, f = cx - a * cx - b * cy, cy - d * cx - e * cy
    pil = pil.transform((w, h), Image.Transform.AFFINE, (a, b, c, d, e, f),
                        resample=Image.Resampling.BILINEAR)

    arr = np.asarray(pil, dtype=np.float32)
    ys, xs = np.where(arr > 25)
    if len(ys) < 4:
        return None
    crop = arr[ys.min():ys.max() + 1, xs.min():xs.max() + 1]
    ch, cw = crop.shape
    target_h = random.randint(10, 19)
    target_w = max(2, int(round(cw * target_h / max(1.0, float(ch)))))
    small = Image.fromarray(crop.astype(np.uint8), mode="L").resize(
        (target_w, target_h), Image.Resampling.BILINEAR)

    pad_x = 3
    pad_top, pad_bot = random.randint(2, 5), random.randint(2, 5)
    canvas = Image.new("L", (target_w + 2 * pad_x, target_h + pad_top + pad_bot), 0)
    canvas.paste(small, (pad_x, pad_top))
    canvas = canvas.filter(ImageFilter.GaussianBlur(radius=random.uniform(0.3, 1.15)))
    g = np.asarray(canvas, dtype=np.float32)

    bg = random.uniform(50.0, 160.0)
    fg_boost = random.uniform(70.0, 165.0)
    gx, gy = random.uniform(-18.0, 18.0), random.uniform(-18.0, 18.0)
    yy, xx = np.mgrid[0:g.shape[0], 0:g.shape[1]]
    grad = gx * (xx / max(1, g.shape[1] - 1) - 0.5) + gy * (yy / max(1, g.shape[0] - 1) - 0.5)
    noise = np.random.normal(0.0, random.uniform(2.0, 10.0), g.shape).astype(np.float32)
    sim = bg + grad + (g / 255.0) * fg_boost + noise

    if allow_edge_glare and random.random() < 0.25:
        glare_val = bg + fg_boost * random.uniform(0.65, 1.0)
        glare_len = random.randint(2, max(2, target_w))
        glare_x0 = random.randint(pad_x, max(pad_x, pad_x + target_w - glare_len))
        if random.random() < 0.5:
            sim[0:random.randint(1, 2), glare_x0:glare_x0 + glare_len] = glare_val
        else:
            sim[-random.randint(1, 2):, glare_x0:glare_x0 + glare_len] = glare_val

    if random.random() < 0.25:
        mask = np.random.rand(*sim.shape) < random.uniform(0.01, 0.035)
        sim[mask] += np.random.uniform(-45.0, 45.0, size=int(mask.sum()))
    sim = np.clip(sim, 0.0, 255.0)

    lo, hi = np.percentile(sim, 15), np.percentile(sim, 96)
    contrast = max(12.0, hi - lo)
    thr = (lo + hi) * 0.5 + random.uniform(-0.16, 0.14) * contrast
    spread = max(12.0, contrast * 0.92)
    ink_raw = np.clip(0.5 + (sim - thr) / spread, 0.0, 1.0)
    core = sim >= thr
    if core.sum() < 4:
        return None
    halo = binary_dilation(core, structure=np.ones((3, 3))) & (~core)
    ink = np.zeros_like(ink_raw)
    ink[core] = ink_raw[core]
    ink[halo] = np.minimum(ink_raw[halo], 0.48)

    cy_idx, cx_idx = np.where(core)
    t, b = int(cy_idx.min()), int(cy_idx.max())
    l, r = int(cx_idx.min()), int(cx_idx.max())
    bw, bh = r - l + 1, b - t + 1
    if bh < 3 or bw < 1:
        return None
    return normalize_box(ink, l, r, t, b), float(np.clip(math.log(bw / float(bh)), -3.0, 1.5))


def im2col_s2_p1(x):
    B, H, W, C = x.shape
    xp = np.pad(x, ((0, 0), (1, 2), (1, 2), (0, 0)), mode="constant")
    oh, ow = H // 2, W // 2
    cols = np.empty((B, oh, ow, 16, C), dtype=np.float32)
    idx = 0
    for dy in range(4):
        for dx in range(4):
            cols[:, :, :, idx, :] = xp[:, dy:dy + 2 * oh:2, dx:dx + 2 * ow:2, :]
            idx += 1
    return cols.reshape(B * oh * ow, 16 * C)


def col2im_s2_p1(dcols, B, H, W, C):
    oh, ow = H // 2, W // 2
    dcols = dcols.reshape(B, oh, ow, 16, C)
    dxp = np.zeros((B, H + 3, W + 3, C), dtype=np.float32)
    idx = 0
    for dy in range(4):
        for dx in range(4):
            dxp[:, dy:dy + 2 * oh:2, dx:dx + 2 * ow:2, :] += dcols[:, :, :, idx, :]
            idx += 1
    return dxp[:, 1:H + 1, 1:W + 1, :]


def forward(xb, ab, ps):
    W1, b1, W2, b2, W3, b3, W4, b4 = ps
    B = xb.shape[0]
    col1 = im2col_s2_p1(xb[:, :, :, None])
    z1 = col1 @ W1 + b1
    a1 = np.maximum(0.0, z1)
    col2 = im2col_s2_p1(a1.reshape(B, 8, 8, C1))
    z2 = col2 @ W2 + b2
    a2 = np.maximum(0.0, z2)
    flat = np.concatenate([a2.reshape(B, 384), ab[:, None]], axis=1)
    z3 = flat @ W3 + b3
    a3 = np.maximum(0.0, z3)
    logits = a3 @ W4 + b4
    return logits, (col1, z1, col2, z2, flat, z3, a3)


def compress_huffman_base85(raw_bytes):
    freq = collections.Counter(raw_bytes)
    heap = [[w, [sym]] for sym, w in freq.items()]
    heapq.heapify(heap)
    lengths = [0] * 256
    while len(heap) > 1:
        w1, s1 = heapq.heappop(heap)
        w2, s2 = heapq.heappop(heap)
        for s in s1:
            lengths[s] += 1
        for s in s2:
            lengths[s] += 1
        heapq.heappush(heap, [w1 + w2, s1 + s2])

    if max(lengths) > 15:
        syms = sorted(freq.keys(), key=lambda s: (freq[s], s))
        items = [(freq[s], [s]) for s in syms]
        cur = items[:]
        for _ in range(14):
            cur.sort(key=lambda x: x[0])
            pkgs = [(cur[k][0] + cur[k + 1][0], cur[k][1] + cur[k + 1][1])
                    for k in range(0, len(cur) - 1, 2)]
            cur = items + pkgs
        cur.sort(key=lambda x: x[0])
        lengths = [0] * 256
        for _, slist in cur[:2 * len(syms) - 2]:
            for s in slist:
                lengths[s] += 1

    bl_count = [0] * 16
    for l in lengths:
        if l > 0:
            bl_count[l] += 1
    next_code, code = [0] * 16, 0
    for bits in range(1, 16):
        code = (code + bl_count[bits - 1]) << 1
        next_code[bits] = code
    codes = [0] * 256
    for sym in range(256):
        if lengths[sym] > 0:
            codes[sym] = next_code[lengths[sym]]
            next_code[lengths[sym]] += 1

    payload = bytearray()
    for i in range(0, 256, 2):
        payload.append(lengths[i] | (lengths[i + 1] << 4))
    bitbuf, bitcnt = 0, 0
    for b in raw_bytes:
        l = lengths[b]
        bitbuf = (bitbuf << l) | codes[b]
        bitcnt += l
        while bitcnt >= 8:
            bitcnt -= 8
            payload.append((bitbuf >> bitcnt) & 255)
    if bitcnt > 0:
        payload.append((bitbuf << (8 - bitcnt)) & 255)
    while len(payload) % 4 != 0:
        payload.append(0)

    chars = []
    for i in range(0, len(payload), 4):
        v = (payload[i] << 24) | (payload[i + 1] << 16) | (payload[i + 2] << 8) | payload[i + 3]
        chunk = [0] * 5
        for k in range(4, -1, -1):
            chunk[k] = chr(42 + (v % 85))
            v //= 85
        chars.extend(chunk)
    s = "".join(chars)
    return "\n".join(s[i:i + 120] for i in range(0, len(s), 120))


def main():
    t0 = time.time()
    X_img, X_asp, Y_lbl = [], [], []
    for cls_idx in range(NUM_CLASSES):
        cnt = 0
        while cnt < 2400:
            arr = render_char(ALPHABET[cls_idx]) if cls_idx < 15 else render_junk()
            res = degrade_and_extract(arr, allow_edge_glare=(cls_idx < 15))
            if res is None:
                continue
            X_img.append(res[0])
            X_asp.append(res[1])
            Y_lbl.append(cls_idx)
            cnt += 1

    X_img = np.array(X_img, dtype=np.float32)
    X_asp = np.array(X_asp, dtype=np.float32)
    Y_lbl = np.array(Y_lbl, dtype=np.int32)
    perm = np.random.permutation(len(Y_lbl))
    X_img, X_asp, Y_lbl = X_img[perm], X_asp[perm], Y_lbl[perm]
    val_n = len(Y_lbl) // 10
    X_tr, A_tr, Y_tr = X_img[val_n:], X_asp[val_n:], Y_lbl[val_n:]
    X_va, A_va, Y_va = X_img[:val_n], X_asp[:val_n], Y_lbl[:val_n]
    print(f"Dataset ready ({time.time() - t0:.1f}s): train={len(Y_tr)}, val={len(Y_va)}")

    params = [
        np.random.randn(16, C1).astype(np.float32) * math.sqrt(2.0 / 16),
        np.zeros(C1, dtype=np.float32),
        np.random.randn(16 * C1, C2).astype(np.float32) * math.sqrt(2.0 / (16 * C1)),
        np.zeros(C2, dtype=np.float32),
        np.random.randn(16 * C2 + 1, HIDDEN).astype(np.float32) * math.sqrt(2.0 / (16 * C2 + 1)),
        np.zeros(HIDDEN, dtype=np.float32),
        np.random.randn(HIDDEN, NUM_CLASSES).astype(np.float32) * math.sqrt(2.0 / HIDDEN),
        np.zeros(NUM_CLASSES, dtype=np.float32),
    ]
    m_adam = [np.zeros_like(p) for p in params]
    v_adam = [np.zeros_like(p) for p in params]
    epochs, batch, wd, step = 24, 256, 1e-4, 0

    for ep in range(1, epochs + 1):
        lr = 2e-4 + 0.5 * (3e-3 - 2e-4) * (1.0 + math.cos(math.pi * (ep - 1) / epochs))
        idx = np.random.permutation(len(Y_tr))
        for s in range(0, len(Y_tr), batch):
            bi = idx[s:s + batch]
            xb, ab, yb = X_tr[bi], A_tr[bi], Y_tr[bi]
            B = len(bi)
            logits, (col1, z1, col2, z2, flat, z3, a3) = forward(xb, ab, params)
            exps = np.exp(logits - logits.max(axis=1, keepdims=True))
            probs = exps / exps.sum(axis=1, keepdims=True)
            target = np.full((B, NUM_CLASSES), 0.02 / NUM_CLASSES, dtype=np.float32)
            target[np.arange(B), yb] += 0.98
            dlogits = (probs - target) / B

            W1, b1, W2, b2, W3, b3, W4, b4 = params
            dW4, db4 = a3.T @ dlogits + wd * W4, dlogits.sum(axis=0)
            dz3 = (dlogits @ W4.T) * (z3 > 0)
            dW3, db3 = flat.T @ dz3 + wd * W3, dz3.sum(axis=0)
            dz2 = ((dz3 @ W3.T)[:, :384].reshape(B * 16, C2)) * (z2 > 0)
            dW2, db2 = col2.T @ dz2 + wd * W2, dz2.sum(axis=0)
            dz1 = (col2im_s2_p1(dz2 @ W2.T, B, 8, 8, C1).reshape(B * 64, C1)) * (z1 > 0)
            dW1, db1 = col1.T @ dz1 + wd * W1, dz1.sum(axis=0)

            grads = [dW1, db1, dW2, db2, dW3, db3, dW4, db4]
            step += 1
            bc1, bc2 = 1.0 - 0.9 ** step, 1.0 - 0.999 ** step
            for i in range(8):
                m_adam[i] = 0.9 * m_adam[i] + 0.1 * grads[i]
                v_adam[i] = 0.999 * v_adam[i] + 0.001 * (grads[i] * grads[i])
                params[i] -= lr * (m_adam[i] / bc1) / (np.sqrt(v_adam[i] / bc2) + 1e-8)

        if ep % 6 == 0 or ep == epochs:
            val_acc = (forward(X_va, A_va, params)[0].argmax(axis=1) == Y_va).mean()
            print(f"Epoch {ep:2d}/{epochs} | val_acc={val_acc * 100:.2f}%")

    scales, qbytes = [], bytearray()
    for p in params:
        flat = p.reshape(-1)
        sc = float(np.max(np.abs(flat))) / 127.0
        q = np.clip(np.round(flat / sc), -127, 127).astype(np.int32)
        scales.append(sc)
        qbytes.extend((q + 128).tolist())

    b85_text = compress_huffman_base85(bytes(qbytes))
    with open("exported_weights.inc", "w") as f:
        f.write("constexpr array<float, 8> model_scales{"
                + ",".join(f"{s:.8g}f" for s in scales) + "};\n")
        f.write('constexpr string_view model_data = R"(\n' + b85_text + '\n)";\n')
    print(f"Exported exported_weights.inc (model_data len={len(b85_text)})")


if __name__ == "__main__":
    main()

排查错误测试点时,可将输入矩阵放大为每个像素 24×2424 \times 24 的色块灰度图查看,避免图片查看器插值模糊:

Python
import numpy as np
from PIL import Image

lines = open("case.in").read().strip().splitlines()
w, h = map(int, lines[0].split())
grid = np.array([[int(x) for x in row.split()] for row in lines[1:]], dtype=np.uint8)
Image.fromarray(np.repeat(np.repeat(grid, 24, axis=0), 24, axis=1), mode="L").save("case.png")

参考代码

以下代码使用 GNU C++20,将训练脚本生成的 model_scales 和 model_data 填入对应位置即可编译运行。洛谷评测通过记录。

C++
#include <bits/stdc++.h>
using namespace std;

namespace {

constexpr string_view alphabet = "0123456789ADELX";
constexpr int side = 16;
constexpr int c1 = 16, c2 = 24, hidden = 64, classes = 16;
constexpr int max_chars = 9;
constexpr float impossible = -1.0e20f;

// 由训练脚本 exported_weights.inc 导出。
constexpr array<float, 8> model_scales{/* 8 个量化缩放系数 */};
constexpr string_view model_data = R"(
/* 范式霍夫曼 + Base85 压缩后的权重字符串 */
)";

struct Model {
    array<float, 16 * c1> conv1;
    array<float, c1> bias1;
    array<float, 16 * c1 * c2> conv2;
    array<float, c2> bias2;
    array<float, (16 * c2 + 1) * hidden> dense1;
    array<float, hidden> bias3;
    array<float, hidden * classes> dense2;
    array<float, classes> bias4;

    Model() {
        vector<uint8_t> raw;
        uint32_t acc = 0;
        int k = 0;
        for (char ch : model_data) {
            if (ch < 42 || ch > 126) continue;
            acc = acc * 85 + static_cast<uint32_t>(ch - 42);
            if (++k == 5) {
                for (int s = 24; s >= 0; s -= 8)
                    raw.push_back(static_cast<uint8_t>((acc >> s) & 255u));
                acc = 0;
                k = 0;
            }
        }
        // 前 128 字节保存 256 个 4-bit 霍夫曼码长,重建范式解码表。
        int len[256], cnt[16]{}, fc[16]{}, fi[16]{}, sym[256];
        for (int i = 0; i < 128; ++i) {
            len[2 * i] = raw[i] & 15;
            len[2 * i + 1] = raw[i] >> 4;
        }
        for (int i = 0; i < 256; ++i)
            if (len[i]) ++cnt[len[i]];
        for (int b = 1, c = 0, idx = 0; b < 16; ++b) {
            c = (c + cnt[b - 1]) << 1;
            fc[b] = c;
            fi[b] = idx;
            idx += cnt[b];
        }
        int pos[16];
        memcpy(pos, fi, sizeof(pos));
        for (int i = 0; i < 256; ++i)
            if (len[i]) sym[pos[len[i]]++] = i;

        vector<int> bytes;
        bytes.reserve(32184);
        size_t bp = 128 * 8;
        while (bytes.size() < 32184) {
            int c = 0;
            for (int b = 1; b < 16; ++b) {
                c = (c << 1) | ((raw[bp >> 3] >> (7 - (bp & 7))) & 1);
                ++bp;
                if (c - fc[b] < cnt[b]) {
                    bytes.push_back(sym[fi[b] + c - fc[b]] - 128);
                    break;
                }
            }
        }
        size_t offset = 0;
        auto read = [&](auto& weights, float scale) {
            for (float& w : weights) w = scale * bytes[offset++];
        };
        read(conv1, model_scales[0]);
        read(bias1, model_scales[1]);
        read(conv2, model_scales[2]);
        read(bias2, model_scales[3]);
        read(dense1, model_scales[4]);
        read(bias3, model_scales[5]);
        read(dense2, model_scales[6]);
        read(bias4, model_scales[7]);
    }

    template <int S, int C, int D>
    static auto convolution(const array<float, S * S * C>& input,
                            const array<float, 16 * C * D>& weights,
                            const array<float, D>& bias) {
        constexpr int out_side = S / 2;
        array<float, out_side * out_side * D> output;
        for (int y = 0; y < out_side; ++y) {
            for (int x = 0; x < out_side; ++x) {
                auto block = bias;
                for (int dy = 0; dy < 4; ++dy) {
                    int row = 2 * y + dy - 1;
                    if (row < 0 || row >= S) continue;
                    for (int dx = 0; dx < 4; ++dx) {
                        int col = 2 * x + dx - 1;
                        if (col < 0 || col >= S) continue;
                        const float* values = &input[(row * S + col) * C];
                        const float* w_pix = &weights[(dy * 4 + dx) * C * D];
                        for (int i = 0; i < C; ++i) {
                            float v = values[i];
                            for (int j = 0; j < D; ++j) block[j] += v * w_pix[i * D + j];
                        }
                    }
                }
                float* dst = &output[(y * out_side + x) * D];
                for (int j = 0; j < D; ++j) dst[j] = max(0.0f, block[j]);
            }
        }
        return output;
    }

    // 仅在前 15 类中选字符,softmax 分母包含第 16 类(非字符类)。
    pair<char, float> classify(const array<float, side * side>& shape, float log_aspect) const {
        auto layer1 = convolution<side, 1, c1>(shape, conv1, bias1);
        auto layer2 = convolution<side / 2, c1, c2>(layer1, conv2, bias2);
        auto mid = bias3;
        for (size_t i = 0; i < layer2.size(); ++i)
            for (int j = 0; j < hidden; ++j) mid[j] += layer2[i] * dense1[i * hidden + j];
        auto logits = bias4;
        for (int i = 0; i < hidden; ++i) {
            float v = max(0.0f, mid[i] + log_aspect * dense1[layer2.size() * hidden + i]);
            for (int j = 0; j < classes; ++j) logits[j] += v * dense2[i * classes + j];
        }
        int best = int(max_element(logits.begin(), logits.begin() + alphabet.size()) - logits.begin());
        float peak = *max_element(logits.begin(), logits.end());
        float sum = 0.0f;
        for (float logit : logits) sum += exp((logit - peak) / 1.10f);
        return {alphabet[best], (logits[best] - peak) / 1.10f - log(sum)};
    }
};

struct Image {
    int width, height;
    vector<float> pixels;
    Image(int w, int h) : width(w), height(h), pixels(w * h) {}
    float& at(int x, int y) { return pixels[y * width + x]; }
    float at(int x, int y) const { return pixels[y * width + x]; }
};

Image suppress_impulses(const Image& input) {
    Image output = input;
    for (int y = 0; y < input.height; ++y) {
        for (int x = 0; x < input.width; ++x) {
            float lo = 255, hi = 0;
            for (int yy = max(0, y - 1); yy <= min(y + 1, input.height - 1); ++yy)
                for (int xx = max(0, x - 1); xx <= min(x + 1, input.width - 1); ++xx) {
                    if (xx == x && yy == y) continue;
                    lo = min(lo, input.at(xx, yy));
                    hi = max(hi, input.at(xx, yy));
                }
            output.at(x, y) = clamp(input.at(x, y), lo - 22, hi + 22);
        }
    }
    return output;
}

Image extremum_filter(const Image& input, int radius, bool dilate) {
    Image horizontal(input.width, input.height), output(input.width, input.height);
    auto update = [dilate](float a, float b) { return dilate ? max(a, b) : min(a, b); };
    for (int y = 0; y < input.height; ++y)
        for (int x = 0; x < input.width; ++x) {
            float v = input.at(x, y);
            for (int xx = max(0, x - radius); xx <= min(x + radius, input.width - 1); ++xx)
                v = update(v, input.at(xx, y));
            horizontal.at(x, y) = v;
        }
    for (int y = 0; y < input.height; ++y)
        for (int x = 0; x < input.width; ++x) {
            float v = horizontal.at(x, y);
            for (int yy = max(0, y - radius); yy <= min(y + radius, input.height - 1); ++yy)
                v = update(v, horizontal.at(x, yy));
            output.at(x, y) = v;
        }
    return output;
}

Image correct_background(const Image& input) {
    int radius = clamp(min(input.width, input.height) / 7, 2, 7);
    Image base = extremum_filter(extremum_filter(input, radius, false), radius, true);
    Image output(input.width, input.height);
    for (size_t i = 0; i < output.pixels.size(); ++i)
        output.pixels[i] = input.pixels[i] - 0.86f * base.pixels[i];
    return output;
}

Image correct_gradient(const Image& input) {
    using Basis = array<double, 6>;
    vector<Basis> basis;
    for (int y = 0; y < input.height; ++y)
        for (int x = 0; x < input.width; ++x) {
            double u = 2.0 * x / (input.width - 1) - 1;
            double v = 2.0 * y / (input.height - 1) - 1;
            basis.push_back({1, u, v, u * u, u * v, v * v});
        }
    auto predict = [](const Basis& a, const Basis& b) {
        double v = 0;
        for (int j = 0; j < 6; ++j) v += a[j] * b[j];
        return v;
    };
    Basis fit{};
    for (int it = 0; it < 9; ++it) {
        double a[6][7]{};
        for (size_t i = 0; i < basis.size(); ++i) {
            double val = input.pixels[i], res = val - predict(basis[i], fit);
            double w = (res > 0 ? 0.23 : 0.77) / max(4.0, abs(res));
            for (int j = 0; j < 6; ++j) {
                double p = basis[i][j] * w;
                for (int k = 0; k < 6; ++k) a[j][k] += p * basis[i][k];
                a[j][6] += p * val;
            }
        }
        for (int j = 0; j < 6; ++j) {
            double pivot = a[j][j];
            for (int k = j; k <= 6; ++k) a[j][k] /= pivot;
            for (int r = 0; r < 6; ++r) {
                if (r == j) continue;
                double f = a[r][j];
                for (int k = j; k <= 6; ++k) a[r][k] -= f * a[j][k];
            }
        }
        for (int j = 0; j < 6; ++j) fit[j] = a[j][6];
    }
    Image corrected = input;
    for (size_t i = 0; i < basis.size(); ++i)
        corrected.pixels[i] = clamp(float(input.pixels[i] - (predict(basis[i], fit) - fit[0])), 0.0f, 255.0f);
    return corrected;
}

struct Levels { float threshold, contrast; };

Levels otsu(const Image& input) {
    array<int, 256> hist{};
    double total = 0.0;
    for (float v : input.pixels) {
        int bin = clamp(int(lround(v)), 0, 255);
        ++hist[bin];
        total += bin;
    }
    int count = int(input.pixels.size()), lc = 0;
    double ls = 0.0, best = -1, dark = total / count, bright = dark;
    for (int bin = 0; bin < 255; ++bin) {
        lc += hist[bin];
        ls += double(bin) * hist[bin];
        int rc = count - lc;
        if (!lc || !rc || !hist[bin]) continue;
        double lo = ls / lc, hi = (total - ls) / rc;
        double score = double(lc) * rc * (hi - lo) * (hi - lo);
        if (score > best) { best = score; dark = lo; bright = hi; }
    }
    return {float((dark + bright) * 0.5), max(1.0f, float(bright - dark))};
}

struct Component { vector<int> cells; int top, bottom; };

struct Foreground {
    Image ink;
    vector<int> top, bottom;
    vector<float> mass, link;
    int typical_height = 0, total_mass = 0;
    Foreground(int w, int h) : ink(w, h), top(w, h), bottom(w, -1), mass(w), link(w + 1) {}
};

Foreground make_foreground(const Image& input, float threshold, float contrast) {
    int w = input.width, h = input.height;
    Foreground fg(w, h);
    vector<char> active(w * h);
    for (int i = 0; i < w * h; ++i) active[i] = input.pixels[i] >= threshold;

    vector<Component> comps;
    int largest = 0;
    for (int i = 0; i < w * h; ++i) {
        if (!active[i]) continue;
        Component comp{{i}, i / w, i / w};
        active[i] = 0;
        for (size_t head = 0; head < comp.cells.size(); ++head) {
            int cur = comp.cells[head], y = cur / w, x = cur % w;
            comp.top = min(comp.top, y);
            comp.bottom = max(comp.bottom, y);
            for (int yy = max(0, y - 1); yy <= min(y + 1, h - 1); ++yy)
                for (int xx = max(0, x - 1); xx <= min(x + 1, w - 1); ++xx) {
                    int nxt = yy * w + xx;
                    if (!active[nxt]) continue;
                    active[nxt] = 0;
                    comp.cells.push_back(nxt);
                }
        }
        largest = max(largest, int(comp.cells.size()));
        comps.push_back(move(comp));
    }

    vector<char> core(w * h);
    const int min_area = min(7, max(2, largest / 45));
    vector<int> hmass(h + 1);
    for (const auto& c : comps) {
        int area = int(c.cells.size());
        if (area < min_area && area < largest) continue;
        for (int i : c.cells) core[i] = 1;
        fg.total_mass += area;
        hmass[c.bottom - c.top + 1] += area;
    }
    for (int height = 1, seen = 0; height <= h; ++height) {
        seen += hmass[height];
        if (seen * 5 >= fg.total_mass * 3) { fg.typical_height = max(3, height); break; }
    }

    const float spread = max(12.0f, contrast * 0.92f);
    for (int y = 0; y < h; ++y) {
        for (int x = 0; x < w; ++x) {
            float v = clamp(0.5f + (input.at(x, y) - threshold) / spread, 0.0f, 1.0f);
            if (core[y * w + x]) {
                fg.top[x] = min(fg.top[x], y);
                fg.bottom[x] = max(fg.bottom[x], y);
                fg.mass[x] += v;
                fg.ink.at(x, y) = v;
                continue;
            }
            if (v <= 0.02f) continue;
            for (int yy = max(0, y - 1); yy <= min(h - 1, y + 1); ++yy)
                for (int xx = max(0, x - 1); xx <= min(w - 1, x + 1); ++xx)
                    if (core[yy * w + xx]) fg.ink.at(x, y) = min(v, 0.48f);
        }
    }
    for (int cut = 1; cut < w; ++cut)
        for (int y = 0; y < h; ++y)
            if (core[y * w + cut - 1] && core[y * w + cut])
                fg.link[cut] += min(fg.ink.at(cut - 1, y), fg.ink.at(cut, y));
    return fg;
}

struct Box { int left, right, top, bottom; };

array<float, side * side> normalize(const Image& ink, Box b) {
    array<float, side * side> shape{};
    for (int y = 0; y < side - 2; ++y) {
        float iy = clamp(b.top - 0.5f + (y + 0.5f) * (b.bottom - b.top + 1) / (side - 2),
                         float(b.top), float(b.bottom));
        int y0 = int(iy), y1 = min(y0 + 1, b.bottom);
        for (int x = 0; x < side - 2; ++x) {
            float ix = clamp(b.left - 0.5f + (x + 0.5f) * (b.right - b.left + 1) / (side - 2),
                             float(b.left), float(b.right));
            int x0 = int(ix), x1 = min(x0 + 1, b.right);
            float a = lerp(ink.at(x0, y0), ink.at(x1, y0), ix - x0);
            float btm = lerp(ink.at(x0, y1), ink.at(x1, y1), ix - x0);
            shape[(y + 1) * side + x + 1] = lerp(a, btm, iy - y0);
        }
    }
    return shape;
}

struct Result { string word; float score = impossible; float used_mass = 0; };

vector<char> select_cuts(const Foreground& fg) {
    const int w = fg.ink.width;
    vector<char> sel(w + 1, 1);
    if (w <= 46) return sel;
    fill(sel.begin(), sel.end(), 0);
    sel.front() = sel.back() = 1;
    vector<pair<float, int>> ranked;
    for (int x = 1; x < w; ++x) {
        if (fg.mass[x - 1] == 0 || fg.mass[x] == 0) { sel[x] = 1; continue; }
        float pri = fg.link[x] + 0.16f * (fg.mass[x - 1] + fg.mass[x]);
        if (fg.link[x] <= min(fg.link[x - 1], fg.link[x + 1])) pri *= 0.8f;
        ranked.emplace_back(pri, x);
    }
    sort(ranked.begin(), ranked.end());
    for (int i = 0; i < min(42, int(ranked.size())); ++i) sel[ranked[i].second] = 1;
    return sel;
}

Result decode(const Foreground& fg, const Model& model) {
    int w = fg.ink.width, h = fg.ink.height, typical = fg.typical_height;
    if (!fg.total_mass) return {};
    vector<char> cuts = select_cuts(fg);
    struct State { float score = impossible, used_mass = 0; int previous = -1; char letter = 0; };
    vector<array<State, max_chars + 1>> dp(w + 1);
    dp[0][0].score = 0;

    for (int l = 0; l < w; ++l) {
        for (int n = 0; n <= max_chars; ++n) {
            const auto& st = dp[l][n];
            float sc = st.score - 4.6f * fg.mass[l] / typical;
            if (sc > dp[l + 1][n].score) dp[l + 1][n] = {sc, st.used_mass, l, 0};
        }
        if (!cuts[l] || !fg.mass[l]) continue;
        bool reachable = false;
        for (int n = 0; n < max_chars; ++n) reachable |= (dp[l][n].score > impossible);
        if (!reachable) continue;

        int top = h, bottom = -1, gap = 0, largest_gap = 0;
        float mass = 0.0f;
        for (int r = l; r < w; ++r) {
            if (!fg.mass[r]) { ++gap; continue; }
            largest_gap = max(largest_gap, gap);
            gap = 0;
            if (largest_gap > max(2, typical / 3)) break;
            top = min(top, fg.top[r]);
            bottom = max(bottom, fg.bottom[r]);
            mass += fg.mass[r];
            int width = r - l + 1, height = bottom - top + 1;
            if (width > max(4, int(1.9f * typical))) break;
            if (!cuts[r + 1]) continue;
            if (height < max(3, int(0.42f * typical)) || width > 1.72f * height + 0.5f) continue;

            auto shape = normalize(fg.ink, {l, r, top, bottom});
            auto [letter, prob] = model.classify(shape, clamp(log(float(width) / height), -3.0f, 1.5f));
            float mismatch = max(0.0f, 0.78f - float(height) / typical);
            float cut = (fg.link[l] + fg.link[r + 1]) * 2.1f / typical;
            float glyph_score = prob - 0.48f - 2.1f * mismatch - cut;
            if (largest_gap) glyph_score -= min(0.48f, 2.4f * largest_gap / typical);

            for (int n = 0; n < max_chars; ++n) {
                float sc = dp[l][n].score + glyph_score;
                if (sc > dp[r + 1][n + 1].score)
                    dp[r + 1][n + 1] = {sc, dp[l][n].used_mass + mass, l, letter};
            }
        }
    }

    int n = 1;
    for (int k = 2; k <= max_chars; ++k)
        if (dp[w][k].score > dp[w][n].score) n = k;
    Result res;
    if (dp[w][n].previous < 0) return res;
    res.score = dp[w][n].score / (n + 0.35f);
    res.used_mass = dp[w][n].used_mass;
    for (int x = w; x > 0;) {
        auto st = dp[x][n];
        if (st.letter) { res.word.push_back(st.letter); --n; }
        x = st.previous;
    }
    reverse(res.word.begin(), res.word.end());
    return res;
}

string recognize(const Image& input, const Model& model) {
    Image raw = suppress_impulses(input);
    array<Image, 3> fields{raw, correct_background(raw), correct_gradient(raw)};
    vector<Result> results;
    for (const Image& field : fields) {
        auto [threshold, contrast] = otsu(field);
        vector<Result> variants;
        for (float shift : {0.0f, -0.15f, 0.12f}) {
            Foreground fg = make_foreground(field, threshold + shift * contrast, contrast);
            Result res = decode(fg, model);
            if (!res.word.empty()) variants.push_back(move(res));
        }
        if (variants.empty()) continue;
        float ref = variants.front().used_mass;
        for (Result& res : variants) {
            float erosion = max(0.0f, 0.74f - res.used_mass / max(1.0f, ref));
            res.score -= 1.1f * erosion;
            results.push_back(move(res));
        }
    }
    Result best;
    for (const auto& res : results) {
        float sc = res.score;
        for (const auto& other : results)
            if (other.word == res.word) sc += 0.05f;
        if (sc > best.score) best = {res.word, sc, res.used_mass};
    }
    return best.word.empty() ? "1" : best.word;
}

}  // namespace

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int width, height;
    if (!(cin >> width >> height)) return 0;
    Image image(width, height);
    for (float& pixel : image.pixels) cin >> pixel;
    const Model model;
    string word = recognize(image, model);
    cout << word.size() << '\n' << word << '\n';
}
原文