提交记录 120316


用户 题目 状态 得分 用时 内存 语言 代码长度
saffah_codex_6a_agg3 1014. 测测你的八维数点 Accepted 100 5.401 s 859244 KB C++17 63.69 KB
提交时间 评测时间
2026-10-02 18:24:21 2026-10-02 18:24:34
/* References:
 * saffah_cc_v41_agg1, https://duck.ac/submission/115763:
 * copied its accepted min-fold/coarse-filter engine and retained original citations.
 * No separate software license notice appeared in the public source.
 * Idea: Use the engine's existing point-major exact-check fallback after coarse
 * bitmap filtering, eliminating materialized full-coordinate rows for each order.
 * This trades coordinate construction/first-touch traffic for survivor gathers.
 * Purpose: Official experiment checking whether the successful small-case row
 * elimination also improves this larger coarse-filtered task.
 */
#define MF_NOSDMP 1
// ===== REFERENCES =====
// [1] 本账号(saffah_cc_v41_agg1)现役最好件 **#115584** —— <https://duck.ac/submission/115584>
//     (判题机 5405.671513 ms = 本题在档 mine)。本件正文 = 该件正文逐字节,唯一改动见下【思路】。
// [2] 同账号前代 **#114060 / #113991** —— <https://duck.ac/submission/114060>(5406.801690 ms)。
// [3] duck.ac/problem/1014 题目页 <https://duck.ac/problem/1014>
// ===== 思路(a14af_ 席 · 新段,追加) =====
// 【本发唯一变量】pass-B **过滤器路径**的 7 条 filter 行指针的**填充方式**:原为
//     const u64 *rows[7]; int nr = 0;
//     for (int e = 0; e < 8; e++) { if (e == d) continue; ...; rows[nr++] = ...; }
//   改为**常数下标填充**(跳过维用 `ee = e + (e >= d)` 的代数恒等式表达,**不用 switch**):
//     const u64 *rows[7];
//     for (int e = 0; e < 7; e++) { const int ee = e + (e >= (int)d); ...; rows[e] = ...; }
//   两者产出**逐位相同的 7 条指针序列**(`ee` 取 0..d-1, d+1..7 与 `nr++` 序恒等)。
// 【为何发】★ 本发**不是**为了"这一处能省多少",而是**为全队标定判题机单价**:
//   `work/a14ae_scan.md` §五 / `work/a14ae_pricing.md` §五 交班点名的第一件事 —— pass-B 里最大的两个栈站
//   (`[rsp+0xec]` 配对环上界 **7,000,035** 次 + `[rsp+0xa0]` 行指针回读 **5,894,641** 次 = **12.9 M 栈 uop/局**)
//   的去留,**完全取决于"1 条栈 uop / 1 次紧邻往返事件"在判题机上的单价**:
//     · **uop 支**(在档 1 ALU uop/主环迭代 = 1.582 ms、1 载入 uop/迭代 = 0.396 ms)⇒ 12.9 M 上界 **4.13 ms**;
//     · **事件支**(`a14ad_` 由 `hsum256` 实测 **1.6 ns/次紧邻停等**)⇒ 12.9 M 上界 **20.6 ms**。
//   两者判决截然相反(4.13 ms 只勉强过缺口 3.558905 ms、远不够 2× 门 7.118 ms;20.6 ms 轻松过门)⇒
//   **必须用一发实测单价**。本件就是那把尺:它**同时**含三件事,可反解出单价(详见 `work/a14af_price.md` §三 预注册):
//     (a) 消除 872,192 次**紧邻**(+8~228 B)8 B 存→8 B 载栈往返(`rows[]` 槽回读 **6,105,344 → 0**);
//     (b) 分配器**另**溢出 2 条行指针(`[rsp+0x110]/0x118`,各回读 6,977,601 次,**跨块非紧邻**);
//     (c) 附带少执行 **120,973,660 条非内存指令**(变长索引存 + 8 路 `if (e==d) continue` 的地址计算被消掉)。
// 【机制/剂量自证】★ **objdump(判题同款 gcc 9.3,本席发前复核)**:`query_group<8>`(= 判题几何 k=8 用的实例,
//   **live 路径**)指令数 **1877 → 1758(−119)**、`rsp+rbp` 引用 **251 → 218(−33)**、内存操作数 599 → 557;
//   `.text` **50254 B / `7b234060825d` → 49742 B / `e8bfaad9321b`**(−512 B),其余 4 个 `query_group<k>`(k=4,5,6,7)
//   与 `solve_mf` **逐字节不变**(同一份 objdump 逐函数核对)。
// 【逐位等价】`rows[]` 的内容与顺序一字未改;`s_fbm` 地址、`cell`、`FW`、`w0` 全同 ⇒ 官形 ck 3908545491 逐位同。
// 【与 a14ad_ ROWS 刀的差别】那一刀用 `switch` ⇒ GCC 9.3 生成**跳转表**(栈流量反增 252→360,被反制未发);
//   本发用**代数跳维**(`e + (e >= d)`),下标全为编译期常数 ⇒ 分配器可把 7 条指针留在寄存器。
// 【(914)(2) 自查】不碰任何 pragma / 不重开在册正号 / 不重做在档已封轴(分支·展开·摆放·MF_KSPAD·MF_QCOEF·
//   访存形态·预取距离,以及 a14ad_ 已封闭的 RLOAD/ROWS(switch)/PBW/PFW 面一字未动)。
// 闸门:判题同款 flag rc=0 · 自驱逐位 ck 3908545491 · dlopen 双载 IDENTICAL · (241)② 正控打在本发改动行 ·
//   去重闸 code_hash 唯一(已对 prior_code_hashes('1014') 全表核过)。
// ======================
// ===== REFERENCES =====
// [1] 本账号(saffah_cc_v41_agg1)现役最好件 **#114060 / #113991** —— <https://duck.ac/submission/114060>
//     (判题机 5406.801690 ms = 本题在档 mine;`.text` md5 28b6ff90103b 与 #113991 逐字节恒等)。
//     本件正文 = 该件正文逐字节,唯一改动见下【思路】。
// [2] 同账号前代 **#113399**(`schedule-insns` 落地件)—— <https://duck.ac/submission/113399>。
// [3] duck.ac/problem/1014 题目页 <https://duck.ac/problem/1014>
// ===== 思路(a14ad_ 席 · 新段,追加) =====
// 【本发唯一变量】`hsum256` 的 32 B **栈存 + 4 次 8 B 载入**(store-to-load forwarding 点,每查询一次)改为**纯寄存器归约**
//   (`vextracti128` + `vpaddq` + `vmovq` + `vpextrq`)⇒ 每次 `and_popcount_range` 调用 **−1 存 −4 载**,
//   并去掉那条带 `"+m"` 的 **volatile asm 内存栅**。
// 【为何发】本棒按派单先做**判题机口径的算力轴 uop 账**(`work/a14ad_uops.md`):把 `query_group<8>` 的每条
//   uop 按在档新单价表(ALU=3/拍 · 载入=2/拍 · p5=1/拍 · 前端 4 宽)折成拍,再与实测拍数对照。
//   结论(逐条自证,objdump 数出):pass-A 主环 = **14 载入 + 26 ALU(22 条 p015 + 4 条 p5)+ 6 预取 + 8 槽环控/对齐**;
//   端口地板 p015 7.33 / p5 4 / p23 10 / 前端 13.75 拍,实测 ≈55~60 拍/迭代 ⇒ **访存(并发)绑、ALU 有 4× 余量**,
//   且 nibble-popcount 主环在 AVX2 指令层**已到地板**(13 条/32 B 向量,无 AVX-512 ⇒ 无 vpternlogd/vpopcntb)——
//   故本棒的刀**不砍算法本身**,而砍「uop 的**表达形态**」:把**无需存在**的 uop 从热路径里去掉。
// 【机制】★ **uop 账**:每查询 1 次 ⇒ 10⁶ 次/局;每次 **1 条 32 B 栈存 + 4 条 8 B 载入**(store-forward 点,
//   且该 asm 带 `"+m"` 内存操作数 = 编译器内存栅)⇒ 改后 **−5 条内存 uop × 10⁶ = −5M 条**,
//   并去掉 10⁶ 次可能的 store-forwarding 停等。量级小(0.02% Ir),本发是**低风险对照**:
//   若连它也动到带外,说明本棒的量具分辨力有问题。
// 【(914)(2) 自查】逐项核过现役双串清单:本改动不碰任何 pragma / 不重开在册正号 / 不重做在档已封轴
//   (分支·展开·摆放·MF_KSPAD·MF_QCOEF·访存形态·预取距离,一字未动)。
// 【逐位等价】数据流一字未改:只改**取数的表达形式**,不改变任何被读地址、任何算术结果。
// 闸门:判题同款 flag rc=0 · 自驱逐位 ck 3908545491 · dlopen 双载 IDENTICAL · (241) 正控三自证 ·
//   去重闸 code_hash 唯一(已对 prior_code_hashes('1014') 全表核过)。
// ======================
// ===== REFERENCES =====
// [1] duck.ac/problem/1014 <https://duck.ac/problem/1014>(MIN-FOLD 引擎;k=8 n=1e6)
// [2] duck.ac 本账号 saffah_cc_v41_agg1,提交 #113696 <https://duck.ac/submission/113696>
//     (5410.849157 ms = 本题现役 mine)—— 本件正文 = **`work/trim_base_113696.cpp`(已证同码 + 自驱 ck 3908545491)
//     的逐字节副本 + 下方唯一改动**,其余逐字节未动。
// [3] 上游线索 = **`re9_` 席**(`problems/re9_audit/work/re9_table.md` §4):本题 4 项删侧 flag 被旧
//     (裸 `g++` = gcc 15.2)预筛判“空转”故从未发,而**判题编译器 gcc 9.3** 下判“真改码”且**从未在判题机定价**
//     ⇒ 本席是本 flag 面(据派单)**最后 4 项**的收口棒。
// 合规:判题提交正文按站点规则公开可见;本账号自有代码。本文件按 RULES §3 逐项署名。
// ======================
// ===== 思路 =====
// 【本发唯一变量(相对 [2]):源内 `optimize(...)` 清单追加 `no-tree-fre`。不带其他刀。】
// ★ **Ir 过滤(本席先算后做,遵 `re9_` 交棒要求)**:判题几何下 callgrind 确定性 Ir(n=1e5 缩放,
//   base 与各臂**同一 n** 比较;checksum 五件逐位同 `38982155`):
//   `no-tree-fre` **−0.4648%** · `no-tree-pre` **−1.0381%** ⇒ 二者**Ir 确实下降** ⇒ 进入定价;
//   `no-tree-slp-vectorize` **+0.0968%** · `no-tree-vectorize` **+4.0017%** ⇒ **Ir 上升 ⇒ 直接否掉、不发** ✓
// ★★ **且降幅落在热核本体**:`callgrind_annotate` 显示全程序 **91.5% 的 Ir 都在 `solve_mf.constprop.2`**,
//   而两者的降幅正出现在该函数内(base 599,658,760 → fre 596,613,878 = **−0.508%** / pre 592,858,390 = **−1.134%**)
//   ⇒ **不是在冷码上省指令**。(对照:`no-tree-vectorize` 的 `.text` 收缩最大 −3952 B 却让 Ir **+4.0%** ——
//   「码变小 ↔ 活变少」反相关律的**第三次实证**,见 `re9_audit/work/re9_inventory.md` §2.5。)
// ★ 为什么本题比 1014b 值得赌:本题机型判为 **ALU 端口绑(13 ALU/256 位地板)** ⇒ 删掉 ALU 工作**有转成时间的通道**;
//   而 1014b 是延迟/访存绑((884) 的 −3.47% Ir ⇒ 0 时间是在那里测的)。缺口仅 **8.736549 ms = 0.161%**,
//   即只要求 ~16% 的 Ir→时间 传递率即可闭合。**上界(若满额传递)≈ −56 ms = 缺口的 6.4×。**
// 闸门:判题同款 flag rc=0 · 自驱 `-DLOCAL_TEST` k=8 n=1000005 Q=1610 逐位 ck **3908545491** ·
//   双载 IDENTICAL + (241) 正控三自证 · 锚 `.text` 逐字节恒等((729))。
// ======================
// [trim_] identical=True ; base_lines=1085 trimmed_lines=1085 ; base=96003 B trimmed=61017 B
// [trim_] 历史注释预压(正文一字节未动;REFERENCES 块与全部 duck.ac URL 保留)
//   原 96003 B → 预压后 60759 B(去 349 行注释 / 35244 B);机器证明:剥注释后代码行逐行相同 = True
// ======================
// ===== REFERENCES =====
// [1] 本账号 saffah_cc_v41_agg1 提交 #113644 <https://duck.ac/submission/113644>(5411.087927 ms = 本题**现役 mine**)
//     —— 本件正文 = 该提交正文的**逐字节副本 + 一处插入**(下方 [2])。**当时完整清单**:
//     `O3,no-strict-aliasing,rename-registers,web,tree-loop-if-convert,schedule-insns,no-gcse,no-ivopts,no-web,no-stack-protector`
// [2] (L2)/(809) 剂量阶梯探针 **FE**:在 `and_popcount_range` 主环(8 字/迭代 = 一条 64 B 行、两段独立 AND 链)
//     顶部插入 **4 条同类 uop**(4× nop(前端槽))⇒ 只加压力、不改语义。**每环价签必须在该环内实测**((823)(833))。
// 闸门:判题机同款 flag(`judge_flags.txt`)· 自驱 `-DLOCAL_TEST` 逐位 ck **3908545491** · 同批锚 + A-B-A。
// 合规:duck.ac 提交正文按站点规则公开可见;按 /home/yjp/duck.ac/RULES.md 第 3 节署名作者账号与原提交地址。
// ======================
// ===== 思路 =====
// 【p14j_ 席 · 1014】逐环定栏 · FE 栏:and_popcount_range 主环 +4 同类 uop。
// ================
// ===== REFERENCES =====
// [1] 本账号 saffah_cc_v41_agg1 提交 #113589 <https://duck.ac/submission/113589>(5411.189688 ms = 本题**现役 mine**)
//     —— 本件正文 = 该提交正文的**逐字节副本 + 一处真 token 折叠拼写**,其余逐字节未动。
// [2] 拼写 `MAXK (2 * 4)` → `MAXK (24 / 3)`(**无前导零**;值确为 8 ⇒ codegen 不变;已用 `mem_kb`/`.text` 自证同码)。
// 用途:同批折叠等价锚,给本棒 `p14i_` 各臂取同窗带(A-B-A 的 A/C)。
// 闸门:判题机同款 flag rc=0 · 自驱 `-DLOCAL_TEST` 逐位 ck **3908545491**。
// 合规:duck.ac 提交正文按站点规则公开可见;按 /home/yjp/duck.ac/RULES.md 第 3 节署名作者账号与原提交地址。
// ======================
// ===== 思路 =====
// 【p14i_ 席 · 1014 同码锚】MAXK 拼写 (24 / 3)(同值同码,无前导零)。
// ================
// ===== REFERENCES =====
// [1] 本账号 saffah_cc_v41_agg1 提交 #113539 <https://duck.ac/submission/113539>(5411.352803 ms = 本题**现役 mine**,含 no-gcse+no-ivopts+**no-web**)
//     —— 本件正文 = 该提交正文的**逐字节副本 + 一处改动**(下方 [2])。
// [2] 单变量:追加 `no-stack-protector`(在 #113467 基座读 +0.040 = 带内 ⇒ 新基座复测)。
// 闸门:判题机同款 flag rc=0 · 自驱 `-DLOCAL_TEST` k=8 n=1000005 Q=1610 逐位 ck **3908545491** · 同批锚(无前导零 + mem_kb/.text 自证同码)+ A-B-A。
// 合规:duck.ac 提交正文按站点规则公开可见;按 /home/yjp/duck.ac/RULES.md 第 3 节署名作者账号与原提交地址。
// ======================
// ===== 思路 =====
// 【p14h_ 席 · 1014】单变量:追加 `no-stack-protector`(在 #113467 基座读 +0.040 = 带内 ⇒ 新基座复测)。
// ================
// ===== REFERENCES =====
// [1] 本账号 saffah_cc_v41_agg1 提交 #113496 <https://duck.ac/submission/113496>(5415.344208 ms = 本题**现役 mine**,含 `no-gcse`+`no-ivopts`)
//     —— 本件正文 = 该提交正文的**逐字节副本 + 一处改动**(下方 [2])。
// [2] 单变量:追加 `no-web`(预筛 +176 B;注意基座已含 `web` ⇒ 本臂为**去掉该正号件**)。
// 闸门:判题机同款 flag rc=0 · 自驱 `-DLOCAL_TEST` k=8 n=1000005 Q=1610 逐位 ck **3908545491** · 同批锚(无前导零拼写)+ A-B-A。
// 合规:duck.ac 提交正文按站点规则公开可见;按 /home/yjp/duck.ac/RULES.md 第 3 节署名作者账号与原提交地址。
// ======================
// ===== 思路 =====
// 【p14g_ 席 · 1014】单变量:追加 `no-web`(预筛 +176 B;注意基座已含 `web` ⇒ 本臂为**去掉该正号件**)。
// ================
// ===== REFERENCES =====
// [1] 本账号 saffah_cc_v41_agg1 提交 #113467 <https://duck.ac/submission/113467>(5418.520571 ms = 本题**现役 mine**,含 `no-gcse`)
//     —— 本件正文 = 该提交正文的**逐字节副本 + 一处改动**(下方 [2])。
// [2] 单变量:追加 `no-ivopts`(预筛 −1968 B;`ivopts` 正向项前席测为**空转**)。
// 闸门:判题机同款 flag rc=0 · 自驱 `-DLOCAL_TEST` k=8 n=1000005 Q=1610 逐位 ck **3908545491** · 同批锚 + A-B-A。
// 合规:duck.ac 提交正文按站点规则公开可见;按 /home/yjp/duck.ac/RULES.md 第 3 节署名作者账号与原提交地址。
// ======================
// ===== 思路 =====
// 【p14f_ 席 · 1014】单变量:追加 `no-ivopts`(预筛 −1968 B;`ivopts` 正向项前席测为**空转**)。
// ================
// ===== REFERENCES =====
// [1] 本账号 saffah_cc_v41_agg1 提交 #113399 <https://duck.ac/submission/113399>(5420.291669 ms = 本题**现役 mine**)
//     —— 本件正文 = 该提交正文的**逐字节副本 + 一处改动**(下方 [2])。
// [2] 单变量:在上述 `optimize` 列表**追加 `no-gcse`**(预筛:`.text` 50926 B → 50334 B,**真改码**;其余正文逐字节未动)。
//     依据 = 本席 `p14e_screen.py` 预筛(判题机同款 `g9.sh -O2 -std=c++17 -U_FORTIFY_SOURCE -c` + `.text` 逐字节比对,(826) 口径);
//     正向族已被前席扫遍(116 项次仅 7 项真改码),**`no-*` 删侧族与带值 `-f` 本题从未扫过**。
// 闸门:判题机同款 flag rc=0 · 自驱 `-DLOCAL_TEST` 逐位 ck **3908545491** · 同批折叠等价锚 + A-B-A。
// 合规:duck.ac 提交正文按站点规则公开可见;按 /home/yjp/duck.ac/RULES.md 第 3 节署名作者账号与原提交地址。
// ======================
// ===== 思路 =====
// 【p14e_ 席 · 1014】optimize 列表追加 `no-gcse`(单变量、真改码项,预筛后发射)。
// ================
// ===== REFERENCES =====
// [1] 本账号现役最好件 **#113358** —— <https://duck.ac/submission/113358>(判题机 5430.047488 ms = 本题 mine;
//     = 上一棒 `web + tree-loop-if-convert` 叠加件)—— 本件正文 = 该件正文**逐字节 + 下方唯一一处 pragma 追加**。
// [2] 同机器码孪生件 **#113345** —— <https://duck.ac/submission/113345>(5430.272766 ms,`.text` md5 与本件基座逐字节同)。
// [3] duck.ac 用户 saffah_codex_6s_agg2 **#109580** —— <https://duck.ac/submission/109580>(5456.678392 ms = 本题 T)。
// [4] 在档同族读数(本席上棒,全部判题机定价):`+web` = **−4.590402 ms ✓** · **`+tree-loop-if-convert` = −1.053895 ms ✓(判正)**
//     · `+unroll-loops` = **+22.969045 ✗** · `+tree-loop-linear` = **+35.106232 ✗✗** · 其余 60 项 `.text` 0 差异(空转)。
// [5] duck.ac/problem/1014。以上均为公开提交,正文按站点规则公开可见。
// ===== 思路 =====
//   · 纯预取 ⇒ 语义零改动;`-DLOCAL_TEST` k=8 n=2000 mode 0 / 4 暴力对拍 ⇒ **0 mismatch** ✓
//   · 生产尺度 k=8 n=1000005 Q=1610 mode 10:**checksum 3908545491 与 #106713 逐位相同** ✓
//   · `g++ -O2 -static -U_FORTIFY_SOURCE -std=c++17 -c`:warning 数与基座**完全相同**(58,0 新增)✓
// ================
// ===== 思路(a14w_ 席 · 新段,追加) =====
// 【本发唯一变量(相对基座 #113894 <https://duck.ac/submission/113894>):源内 `optimize(...)` 清单尾追加 ``vect-cost-model=unlimited``。】
// 基座 = #113894 正文**逐字节副本**(已含 `no-tree-fre`,即 a14s_ 的删侧落地件)⇒ 本件即"叠在 no-tree-fre 之上"。
// 【为何发】本棒 = **加侧(正向旗)gcc 9.3 重筛**:旧预筛用裸 `g++`(15.2)、判题机是 gcc 9.3 ⇒ 旧判决整片可疑
//   (同题删侧已由 a14s_ 兑现 `no-tree-fre` −1.44 ms 实证此污染)。本席用 `ref/gcc9/g9.sh` + judge_flags(4 旗)
//   重编重比 `.text`,逐字节筛出**真改码**项;再以官形 callgrind(n=1e5 缩放,base 同 n)做 **Ir 过滤**。
// 【Ir 读数】见 a14w_screen.md / a14w_pricing.md(本席实测)
// 闸门:判题同款 flag rc=0 · 自驱 `-DLOCAL_TEST` 逐位 ck 3908545491 · 双载 IDENTICAL + (241) 正控三自证 ·
//   去重闸 code_hash 唯一(已对 `prior_code_hashes('1014')` 全表核过)。
// ======================
#pragma GCC optimize("O3,no-strict-aliasing,rename-registers,web,tree-loop-if-convert,schedule-insns,no-gcse,no-ivopts,no-web,no-stack-protector","no-tree-fre,vect-cost-model=unlimited")
#pragma GCC target("avx2,bmi,bmi2,popcnt,lzcnt,tune=skylake")
#define MF_QCOEF 140
// duck.ac 1012..1016 : k-D dominance counting (k=6..10).
//
// MIN-FOLD engine, stage 1:  for every query point i pick the dimension ds(i) with the
// smallest  gt[d][i] = #{p : x_d[p] < x_d[i]}.  Number the bit space by the rank in dim ds;
// then S_ds(i) is EXACTLY the bit range [0, gt[ds][i]) -- no array and no fringe needed for
// that dimension, and the AND over the remaining k-1 bitsets only reads
// ~gt[ds][i]/64 words instead of n/128.  With random coordinates E[min_d x_d] = n/(k+1),
#include <immintrin.h>

static inline __m256i LDU(const void *p) {
  __m256i v;
  __asm__("vmovdqu %1, %0" : "=x"(v) : "m"(*(const __m256i *)p));
  return v;
}
static inline __m256i LDA(const void *p) {   // p 必须 32 字节对齐
  __m256i v;
  __asm__("vmovdqa %1, %0" : "=x"(v) : "m"(*(const __m256i *)p));
  return v;
}
// 存数:内存是读写出操作数,这样编译器知道内存被改写,不会做 CSE / 消除。
static inline void STU(void *p, __m256i v) {
  __asm__ volatile("vmovdqu %1, %0" : "+m"(*(__m256i *)p) : "x"(v));
}
static inline void STA(void *p, __m256i v) {  // p 必须 32 字节对齐
  __asm__ volatile("vmovdqa %1, %0" : "+m"(*(__m256i *)p) : "x"(v));
}
static inline __m128i LDQ(const void *p) {
  __m128i v;
  __asm__("vmovdqu %1, %0" : "=x"(v) : "m"(*(const __m128i *)p));
  return v;
}

// ---- 宏版本(放在 #pragma GCC target(...) 之后使用)----
// 取数:内存是输入操作数,语义正确。
// 存数:`"+m"` 读写出 + volatile,语义正确。
#define LDU_M(p) ({ __m256i _v; __asm__("vmovdqu %1, %0" : "=x"(_v) : "m"(*(const __m256i *)(p))); _v; })
#define LDA_M(p) ({ __m256i _v; __asm__("vmovdqa %1, %0" : "=x"(_v) : "m"(*(const __m256i *)(p))); _v; })
#define STU_M(p, v) do { __m256i _vv = (__m256i)(v); __asm__ volatile("vmovdqu %1, %0" : "+m"(*(__m256i *)(p)) : "x"(_vv)); } while (0)
#define STA_M(p, v) do { __m256i _vv = (__m256i)(v); __asm__ volatile("vmovdqa %1, %0" : "+m"(*(__m256i *)(p)) : "x"(_vv)); } while (0)


#ifdef LOCAL_TEST
#include <cstdio>
#include <cstdlib>
#include <ctime>
#else
#ifdef __cplusplus
extern "C" void *malloc(unsigned long);
#else
void *malloc(unsigned long);
#endif
#endif

typedef unsigned u32;
typedef unsigned long long u64;

#ifndef MAXN
#define MAXN 1000005
#endif
#define MAXK (24 / 3)
#define STRIDE 8

// Bucket-count coefficient: q ~ sqrt(n) * MF_QCOEF/100.  Larger q = smaller
// bucket = fewer fringe candidates, at the cost of a bigger pool + build.
// Bucket count = sqrt(n) * MF_QCOEF/100 * kscale[k].  MEASURED OPTIMA (board):
//   n=1e6  k=6..8 : 122 default is fine (1013 7.491 s, 1014 8.503 s at 122)
//   n=1e6  k=9/10 : 92  (1016 10.888 s at 92; 10.959 at 122; 11.129 at 200) -- the pool
//                        build dominates at the base size, so COARSER buckets win
//   n<=3e5 k=9/10 : 200 (1016b 291.4 ms vs 326.6 at 122; 1015a 1.444, 1016a 1.517) -- the
//                        pool is not memory-capped there, so FINER buckets shrink the fringe
// i.e. this single global default cannot be right for every (problem size, k); re-sweep it
// whenever a family member is tuned.
#ifndef MF_QCOEF
#define MF_QCOEF 70
#endif
// Transposed fringe rows: stride padded to 8 u32 (32 B) for k<=8 so every
// candidate load is one aligned, line-contained 32-byte vector load.
#ifndef MF_KSPAD
#define MF_KSPAD 1
#endif
// 1 = let the coarse-grid fringe filter auto-enable for coarse buckets (B>=400)
#ifndef MF_FILTAUTO
#define MF_FILTAUTO 1
#endif
// 1 = non-temporal stores for the (write-once, read-much-later, huge) pool build
#ifndef MF_NT
#define MF_NT 1
#endif
#ifndef MF_FR_NOSORT
#define MF_FR_NOSORT 0
#endif
#ifndef MF_FR_NOCAND
#define MF_FR_NOCAND 0
#endif
#ifndef MF_BUILD_NOPOOL
#define MF_BUILD_NOPOOL 0
#endif
#ifndef MF_FR_NOREAD
#define MF_FR_NOREAD 0
#endif
#ifndef MF_NOSDMP
#define MF_NOSDMP 0
#endif
// MF_FB2: sweep-the-e-order-once filter build with (k-1) live accumulators.
// MEASURED WORSE on the board (1016 12.580 -> 13.361 s, 1014 9.400 -> 10.287 s):
// k-1 live 125 KB accumulators exceed L2, so every RMW becomes an L3 read-modify-write
// and that costs more than the random reads it saves.  Kept only as a springboard.
#ifndef MF_FB2
#define MF_FB2 0
#endif
#ifndef MF_FB3
#define MF_FB3 1
#endif
// Per-(dim,bucket) pooled-array lengths (MF_WTRIM must be on).
#ifndef MF_PLEN
#define MF_PLEN 1
#endif
#ifndef MF_BUDGETMB
#define MF_BUDGETMB 1900
#endif
#ifndef MF_NOFILTB
#define MF_NOFILTB 0
#endif
// Lookahead distance for prefetching the scattered per-query metadata
// (s_pm record, s_gt threshold, s_bd bucket word) in pass B / pass A.
#ifndef MF_PFB
#define MF_PFB 32
#endif
#define MF_PFB1 (0x10u)
#define MF_PFB2 64
#define MF_PFB3 8
#define MF_PFB4 32
#define MF_PFB_OUT 4
// Pass A: sort each ds group by the bucket of one non-fold dim and copy that
// dim's (dim,bucket) array prefix into a small cache-resident scratch so the
// ~137 queries sharing it do not each re-fetch ~70 KB from DRAM.  1 = on.
#ifndef MF_ASCR
#define MF_ASCR 1
#endif
// ============================================================================
// !! DO NOT ENABLE MF_WTRIM / MF_PLEN !!
// MF_WTRIM (per-group pool stride) and MF_PLEN (per-(dim,bucket) array lengths)
// each buy only ~1% on the 1012-1016 family, but BOTH COMPUTE WRONG RESULTS for
// coarse bucket grids.  Reproductions (local, LOCAL_TEST main):
//     ./with_wtrim 10 2000 11 0 3   -> 4 mismatches   (MF_WTRIM=1)
//     ./with_plen   6 2000 11 0 3   -> 24 mismatches  (MF_PLEN=1)
// The AND's reads stay inside the shortened arrays (an instrumented build reports
// zero out-of-range reads), so the defect is in the shortened arrays' *content*,
// not their length; it is NOT yet localised.  The fastest recorded board times
// (1012 6.753 s, 1016 12.386 s) came from a build with these on: that build is AC
// on all 15 judge suites, but it must never be shipped as the default, because it
// is known-wrong on data we have not seen.  Fixing this properly is worth ~1%.
// ============================================================================
// Trim the pool stride per ds group to the largest R actually read (-13% pool).
#ifndef MF_WTRIM
#define MF_WTRIM 0
#endif
#define AS_WORDS 20480
#ifndef MF_ORDP
#define MF_ORDP 16
#endif
#ifndef MF_ORDP_GT
#define MF_ORDP_GT 16
#endif
#ifndef MF_ORP
#define MF_ORP 64
#endif
#define Y14Z_PT(p) _mm_prefetch((const char *)(p), _MM_HINT_T0)
#define Y14Z_PFW(p) __asm__ __volatile__("prefetchw %0" :: "m"(*(const char *)(p)))
#ifndef MF_PFA
#define MF_PFA 1
#endif
#ifndef MF_FR_NOMETA
#define MF_FR_NOMETA 0
#endif

#ifndef MAXQ
#define MAXQ 4096
#endif

static u32 s_ord[MAXK][MAXN];
static u32 s_gt[MAXK][MAXN];
static u32 s_pm[(size_t)MAXN * 2 * STRIDE] __attribute__((aligned(64)));
/* [Y14V-PMINT] per-query record layout.  k<=8: one 64 B record per point holding the
   s_pm row in words 0..7 and the avpool row in words 8..15, so the two 32 B rows the
   pass-B dim loop reads for a query share ONE cache line (they used to live in two
   separate 32 MB arrays = two line fills per (query,dim), 7e6 times).  k>8 keeps the
   historical layout (16 u32 rows used by the `rec + 8` high-half reads, avpool separate). */
static u32 g_pstr = STRIDE;
#define PMROWK(i, st) (s_pm + (size_t)(i) * (size_t)(st))
#define AVROWK(i, st, avp) (((st) == 2 * STRIDE) ? (s_pm + (size_t)(i) * (2 * STRIDE) + STRIDE) : ((avp) + (size_t)(i) * STRIDE))
static unsigned short s_bd[(size_t)MAXN * MAXK];   // [d4b] u16: bb <= 4095
static unsigned short s_bdv[(size_t)MAXN * MAXK];  // [d4b] dim-major staging plane
static u32 s_g[MAXN];
static u32 s_qord[MAXN], s_tmp[MAXN], s_cntv[MAXN];
static u32 s_frord[MAXK][MAXN];
static u32 s_nid[MAXN];
static u32 s_pos[MAXK][MAXN];
static u32 s_posp[(size_t)MAXK * MAXN];   // s_posp[p*MAXK+d] = rank of p in dim d
static u64 s_facc[(size_t)(MAXK - 1) * (((MAXN) + 63) / 64 + 16)];
static u32 s_bnde[(size_t)MAXK * (MAXQ + 2)];   // per-dim coarse-cell boundary positions
static u64 *s_fbm = 0;
static u64 s_fbuf[8192] __attribute__((aligned(64)));
static __m256i khi8v, khi8hv;
static u32 g_Qc = 16;
static int g_cshift = 20;   // cell(x) = (x*g_Qc)>>g_cshift ; boundary(c) = (c<<g_cshift)/g_Qc
#define CBOUND(c) ((u64)(c) << g_cshift) / g_Qc
static u32 g_fbm_W = 0;
static int g_use_filt = 0;
static int g_lexsort = 0;
static int g_nofilt = 0;
static u32 s_fpos[(MAXK + 1) * MAXQ];
static u32 s_bval[(MAXK + 1) * MAXQ];
static u64 *s_bs = 0;
static u64 s_acc[MAXN / 64 + 256] __attribute__((aligned(64)));
static u32 *s_sdmp[MAXK];
static u64 s_ascr[AS_WORDS] __attribute__((aligned(64)));
static u32 s_maxr[(size_t)MAXK * MAXK * MAXQ];
static u32 s_pofs[(size_t)MAXK * MAXQ];
static u32 s_plen[(size_t)MAXK * MAXQ];
static int g_plen_on = 0;

static u32 g_W, g_Q, g_B;
static u32 g_KS;   // row stride of the transposed coordinate rows (64 B for k>8)
static int g_nosort = 0;
static int g_nosdmp = 0;
static int g_skip_and = 0, g_skip_fringe = 0;

#define FPOS(d, b) s_fpos[(size_t)(d) * MAXQ + (b)]
#define BVAL(d, b) s_bval[(size_t)(d) * MAXQ + (b)]

#include <sys/mman.h>
static void *pool_alloc(size_t bytes) {
  void *raw = malloc(bytes + (2u << 20));
  if (!raw) return 0;
  void *p = (void *)(((size_t)raw + (2u << 20) - 1) & ~(size_t)((2u << 20) - 1));
  /* [x14z_HP] 池巨页:量纲判据((67))= 池足迹 227 MB / 4 KB = 58.1 k 页 ÷ TLB 条数 ~1.5~2 k = 30 ≫ 1
     ⇒ 对象存在(1013 同形刀判题机正收益;1012b 两靶位判负 ⇒ 本题为第三个数据点)。
     madvise 不改任何数据;内核 THP=always 或无 THP 时为 no-op。 */
  madvise(p, bytes, MADV_HUGEPAGE);
  return p;
}

// Harley-Seal / Muła nibble-popcount.  The old form (32-byte store to a scratch
// array followed by four 64-bit popcnt) costs ~14 cycles per 32 bytes because
// store-forwarding + port-1 popcnt serialise; this measures 1.48x faster on a
// pure-L1 microbenchmark (work/c6d2/alucost.cpp: 19.27 -> 13.06 cyc per chunk).
// Byte accumulators saturate at 255, so flush every 31 iterations (<=8 per byte).
__attribute__((target("avx2,popcnt")))
static inline u32 hsum256(__m256i v) {
  __m128i lo = _mm256_castsi256_si128(v);
  __m128i hi = _mm256_extracti128_si256(v, 1);
  __m128i s = _mm_add_epi64(lo, hi);
  return (u32)((u64)_mm_cvtsi128_si64(s) + (u64)_mm_extract_epi64(s, 1));
}
template<int KK>
__attribute__((target("avx2,popcnt")))
static u32 and_popcount_range(const u64 *const *bs, u32 Wr, u32 rem) {
  const __m256i lm = _mm256_set1_epi8(0x0f);
  const __m256i lk = _mm256_setr_epi8(0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,
                                      0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4);
  const __m256i z = _mm256_setzero_si256();
  /* [Y14V-DENS2] 单变量:本内环的**几何**(每迭代 8 字 = 一条 64 B 行,两段独立 AND 链 + 两个
     nibble-LUT 累加器;冲刷节奏 15 迭代 = 15*16 = 240 <= 255 不饱和)。预取**形态与字节提前量一字未动**
     (仍是 6 条 `bs[i] + w + 48`):密度 2 后每迭代消耗整整一行 ⇒ 48 字的提前量 = 6 迭代 = 384 B,
     与旧循环(4 字/迭代、48 字 = 12 迭代 = 384 B)**字节提前量相同**,而新迭代的体量约为旧的 2 倍
     ⇒ 提前**时间**也近似不变(本席 #109354 已实测该提前时间不能缩半:48→24 = +99.72 ms ✗)。 */
  __m256i tot = z, acc0 = z, acc1 = z;
  u32 w = 0, cnt = 0, total = 0;
  for (; w + 8 <= Wr; w += 8) {
    __asm__ __volatile__("nop\n\tnop\n\tnop\n\tnop" ::: "memory");
    _mm_prefetch((const char *)(bs[1] + w + 48), _MM_HINT_T0);
    _mm_prefetch((const char *)(bs[2] + w + 48), _MM_HINT_T0);
    _mm_prefetch((const char *)(bs[3] + w + 48), _MM_HINT_T0);
    _mm_prefetch((const char *)(bs[4] + w + 48), _MM_HINT_T0);
    _mm_prefetch((const char *)(bs[5] + w + 48), _MM_HINT_T0);
    _mm_prefetch((const char *)(bs[6] + w + 48), _MM_HINT_T0);
    __m256i a = LDU((const __m256i *)(bs[0] + w));
    for (int d = 1; d < KK; d++) a = _mm256_and_si256(a, LDU((const __m256i *)(bs[d] + w)));
    __m256i lo = _mm256_and_si256(a, lm);
    __m256i hi = _mm256_and_si256(_mm256_srli_epi16(a, 4), lm);
    acc0 = _mm256_add_epi8(acc0, _mm256_add_epi8(_mm256_shuffle_epi8(lk, lo), _mm256_shuffle_epi8(lk, hi)));
    __m256i b2 = LDU((const __m256i *)(bs[0] + w + 4));
    for (int d = 1; d < KK; d++) b2 = _mm256_and_si256(b2, LDU((const __m256i *)(bs[d] + w + 4)));
    __m256i lo2 = _mm256_and_si256(b2, lm);
    __m256i hi2 = _mm256_and_si256(_mm256_srli_epi16(b2, 4), lm);
    acc1 = _mm256_add_epi8(acc1, _mm256_add_epi8(_mm256_shuffle_epi8(lk, lo2), _mm256_shuffle_epi8(lk, hi2)));
    if (++cnt == 15) { tot = _mm256_add_epi64(tot, _mm256_add_epi64(_mm256_sad_epu8(acc0, z), _mm256_sad_epu8(acc1, z))); acc0 = z; acc1 = z; cnt = 0; }
  }
  tot = _mm256_add_epi64(tot, _mm256_add_epi64(_mm256_sad_epu8(acc0, z), _mm256_sad_epu8(acc1, z)));
  total = hsum256(tot);
  for (; w < Wr; w++) {
    u64 v = bs[0][w];
    for (int d = 1; d < KK; d++) v &= bs[d][w];
    total += (u32)__builtin_popcountll(v);
  }
  if (rem) {
    u64 v = bs[0][Wr];
    for (int d = 1; d < KK; d++) v &= bs[d][Wr];
    total += (u32)__builtin_popcountll(v & ((1ull << rem) - 1));
  }
  return total;
}

template<int KK>
__attribute__((target("avx2,popcnt")))
static void query_group(u32 N, u32 *out, u32 ds, u32 q0, u32 q1, u32 Q, u32 W) {
  const int k = KK;
  const int K1 = KK - 1;
  /* [Y14V-PMINT] compile-time row stride for this instantiation: 2*STRIDE when k<=8
     (interleaved 64 B record) so the hot loop folds it into a shift, never an imul. */
  const u32 PSTR = (KK <= 8) ? (2 * STRIDE) : STRIDE;
#if MF_ASCR
    // ---- pass A locality: order the group by the bucket in one non-fold dim so that the
    //      ~Q-run of queries needing array (e1,b) is processed together, and pin that
    //      array's prefix in a small scratch (the other k-2 dims still stream from DRAM
    //      and evict a 70 KB hot array within one query, which is why merely sorting
    //      the queries was measured a wash). ----
    const u32 d1 = (ds == 0) ? 1u : 0u;
    const u32 e1 = (d1 < ds) ? d1 : d1 - 1;
    {
      u32 *cntv = s_cntv;
      for (u32 v = 0; v <= Q; v++) cntv[v] = 0;
      for (u32 qi = q0; qi < q1; qi++) {
#if MF_PFB > 0
        if (qi + MF_PFB1 < q1) _mm_prefetch((const char *)(s_bdv + (size_t)d1 * N + s_qord[qi + MF_PFB1]), _MM_HINT_T0);
#endif
        cntv[s_bdv[(size_t)d1 * N + s_qord[qi]] + 1]++;
      }
      { u32 ac = q0; for (u32 v = 0; v <= Q; v++) { u32 c = cntv[v]; cntv[v] = ac; ac += c; } }
      for (u32 qi = q0; qi < q1; qi++) {
        if (qi + MF_PFB1 < q1) _mm_prefetch((const char *)(s_bdv + (size_t)d1 * N + s_qord[qi + MF_PFB1]), _MM_HINT_T0);
        u32 id = s_qord[qi]; s_tmp[cntv[s_bdv[(size_t)d1 * N + id] + 1]++] = id;
      }
      for (u32 qi = q0; qi < q1; qi++) s_qord[qi] = s_tmp[qi];
    }
#else
    const u32 d1 = 0, e1 = 0;
#endif
    // ---- pass A: aligned AND; queries ordered lexicographically by their bucket vector so
    //      that consecutive queries share bitset arrays (keeps the working set small). ----
    if (g_lexsort) {
      u32 *cntv = s_cntv;
      for (int dd = k - 1; dd >= 0; dd--) {
        if (dd == ds) continue;
        for (u32 v = 0; v <= Q; v++) cntv[v] = 0;
        for (u32 qi = q0; qi < q1; qi++) cntv[s_bdv[(size_t)dd * N + s_qord[qi]] + 1]++;
        { u32 ac = q0; for (u32 v = 0; v <= Q; v++) { u32 c = cntv[v]; cntv[v] = ac; ac += c; } }
        for (u32 qi = q0; qi < q1; qi++) { u32 id = s_qord[qi]; s_tmp[cntv[s_bdv[(size_t)dd * N + id] + 1]++] = id; }
        for (u32 qi = q0; qi < q1; qi++) s_qord[qi] = s_tmp[qi];
      }
    }
#ifdef PF_DIST
    for (u32 qi = q0; qi < q0 + PF_DIST && qi + PF_DIST < q1; qi++) {
      u32 j = s_qord[qi + PF_DIST];
      const unsigned short *bdn = s_bd + (size_t)j * MAXK;
      for (int e = 0; e < K1; e++) {
        int d = (e < ds) ? e : e + 1;
        const char *pp = (const char *)(s_bs + ((size_t)e * (Q + 1) + bdn[d]) * W);
        _mm_prefetch(pp, _MM_HINT_T0);
        _mm_prefetch(pp + 64, _MM_HINT_T0);
        _mm_prefetch(pp + 128, _MM_HINT_T0);
      }
    }
#endif
#if MF_ASCR
    {
      u32 qi = q0;
      while (qi < q1) {
        u32 b1 = s_bdv[(size_t)d1 * N + s_qord[qi]];
        u32 qe = qi + 1;
        while (qe < q1 && s_bdv[(size_t)d1 * N + s_qord[qe]] == b1) qe++;
        const u64 *bp1 = g_plen_on ? (s_bs + s_pofs[(size_t)e1 * MAXQ + b1])
                                   : (s_bs + ((size_t)e1 * (Q + 1) + b1) * W);
        u32 mx = 1;
        for (u32 t = qi; t < qe; t++) { u32 rr = s_gt[ds][s_qord[t]]; if (rr > mx) mx = rr; }
        u32 nwd = (mx >> 6) + 1;
        if (nwd <= AS_WORDS) {
          const u64 *src = bp1;
          for (u32 w = 0; w < nwd; w++) s_ascr[w] = src[w];
          bp1 = s_ascr;
        }
        for (u32 qq = qi; qq < qe; qq++) {
          u32 i = s_qord[qq];
          const unsigned short *bd = s_bd + (size_t)i * MAXK;
#if MF_PFA > 0
          {
            u32 qj = qq + MF_PFA;
            if (qj < qe) {
              u32 j = s_qord[qj];
              _mm_prefetch((const char *)(s_bd + (size_t)j * MAXK), _MM_HINT_T0);
              _mm_prefetch((const char *)(s_gt[ds] + j), _MM_HINT_T0);
            }
          }
#endif
          const u32 R = s_gt[ds][i];
          u32 cnt = 0;
          if (R && !g_skip_and) {
            const u64 *bp[MAXK];
            for (int e = 0; e < K1; e++) {
              if (e == (int)e1) bp[e] = bp1;
              else { int d = (e < ds) ? e : e + 1;
                     bp[e] = g_plen_on ? (s_bs + s_pofs[(size_t)e * MAXQ + bd[d]])
                                       : (s_bs + ((size_t)e * (Q + 1) + bd[d]) * W); }
            }
            cnt = and_popcount_range<KK - 1>(bp, R >> 6, R & 63u);
          }
          out[i] = cnt;
        }
        qi = qe;
      }
    }
#else
    for (u32 qi = q0; qi < q1; qi++) {
      u32 i = s_qord[qi];
      const unsigned short *bd = s_bd + (size_t)i * MAXK;
#if MF_PFA > 0
      {
        u32 qj = qi + MF_PFA;
        if (qj < q1) {
          u32 j = s_qord[qj];
          _mm_prefetch((const char *)(s_bd + (size_t)j * MAXK), _MM_HINT_T0);
          _mm_prefetch((const char *)(s_gt[ds] + j), _MM_HINT_T0);
        }
      }
#endif
#ifdef PF_DIST
      if (qi + PF_DIST < q1) {
        u32 j = s_qord[qi + PF_DIST];
        const unsigned short *bdn = s_bd + (size_t)j * MAXK;
        for (int e = 0; e < K1; e++) {
          int d = (e < ds) ? e : e + 1;
          const char *pp = (const char *)(s_bs + ((size_t)e * (Q + 1) + bdn[d]) * W);
          _mm_prefetch(pp, _MM_HINT_T0);
          _mm_prefetch(pp + 64, _MM_HINT_T0);
          _mm_prefetch(pp + 128, _MM_HINT_T0);
        }
      }
#endif
      const u32 R = s_gt[ds][i];
      u32 cnt = 0;
      if (R && !g_skip_and) {
          const u64 *bp[MAXK];
        for (int e = 0; e < K1; e++) {
          int d = (e < ds) ? e : e + 1;
          bp[e] = g_plen_on ? (s_bs + s_pofs[(size_t)e * MAXQ + bd[d]])
                            : (s_bs + ((size_t)e * (Q + 1) + bd[d]) * W);
#ifdef DBG_PLEN
          if (g_plen_on) {
            u32 need = (R >> 6) + ((R & 63) ? 1 : 0);
            if (need > s_plen[(size_t)e * MAXQ + bd[d]])
              printf("DBG ds=%d e=%d d=%d b=%u R=%u need=%u len=%u\n", ds, e, d, bd[d], R, need, s_plen[(size_t)e * MAXQ + bd[d]]);
          }
#endif
        }
        cnt = and_popcount_range<KK - 1>(bp, R >> 6, R & 63u);
      }
      out[i] = cnt;
    }
#endif
    if (g_skip_fringe) return;
    // Reuse each query's bucket-boundary vector across all non-fold dimensions.
    static u32 *avpool = 0; static size_t avcap = 0;
    {
      size_t needav = (size_t)N * STRIDE * 4 + 256;
      if (needav > avcap) { avpool = (u32 *)pool_alloc(needav); avcap = avpool ? needav : 0; }
      if (avpool) for (u32 qi = q0; qi < q1; qi++) {
        u32 ii = s_qord[qi];
        const unsigned short *bdi = s_bd + (size_t)ii * MAXK;
        u32 *av = AVROWK(ii, PSTR, avpool);
        for (int e = 0; e < k; e++) av[e] = (e == (int)ds) ? 0x7FFFFFFFu : BVAL(e, bdi[e]);
        for (int e = k; e < STRIDE; e++) av[e] = 0x7FFFFFFFu;
      }
    }
    // ---- pass B: fringe, dimension-major.  Ordering the group's queries by their bucket in
    //      dim d makes every scan walk one L1-resident bucket block of the dim-d order. ----
    for (int d = 0; d < k; d++) {
      if (d == ds) continue;
      const u32 *const fo = s_frord[d];
      u32 exmask = 0;
      for (int e = 0; e < d; e++) if (e != ds) exmask |= 1u << e;
      // "don't care" lanes are forced to a maximum-unsigned value, so one unsigned max test
      // per candidate decides domination *and* the exclusion rule together.
      u32 hiA[8], hiAh[8];
      for (int e = 0; e < 8; e++) hiA[e] = ((exmask >> e) & 1u) ? 0u : 0x7FFFFFFFu;
      for (int e = 8; e < 16; e++) hiAh[e - 8] = ((exmask >> e) & 1u) ? 0u : 0x7FFFFFFFu;
      const __m256i notexlo = LDU((const __m256i *)hiA);
      const __m256i notexloh = LDU((const __m256i *)hiAh);
      const __m256i all8 = _mm256_set1_epi32(-1);
      const u32 *const odd = s_ord[d];
      const u32 *const sdmpd = s_sdmp[d];
      for (u32 qi = q0; qi < q1; qi++) {
        u32 packed = fo[qi];
        u32 i = packed & 0xFFFFFu;
#if MF_PFB > 0
        {
          u32 qj = qi + MF_PFB3;
          if (qj < q1) {
            u32 j = fo[qj] & 0xFFFFFu;
            _mm_prefetch((const char *)(PMROWK(j, PSTR)), _MM_HINT_T0);
            _mm_prefetch((const char *)(s_gt[d] + j), _MM_HINT_T0);
            _mm_prefetch((const char *)(AVROWK(j, PSTR, avpool)), _MM_HINT_T0);
            /* [PFSC] the missing member of this block (BRIEF 2.19.339; 1015b #106709
               -1.486%, 1016a #106692 green, and the 1016 #106738 port): pass B's tail
               does `out[i] += add` -- a RANDOM RMW on the 4 MB output array -- and no
               sibling site warms that line.  j = s_qord[qi + MF_PFB3] comes off the
               sequential query stream, so &out[j] needs no second-level dependency. */
            /* [Y14V-OUTFAR] 本发单变量:out[] 的预取距离独立成 MF_PFB_OUT(不再与上面三站的
               MF_PFB3 共用)。地址仍来自顺序流(qi 顺序、fo 顺读)⇒ 无二级依赖 ✓ */
            if (qi + MF_PFB_OUT < q1) {
              u32 jo = fo[qi + MF_PFB_OUT] & 0xFFFFFu;
              __asm__ __volatile__("prefetchw %0" :: "m"(*(const char *)(out + jo)));
            }
          }
        }
#endif
        const unsigned short bbd = (unsigned short)(packed >> 20);
        const u32 lo = FPOS(d, bbd);
        const u32 hi = s_gt[d][i];
        if (lo >= hi) continue;
        const u32 *rec = PMROWK(i, PSTR);
        const u32 *Avp = AVROWK(i, PSTR, avpool);
        __m256i qr = _mm256_or_si256(LDA((const __m256i *)rec), khi8v);
        __m256i Avm = _mm256_or_si256(LDU((const __m256i *)Avp), notexlo);
        __m256i qT = _mm256_min_epi32(qr, Avm);
        __m256i qTh;
        if (k > 8) {
          __m256i qrh = _mm256_or_si256(LDU((const __m256i *)(rec + 8)), khi8hv);
          __m256i Avmh = _mm256_or_si256(LDU((const __m256i *)(Avp + 8)), notexloh);
          qTh = _mm256_min_epi32(qrh, Avmh);
        } else {
          qTh = all8;
        }
        u32 add = 0;
        const u32 *c0 = sdmpd ? (sdmpd + (size_t)lo * g_KS) : 0;
        if (g_use_filt && KK == 8) {
          const u32 w0 = lo >> 6;
          const u32 nw = ((hi - 1) >> 6) - w0 + 1;
          const u32 csh = (u32)g_cshift, cQc = (u32)g_Qc;
          const u32 FW = g_fbm_W;
          const u64 *rows[7];
          for (int e = 0; e < 7; e++) {
            const int ee = e + (e >= (int)d);   // same 7 rows in the same order, constant index
            u32 cell = (u32)(((u64)rec[ee] * cQc) >> csh) + 1;   // <= cQc for x < N
            rows[e] = s_fbm + ((size_t)(d * 8 + ee) * (g_Qc + 1) + cell) * FW + w0;
          }
          const u64 *r0=rows[0], *r1=rows[1], *r2=rows[2], *r3=rows[3];
          const u64 *r4=rows[4], *r5=rows[5], *r6=rows[6];
          const u32 remh = hi & 63u;
          {   // first word: low mask only
            u64 vv = r0[0] & r1[0] & r2[0] & r3[0] & r4[0] & r5[0] & r6[0];
            vv &= ~0ull << (lo & 63);
            if (nw == 1u && remh) vv &= (1ull << remh) - 1;
#if MF_FR_NOCAND
            vv = 0;
#endif
            while (vv) {
              int t = __builtin_ctzll(vv);
              vv &= vv - 1;
              u32 j = (w0 << 6) + (u32)t;
              const u32 *cp = c0 ? (c0 + (size_t)(j - lo) * g_KS) : (PMROWK(s_ord[d][j], PSTR));
              __m256i pv = LDU((const __m256i *)cp);
              add += (u32)_mm256_testc_si256(_mm256_cmpgt_epi32(qT, pv), all8);
            }
          }
          for (u32 w = 1; w + 1 < nw; w++) {   // middle: no mask work at all
            u64 vv = r0[w] & r1[w] & r2[w] & r3[w] & r4[w] & r5[w] & r6[w];
#if MF_FR_NOCAND
            vv = 0;
#endif
            while (vv) {
              int t = __builtin_ctzll(vv);
              vv &= vv - 1;
              u32 j = ((w0 + w) << 6) + (u32)t;
              const u32 *cp = c0 ? (c0 + (size_t)(j - lo) * g_KS) : (PMROWK(s_ord[d][j], PSTR));
              __m256i pv = LDU((const __m256i *)cp);
              add += (u32)_mm256_testc_si256(_mm256_cmpgt_epi32(qT, pv), all8);
            }
          }
          if (nw > 1u) {                       // last word: high mask only
            u32 w = nw - 1u;
            u64 vv = r0[w] & r1[w] & r2[w] & r3[w] & r4[w] & r5[w] & r6[w];
            if (remh) vv &= (1ull << remh) - 1;
#if MF_FR_NOCAND
            vv = 0;
#endif
            while (vv) {
              int t = __builtin_ctzll(vv);
              vv &= vv - 1;
              u32 j = ((w0 + w) << 6) + (u32)t;
              const u32 *cp = c0 ? (c0 + (size_t)(j - lo) * g_KS) : (PMROWK(s_ord[d][j], PSTR));
              __m256i pv = LDU((const __m256i *)cp);
              add += (u32)_mm256_testc_si256(_mm256_cmpgt_epi32(qT, pv), all8);
            }
          }
          out[i] += add;
          continue;
        }
        if (g_use_filt) {
          const u32 w0 = lo >> 6;
          const u32 nw = ((hi - 1) >> 6) - w0 + 1;
          u64 *fb = s_fbuf;
          const u32 csh = (u32)g_cshift, cQc = (u32)g_Qc;
          const u32 FW = g_fbm_W;
          int first = 1;
#if MF_FR_NOREAD
          first = 0;
          for (u32 w = 0; w < nw; w++) fb[w] = 0;
#endif
          for (int e = 0; e < k; e++) {
            if (e == d) continue;
            u32 c = (u32)(((u64)rec[e] * cQc) >> csh) + 1;
            if (c > cQc) c = cQc;
            const u64 *row = s_fbm + ((size_t)(d * k + e) * (g_Qc + 1) + c) * FW + w0;
            if (first) {
              u32 w = 0;
              for (; w + 4 <= nw; w += 4) STU(fb + w, LDU(row + w));
              for (; w < nw; w++) fb[w] = row[w];
              first = 0;
            } else {
              u32 w = 0;
              for (; w + 4 <= nw; w += 4) STU(fb + w, _mm256_and_si256(LDU(fb + w), LDU(row + w)));
              for (; w < nw; w++) fb[w] &= row[w];
            }
          }
          fb[0] &= ~0ull << (lo & 63);
          u32 r2 = hi & 63u;
          if (r2) fb[nw - 1] &= (1ull << r2) - 1;
          for (u32 w = 0; w < nw; w++) {
            u64 vv = fb[w];
#if MF_FR_NOCAND
            vv = 0;
#endif
            while (vv) {
              int t = __builtin_ctzll(vv);
              vv &= vv - 1;
              u32 j = ((w0 + w) << 6) + (u32)t;
              const u32 *cp = c0 ? (c0 + (size_t)(j - lo) * g_KS) : (PMROWK(s_ord[d][j], PSTR));
              __m256i pv = LDU((const __m256i *)cp);
              u32 ok = (u32)_mm256_testc_si256(_mm256_cmpgt_epi32(qT, pv), all8);
              if (k > 8) {
                __m256i pvh = LDU((const __m256i *)(cp + 8));
                ok &= (u32)_mm256_testc_si256(_mm256_cmpgt_epi32(qTh, pvh), all8);
              }
              add += ok;
            }
          }
          out[i] += add;
          continue;
        }
        if (c0) {
          if (k <= 8) {
            const u32 *c = c0;
            u32 a0 = 0, a1 = 0, a2 = 0, a3 = 0;
            u32 j = lo;
            for (; j + 4 <= hi; j += 4) {
              __m256i p0 = LDU((const __m256i *)(c));
              __m256i p1 = LDU((const __m256i *)(c + g_KS));
              __m256i p2 = LDU((const __m256i *)(c + 2 * g_KS));
              __m256i p3 = LDU((const __m256i *)(c + 3 * g_KS));
              a0 += (u32)_mm256_testc_si256(_mm256_cmpgt_epi32(qT, p0), all8);
              a1 += (u32)_mm256_testc_si256(_mm256_cmpgt_epi32(qT, p1), all8);
              a2 += (u32)_mm256_testc_si256(_mm256_cmpgt_epi32(qT, p2), all8);
              a3 += (u32)_mm256_testc_si256(_mm256_cmpgt_epi32(qT, p3), all8);
              c += 4 * g_KS;
            }
            for (; j < hi; j++, c += g_KS) {
              __m256i pv = LDU((const __m256i *)c);
              a0 += (u32)_mm256_testc_si256(_mm256_cmpgt_epi32(qT, pv), all8);
            }
            add = a0 + a1 + a2 + a3;
          } else {
            const u32 *c = c0;
            for (u32 j = lo; j < hi; j++, c += g_KS) {
              __m256i pv = LDU((const __m256i *)c);
              __m256i pvh = LDU((const __m256i *)(c + 8));
              u32 ok = (u32)_mm256_testc_si256(_mm256_cmpgt_epi32(qT, pv), all8) &
                       (u32)_mm256_testc_si256(_mm256_cmpgt_epi32(qTh, pvh), all8);
              add += ok;
            }
          }
        } else {
          for (u32 j = lo; j < hi; j++) {
            const u32 *c = PMROWK(odd[j], PSTR);
            __m256i pv = LDA((const __m256i *)c);
            add += (u32)_mm256_testc_si256(_mm256_cmpgt_epi32(qT, pv), all8);
          }
        }
        out[i] += add;
      }
    }
}

__attribute__((target("avx2")))

/* [x14ai] OR-gather inner ring, lifted into its own function so gcc allocates
   registers for it on its own (the in-loop form reloads the nid pointer twice per
   element from the stack and spills q>>6 to the stack and immediately reloads it). */
static inline u32 or_ring(const u32 *nid, const u32 *od, u64 *cur, u32 ptr, u32 pend, u32 nlim) {
  const u32 lim = (nlim > MF_ORP) ? (u32)(nlim - MF_ORP) : 0u;
  u32 pfe = (pend < lim) ? pend : lim;
  while (ptr < pfe) { Y14Z_PT(nid + od[ptr + MF_ORP]);
                      u32 q = nid[od[ptr]]; cur[q >> 6] |= 1ull << (q & 63); ptr++; }
  while (ptr < pend) { u32 q = nid[od[ptr]]; cur[q >> 6] |= 1ull << (q & 63); ptr++; }
  return ptr;
}
static void solve_mf(u32 N, const unsigned **x, u32 *out, int k) {
  // W padded to 8 words: every (dim,bucket) array then starts on a 64-byte
  // boundary and every 32-byte vector load inside a stream is line-contained.
  const u32 W = ((N + 63) / 64 + 7u) & ~7u;
  g_W = W;
  g_pstr = (k <= 8) ? (2 * STRIDE) : STRIDE;
#ifdef MF_SKIP_AND
  g_skip_and = 1;
#endif
#ifdef MF_FILT
  g_use_filt = 1;
#endif
#ifdef MF_NOFILT
  g_use_filt = 0;
#endif
#ifdef MF_Q
  g_Q = MF_Q; g_B = (u32)((N + (MF_Q) - 1) / (MF_Q));
#endif
#ifdef MF_FILT
  g_use_filt = 1;
#endif
#ifdef MF_NOFILT
  g_use_filt = 0;
#endif
#ifdef MF_SKIP_FRINGE
  g_skip_fringe = 1;
#endif
  if (!g_Q) {
    // bucket size ~ 0.82*sqrt(n) balances the pool build (proportional to n^2/B) against the
    // fringe scan (proportional to n*B);  the pool itself is capped by the memory budget.
    u64 r = (u64)N, s2 = 0;
    while (s2 * s2 < r) s2++;                       // ceil(sqrt(n)) without libm
    // Reserve: the .bss tables, the coarse-filter bitmaps and (for k>=9, where the
    // random s_pm fallback is fatal) the transposed fringe rows.
    u64 overhead = (u64)(5 * k + 21) * N * 4;
    overhead += (u64)k * k * 4 * N;
    overhead += (u64)N * ((k <= 8) ? 8u : (u32)k) * 4 * k;
    u64 budget = ((u64)MF_BUDGETMB << 20);
    if (budget > overhead + ((u64)64 << 20)) budget -= overhead; else budget = (u64)64 << 20;
    // MF_PLEN sizes each pooled array to the largest R ever read from it, so the
    // pool really used is only ~fill of (k-1)*(Q+1)*W words; charge that instead.
#if MF_PLEN
    static const u32 kfill[7] = {72, 67, 62, 58, 54, 50, 46};   // per-array fill, k=4..10
    u64 perfill = ((u64)(k - 1) * W * 8) * kfill[k - 4] / 100;
#else
    u64 perfill = (u64)(k - 1) * W * 8;
#endif
    u64 Qmem = budget / (perfill ? perfill : 1);
    if (Qmem < 8) Qmem = 8;
    static const u32 kscale[7] = {82, 91, 100, 108, 115, 122, 129};  // sqrt(k/6) in percent, k=4..10
    u32 q = (u32)((s2 * MF_QCOEF + 99) / 100);
    q = (u32)(((u64)q * kscale[k - 4] + 99) / 100);
    if ((u64)q > Qmem) q = (u32)Qmem;
    if (q > N) q = N;
    g_Q = q;
    g_B = (N + q - 1) / q;
  }
  const u32 Q = g_Q, B = g_B;
  // [e4f] exact reciprocal for the orders-phase floor(x/B): with 2^divS >= B*N and
  // divM = ceil(2^divS/B), floor(x*divM/2^divS) == floor(x/B) for every x < N
  // (proof: x*divM/2^divS < x/B + 1/B <= floor(x/B) + 1).  N < 2^20 and B <= N, so
  // divS <= 40 and x*divM < 2^60 fits u64.
  u64 divM; int divS;
  { u64 t = (u64)B * (u64)N; divS = 0;
    while (divS < 64 && ((u64)1 << divS) < t) divS++;
    divM = ((u64)1 << divS) / B + 1; }
#if MF_PLEN
  g_plen_on = 1;   // independent of MF_WTRIM: lengths only, stride stays W
#endif
#if MF_WTRIM
  u32 Wpool = W;   // MF_WTRIM is KNOWN-BROKEN, see the warning above
#else
  const u32 Wpool = W;
#endif
#if MF_FILTAUTO
  if (!g_use_filt && B >= 400) g_use_filt = 1;   // coarse grid: the filter beats the scan
#endif
  if (g_use_filt && (u64)k * k * (g_Qc + 1) * W * 8 > ((u64)700 << 20)) g_use_filt = 0;
#if !MF_FILTAUTO
  g_use_filt = 0;
#endif
  // [W2] the coarse-cell ladder must be fixed up-front: s_bnde (boundaries in
  // value space) and the per-query cell index must use the SAME shift, otherwise
  // the filter stops being a tight superset (measured: 7.5x more candidates).
  if (g_use_filt) { int sh = 0; while ((sh < 32) && (((u64)1 << sh) < (u64)N)) sh++;
                    g_cshift = sh; }
  {
    int lo8[8], hi8[8];
    for (int e = 0; e < 8; e++) lo8[e] = (e < k) ? 0 : 0x7FFFFFFF;
    for (int e = 0; e < 8; e++) hi8[e] = (8 + e < k) ? 0 : 0x7FFFFFFF;
    khi8v = LDU((const __m256i *)lo8);
    khi8hv = LDU((const __m256i *)hi8);
  }
  const int K1 = k - 1;
  // ---------- per-dimension orders, ranks, tie info ----------
  for (int d = 0; d < k; d++) {
    const unsigned *xd = x[d];
    u32 *od = s_ord[d];
    // Counting sort + rank record in sequential passes: start[v] = #{q : x_d[q] < v}
    // is exactly gt[] of every point with x_d == v, and end[v]-1 = start[v+1]-1 is the
    // last rank of that tie group, so bd[] follows from start[v+1] too.  Both are value
    // lookups, so the per-point work is a sequential sweep of xd[] instead of the
    // previous random xd[od[j]] read plus random gt[]/bd[] writes.
    for (u32 i = 0; i <= N; i++) s_cntv[i] = 0;
    for (u32 i = 0; i < N; i++) {
      if (i + MF_ORDP < N) { u32 vf = xd[i + MF_ORDP]; Y14Z_PFW(&s_cntv[vf < N ? vf : 0]); }
      u32 v = xd[i]; s_cntv[v < N ? v : 0]++;
    }
    { u32 s = 0; for (u32 i = 0; i <= N; i++) { u32 c = s_cntv[i]; s_cntv[i] = s; s_tmp[i] = s; s += c; } }
    /* [x14aa-265] 跨相位同一张表:`s_bnde[d][c] = #{p : x_d[p] < CBOUND(c)}` 正是**本维刚刚算出的
       计数前缀** `s_cntv[·]` 在 v = CBOUND(c) 处的取值(同维、同刻)⇒ 顺手取 Qc+1 次,把后面那趟
       "按 s_ord[d] 重走 N 点 + 每点一次 xe[pe[ptr]] 随机读" 的重扫整块删掉(逐位同值)。 */
    if (g_use_filt) {
      u32 *bn = s_bnde + (size_t)d * (MAXQ + 2);
      for (u32 c = 0; c <= (u32)g_Qc; c++) {
        u64 v = CBOUND(c);
        bn[c] = (u32)(v >= (u64)N ? (u64)N : (u64)s_cntv[(u32)v]);
      }
    }
    { u32 *pp = s_pos[d];
      for (u32 i = 0; i < N; i++) {
        if (i + MF_ORDP < N) { u32 vf = xd[i + MF_ORDP]; if (vf >= N) vf = 0;
          Y14Z_PFW(&od[s_tmp[vf]]); }
        u32 v = xd[i]; if (v >= N) v = 0; u32 q = s_tmp[v]++; od[q] = i; pp[i] = q;
      } }
    { u32 *gt = s_gt[d];
      // [Y14Z-GTPF] gt 趟:`gt[i] = s_cntv[v]`(v = xd[i])是对 4 MB 计数数组的**随机读**,每维 1e6 次 × k 维。
      // 前瞻地址只经过顺序流 xd[](§2.19.339 无二级依赖)。与同相位已兑现的计数/散写两趟同形态。
      for (u32 i = 0; i < N; i++) {
        if (i + MF_ORDP_GT < N) { u32 vf = xd[i + MF_ORDP_GT]; if (vf >= N) vf = 0; Y14Z_PT(s_cntv + vf); }
        u32 v = xd[i]; if (v >= N) v = 0;
        gt[i] = s_cntv[v];
        u32 bb = (u32)(((u64)(s_cntv[v + 1] - 1u) * divM) >> divS);
        s_bdv[(size_t)d * N + i] = (unsigned short)(bb > Q - 1 ? Q - 1 : bb);
      } }
    BVAL(d, 0) = 0; FPOS(d, 0) = 0;
    for (u32 b = 1; b < Q; b++) {
      u32 pos = b * B < N ? b * B : N - 1;
      u32 v = xd[od[pos]];
      BVAL(d, b) = v;
      u32 gs = pos;
      while (gs > 0 && xd[od[gs - 1]] == v) gs--;
      FPOS(d, b) = gs;
    }
    BVAL(d, Q) = 0xFFFFFFFFu; FPOS(d, Q) = 0;
  }
  // [d4b] one blocked transpose: dim-major -> record layout.  The per-dim pass
  // above only ever stores 4 B per 32-B record (8/64 B of a line), so 8 passes
  // touch 8*N/2 lines with RFO; writing the dim-major plane is dense (4 MB per
  for (u32 i = 0; i < N; i++) {
    unsigned short *dst = s_bd + (size_t)i * MAXK;
    for (int d = 0; d < k; d++) dst[d] = s_bdv[(size_t)d * N + i];
  }
  for (u32 i = 0; i < N; i++) {
    u32 *p = PMROWK(i, g_pstr);
    for (int d = 0; d < k; d++) p[d] = x[d][i];
    for (int d = k; d < STRIDE; d++) p[d] = 0;
  }
  // ---------- coarse superset bitmaps over every dim order (fringe filter) ----------
#if MF_NOFILTB
  g_use_filt = 0;
#endif
#if MF_FB3
  /* [x14aa-265] 原重扫趟已删:s_bnde 在 orders 相按同维同刻的 s_cntv 前缀逐位取值 ✓ */
#endif
  if (g_use_filt) {
    u32 Qc = g_Qc;
    u64 wc = (u64)N / Qc + 1;
    size_t need2 = (size_t)k * k * (Qc + 1) * W * sizeof(u64);
    static u64 *fpool = 0; static size_t fcap = 0;
    if (need2 > fcap) { fpool = (u64 *)pool_alloc(need2 + 4096); fcap = need2; }
    if (fpool) {
      s_fbm = fpool; g_fbm_W = W;
#if MF_FB2
      // Sweep the e-order ONCE per dim e, keeping (k-1) running bitsets (one per
      // target dim d), and copy them out at each coarse-cell boundary.  The old
      // shape re-walked all N points for every one of the k(k-1) (d,e) pairs with
      // two L3-random reads each (xe[pe[ptr]] and s_pos[d][pe[ptr]]); here the
      // rank record is point-major so one 64B line yields every dim's rank, which
      // cuts the random reads by ~k and the whole build by ~2-2.5x at k>=8.
      for (int d = 0; d < k; d++)
        for (int e = 0; e < k; e++) {
          if (e == d) continue;
          u64 *b0 = s_fbm + (size_t)(d * k + e) * (Qc + 1) * W;
          for (u32 w = 0; w < W; w++) b0[w] = 0;
        }
      for (int e = 0; e < k; e++) {
        const unsigned *xe = x[e];
        const u32 *pe = s_ord[e];
        int dmap[MAXK], km1 = 0;
        for (int d = 0; d < k; d++) if (d != e) dmap[km1++] = d;
        for (int i = 0; i < km1; i++) { u64 *a = s_facc + (size_t)i * W; for (u32 w = 0; w < W; w++) a[w] = 0; }
        u32 ptr = 0;
        for (u32 c = 1; c <= Qc; c++) {
          u64 v = (u64)c * wc;
          if (v > 0xFFFFFFFFull) v = 0xFFFFFFFFull;
          while (ptr < N && (u64)xe[pe[ptr]] < v) {
            const u32 *pv = s_posp + (size_t)pe[ptr] * MAXK;
            for (int i = 0; i < km1; i++) {
              u32 q = pv[dmap[i]];
              s_facc[(size_t)i * W + (q >> 6)] |= 1ull << (q & 63);
            }
            ptr++;
          }
          for (int i = 0; i < km1; i++) {
            int d = dmap[i];
            u64 *dst = s_fbm + ((size_t)(d * k + e) * (Qc + 1) + c) * W;
            const u64 *src = s_facc + (size_t)i * W;
#if MF_NT
            { u32 w = 0;
              for (; w + 4 <= W; w += 4) _mm256_stream_si256((__m256i *)(dst + w), LDA((const __m256i *)(src + w)));
              for (; w < W; w++) dst[w] = src[w]; }
#else
            for (u32 w = 0; w < W; w++) dst[w] = src[w];
#endif
          }
        }
      }
#else
      for (int d = 0; d < k; d++) {
        for (int e = 0; e < k; e++) {
          if (e == d) continue;
          const unsigned *xe = x[e];
          const u32 *pe = s_ord[e];
          const u32 *pd = s_pos[d];
          u64 *base = s_fbm + (size_t)(d * k + e) * (Qc + 1) * W;
          for (u32 w = 0; w < W; w++) base[w] = 0;
          u64 *cur = s_acc;
          for (u32 w = 0; w < W; w++) cur[w] = 0;
          u32 ptr = 0;
          for (u32 c = 1; c <= Qc; c++) {
#if MF_FB3
            u32 pend = s_bnde[(size_t)e * (MAXQ + 2) + c];
#else
            u64 v = (u64)c * wc;
            if (v > 0xFFFFFFFFull) v = 0xFFFFFFFFull;
            u32 pend = ptr;
            { const unsigned *xe_ = xe; const u32 *pe_ = pe;
              while (pend < N && (u64)xe_[pe_[pend]] < v) pend++; }
#endif
            while (ptr < pend) {
              if (ptr + MF_ORP < N) Y14Z_PT(pd + pe[ptr + MF_ORP]);
              u32 q = pd[pe[ptr]]; cur[q >> 6] |= 1ull << (q & 63); ptr++; }
            u64 *dst = base + (size_t)c * W;
#if MF_NT
            { u32 w = 0;
              for (; w + 4 <= W; w += 4) _mm256_stream_si256((__m256i *)(dst + w), LDA((const __m256i *)(cur + w)));
              for (; w < W; w++) dst[w] = cur[w]; }
#else
            for (u32 w = 0; w < W; w++) dst[w] = cur[w];
#endif
          }
        }
      }
#endif
    } else { g_use_filt = 0; }
    _mm_sfence();
  }

  // ---------- fold dimension + bucket vector per query ----------
  {
    size_t mrn = (size_t)MAXK * MAXK * MAXQ;
    for (size_t z = 0; z < mrn; z++) s_maxr[z] = 0;
  }
  for (u32 i = 0; i < N; i++) {
    u32 best = 0xFFFFFFFFu; int ds = 0;
    for (int d = 0; d < k; d++) {
      u32 g = s_gt[d][i];
      if (g < best) { best = g; ds = d; }
    }
    s_g[i] = (u32)ds;
    // Largest R that will ever be read out of each (fold dim, dim, bucket) array:
    // the pooled array (ds,d,b) is only ever scanned over [0, maxR] words, so the
    // per-array length can be far below the group maximum (0.38n vs 0.93n at k=10).
    if (g_plen_on) {
      const unsigned short *bdv = s_bd + (size_t)i * MAXK;
      u32 *mr = s_maxr + ((size_t)ds * MAXK) * MAXQ;
      u32 bb = best;
      for (int d = 0; d < k; d++) {
        if (d == ds) continue;
        u32 b = bdv[d];
        if (bb > mr[(size_t)d * MAXQ + b]) mr[(size_t)d * MAXQ + b] = bb;
      }
    }
  }
  for (u32 i = 0; i < N; i++) s_qord[i] = i;
  // group by ds
  {
    for (u32 v = 0; v <= (u32)k; v++) s_cntv[v] = 0;
    for (u32 i = 0; i < N; i++) s_cntv[s_g[i] + 1]++;
    { u32 ac = 0; for (u32 v = 0; v <= (u32)k; v++) { u32 c = s_cntv[v]; s_cntv[v] = ac; ac += c; } }
    for (u32 i = 0; i < N; i++) { u32 id = s_qord[i]; s_tmp[s_cntv[s_g[id] + 1]++] = id; }
    for (u32 i = 0; i < N; i++) s_qord[i] = s_tmp[i];
  }
  u32 gstart[MAXK + 2];
  { u32 c = 0; for (int d = 0; d <= k; d++) { gstart[d] = c; while (c < N && (int)s_g[s_qord[c]] == d) c++; } gstart[k + 1] = c; }
  // Low 20 bits fit every point ID (N <= 1,000,005); upper bits fit bucket.
  // s_bdv is dimension-major, so each d's bucket lookups stay cache-local.
  for (int d = 0; d < k; d++) {
    u32 pos[MAXK];
    for (int ds = 0; ds < k; ds++) pos[ds] = gstart[ds];
    const u32 *od = s_ord[d];
    const unsigned short *bd = s_bdv + (size_t)d * N;
    for (u32 r = 0; r < N; r++) {
      u32 id = od[r];
      u32 dst = pos[s_g[id]]++;
      s_frord[d][dst] = id | ((u32)bd[id] << 20);
    }
  }
  // ---------- transposed coordinate rows (sequential fringe) ----------
#if MF_NOSDMP
  g_nosdmp = 1;
#endif
  if (!g_nosdmp) {
    u32 KS = k;
#if MF_KSPAD
    if (k <= 8) KS = 8;          // 32-byte aligned candidate rows for k<=8
#endif
    size_t per = (size_t)N * KS * 4;
    size_t lim = (size_t)150 << 20;
    if (k >= 9) lim = (size_t)470 << 20;   // k=9/10 need the rows: the random s_pm fallback is fatal
    if (per * k <= lim) {
      static u32 *pool = 0; static size_t cap = 0;
      if (per * k > cap) { pool = (u32 *)pool_alloc(per * k + 256); cap = per * k; }
      if (pool) {
        g_KS = KS;
        for (int d = 0; d < k; d++) {
          s_sdmp[d] = pool + (size_t)d * N * g_KS;
          const u32 *od = s_ord[d];
          u32 *dst = s_sdmp[d];
          const u32 KSx = g_KS;
          for (u32 j = 0; j < N; j++) {
#if MF_PFB > 0
            if (j + MF_PFB4 < N) _mm_prefetch((const char *)(PMROWK(od[j + MF_PFB4], g_pstr)), _MM_HINT_T0);
#endif
            const u32 *row = PMROWK(od[j], g_pstr);
            u32 *dp = dst + (size_t)j * KSx;
            for (u32 e = 0; e < KSx; e++) dp[e] = (e < (u32)k) ? row[e] : 0u;
          }
        }
      }
    }
  }
  // ---------- pool ----------
  u64 poolwords = (u64)K1 * (Q + 1) * W;
#if MF_PLEN
  if (g_plen_on) {
    u64 best = 0;
    for (int dsx = 0; dsx < k; dsx++) {
      u64 tot = 0;
      for (int e = 0; e < K1; e++) {
        int d = (e < dsx) ? e : e + 1;
        const u32 *mr = s_maxr + ((size_t)dsx * MAXK + d) * MAXQ;
        for (u32 b = 0; b <= Q; b++) {
          u32 RR = mr[b];
          u32 len = ((RR >> 6) + 8u) & ~7u;
          if (len > W) len = W;
          tot += len;
        }
      }
      if (tot > best) best = tot;
    }
    if (best && best < poolwords) poolwords = best;
  }
#endif
  size_t need = (size_t)poolwords * sizeof(u64);
  static u64 *pool = 0; static size_t cap2 = 0;
  if (need > cap2) { pool = (u64 *)pool_alloc(need + 4096); cap2 = need; }
  s_bs = pool;
  // ---------- groups ----------
  for (int ds = 0; ds < k; ds++) {
    u32 q0 = gstart[ds], q1 = gstart[ds + 1];
    if (q0 >= q1) continue;
#if MF_WTRIM
    {
      u32 mx = 1;
      for (u32 qi = q0; qi < q1; qi++) { u32 rr = s_gt[ds][s_qord[qi]]; if (rr > mx) mx = rr; }
      u32 wp = ((mx >> 6) + 8u) & ~7u;
      Wpool = (wp < W) ? wp : W;
    }
#endif
#if MF_PLEN
    // Per-(dim,bucket) array lengths inside the group.
    if (g_plen_on) {
      u64 tot = 0;
      for (int e = 0; e < K1; e++) {
        int d = (e < ds) ? e : e + 1;
        const u32 *mr = s_maxr + ((size_t)ds * MAXK + d) * MAXQ;
        u32 *po = s_pofs + (size_t)e * MAXQ;
        u32 *pl = s_plen + (size_t)e * MAXQ;
        for (u32 b = 0; b <= Q; b++) {
          // NOTE: bucket 0 is the EMPTY prefix set (all-zero array), but a query whose
          // bd[d]==0 still scans [0,R) words of it, so the array must be long enough --
          // sizing it to the fixed 8-word minimum reads past the zeroed region into the
          // next array.  Use the real per-bucket max R here, not 0.
          u32 RR = mr[b];
          u32 len = ((RR >> 6) + 8u) & ~7u;
          if (len > Wpool) len = Wpool;
          po[b] = (u32)tot; pl[b] = len; tot += len;
        }
      }
      if (tot > (u64)K1 * (Q + 1) * W) { g_plen_on = 0; }   // never; safety
    }
#endif
    // bit numbering = rank in dim ds
    const u32 *const nid = s_pos[ds];
    for (int e = 0; e < K1; e++) {
      int d = (e < ds) ? e : e + 1;
      const unsigned *xd = x[d];
      const u32 *od = s_ord[d];
      u64 *base = g_plen_on ? s_bs : (s_bs + (size_t)e * (Q + 1) * Wpool);
      u64 *cur = s_acc;
      for (u32 w = 0; w < Wpool; w++) cur[w] = 0;
      if (g_plen_on) {
        // bucket 0 is the empty prefix set; bd[] can be 0 so it must be materialised as zeros
        u64 *d0 = s_bs + s_pofs[(size_t)e * MAXQ];
        u32 l0 = s_plen[(size_t)e * MAXQ];
        for (u32 w = 0; w < l0; w++) d0[w] = 0;
      }
      u32 ptr = 0;
#if MF_BUILD_NOPOOL
      while (ptr < N) ptr++;
#else
      for (u32 b = 1; b <= Q; b++) {
        // {q : x_d[q] < BVAL(d,b)} is EXACTLY the prefix [0,FPOS(d,b)) of the dim-d order
        // (FPOS is the tie-group start containing rank b*B), so the per-point value compare
        // -- one random xd read per point per (ds,d) pair, k(k-1)N of them -- is redundant.
        // b==Q means "every point" and FPOS(d,Q) is the 0 sentinel, hence N.
        // Credited to agent a7f799ceb7e63b0cd (worth 4-5% at k=4/5 on the board).
        u32 pend = (b < Q) ? FPOS(d, b) : (u32)N;
        while (ptr < pend) {
          if (ptr + MF_ORP < N) Y14Z_PT(nid + od[ptr + MF_ORP]);
          u32 q = nid[od[ptr]]; cur[q >> 6] |= 1ull << (q & 63); ptr++; }
        u64 *dst = g_plen_on ? (base + s_pofs[(size_t)e * MAXQ + b])
                              : (base + (size_t)b * Wpool);
        u32 wlen = g_plen_on ? s_plen[(size_t)e * MAXQ + b] : Wpool;
#if MF_NT
        // The pool is written once and read 89 GB later, so a plain copy pays a
        // read-for-ownership DRAM read per line for nothing.  NT stores remove it
        // (measured: this loop was 4.58 GB / ~1.7 s, i.e. 2.7 GB/s, vs 12.5 GB/s
        // for a plain memset).
        {
          u32 w = 0;
          for (; w + 4 <= wlen; w += 4)
            _mm256_stream_si256((__m256i *)(dst + w), LDA((const __m256i *)(cur + w)));
          for (; w < wlen; w++) dst[w] = cur[w];
        }
#else
        for (u32 w = 0; w < wlen; w++) dst[w] = cur[w];
#endif
      }
      _mm_sfence();
#endif
    }
    switch (k) {
      case 4: query_group<4>(N, out, ds, q0, q1, Q, Wpool); break;
      case 5: query_group<5>(N, out, ds, q0, q1, Q, Wpool); break;
      case 6: query_group<6>(N, out, ds, q0, q1, Q, Wpool); break;
      case 7: query_group<7>(N, out, ds, q0, q1, Q, Wpool); break;
      case 8: query_group<8>(N, out, ds, q0, q1, Q, Wpool); break;
      case 9: query_group<9>(N, out, ds, q0, q1, Q, Wpool); break;
      default: query_group<10>(N, out, ds, q0, q1, Q, Wpool); break;
    }
  }
}

void count_4d(int n, const unsigned *x[4], unsigned *out) { solve_mf((u32)n, (const unsigned **)x, out, 4); }
void count_5d(int n, const unsigned *x[5], unsigned *out) { solve_mf((u32)n, (const unsigned **)x, out, 5); }
void count_6d(int n, const unsigned *x[6], unsigned *out) { solve_mf((u32)n, (const unsigned **)x, out, 6); }
void count_7d(int n, const unsigned *x[7], unsigned *out) { solve_mf((u32)n, (const unsigned **)x, out, 7); }
void count_8d(int n, const unsigned *x[8], unsigned *out) { solve_mf((u32)n, (const unsigned **)x, out, 8); }
void count_9d(int n, const unsigned *x[9], unsigned *out) { solve_mf((u32)n, (const unsigned **)x, out, 9); }
void count_10d(int n, const unsigned *x[10], unsigned *out) { solve_mf((u32)n, (const unsigned **)x, out, 10); }

#ifdef LOCAL_TEST
static void brute_nd(int n, const u32 **x, u32 *out, int k) {
  for (int i = 0; i < n; i++) {
    u32 c = 0;
    for (int j = 0; j < n; j++) {
      int ok = 1;
      for (int d = 0; d < k; d++) if (!(x[d][j] < x[d][i])) { ok = 0; break; }
      c += ok;
    }
    out[i] = c;
  }
}
int main(int argc, char **argv) {
  int k = (argc > 1) ? atoi(argv[1]) : 6;
  int n = (argc > 2) ? atoi(argv[2]) : 200;
  int seed = (argc > 3) ? atoi(argv[3]) : 1;
  int mode = (argc > 4) ? atoi(argv[4]) : 0;
  int qq = (argc > 5 && atoi(argv[5]) > 0) ? atoi(argv[5]) : 0;
  g_Q = qq > 0 ? (u32)qq : 0u;              /* [x14aa] (203): 不抢设引擎自推导的全局项 */
  if (g_Q) g_B = (u32)((n + g_Q - 1) / g_Q);  else g_B = 0;
  if (argc > 6) g_nosort = atoi(argv[6]);
  if (argc > 7) g_nosdmp = atoi(argv[7]);
  if (argc > 8) g_skip_and = atoi(argv[8]);
  if (argc > 9) g_skip_fringe = atoi(argv[9]);
  if (argc > 10) g_use_filt = atoi(argv[10]);
  if (argc > 11) g_lexsort = atoi(argv[11]);
  const int dm = (mode >= 10) ? mode - 10 : mode;
  srand(seed);
  static u32 *xs[10];
  u32 *out = (u32 *)malloc(sizeof(u32) * n);
  u32 *ref = (u32 *)malloc(sizeof(u32) * n);
  for (int d = 0; d < k; d++) {
    xs[d] = (u32 *)malloc(sizeof(u32) * n);
    for (int i = 0; i < n; i++) {
      if (dm == 0) xs[d][i] = (u32)(rand() % n);
      else if (dm == 1) xs[d][i] = (u32)(rand() % 3);
      else if (dm == 2) xs[d][i] = 0;
      else if (dm == 3) xs[d][i] = (u32)(n - 1 - (rand() % n));
      else if (dm == 4) xs[d][i] = (u32)(i);
      else xs[d][i] = (u32)(rand() % n);
    }
  }
  if (mode >= 10) {
    struct timespec t0, t1;
    clock_gettime(CLOCK_MONOTONIC, &t0);
    switch (k) {
      case 4: count_4d(n, (const unsigned **)xs, out); break;
      case 5: count_5d(n, (const unsigned **)xs, out); break;
      case 6: count_6d(n, (const unsigned **)xs, out); break;
      case 7: count_7d(n, (const unsigned **)xs, out); break;
      case 8: count_8d(n, (const unsigned **)xs, out); break;
      case 9: count_9d(n, (const unsigned **)xs, out); break;
      default: count_10d(n, (const unsigned **)xs, out); break;
    }
    clock_gettime(CLOCK_MONOTONIC, &t1);
    double ms = (t1.tv_sec - t0.tv_sec) * 1e3 + (t1.tv_nsec - t0.tv_nsec) / 1e6;
    u64 s = 0; for (int i = 0; i < n; i++) s += out[i];
    printf("k=%d n=%d Q=%u TIME %.1f ms  checksum %llu\n", k, n, g_Q, ms, s);
    return 0;
  }
  switch (k) {
    case 4: count_4d(n, (const unsigned **)xs, out); break;
    case 5: count_5d(n, (const unsigned **)xs, out); break;
    case 6: count_6d(n, (const unsigned **)xs, out); break;
    case 7: count_7d(n, (const unsigned **)xs, out); break;
    case 8: count_8d(n, (const unsigned **)xs, out); break;
    case 9: count_9d(n, (const unsigned **)xs, out); break;
    default: count_10d(n, (const unsigned **)xs, out); break;
  }
  brute_nd(n, (const u32 **)xs, ref, k);
  int bad = 0;
  for (int i = 0; i < n; i++) if (out[i] != ref[i]) { if (bad < 5) printf("MISMATCH i=%d got=%u ref=%u\n", i, out[i], ref[i]); bad++; }
  printf("k=%d n=%d mode=%d Q=%u %s (%d mismatches)\n", k, n, mode, g_Q, bad ? "FAIL" : "OK", bad);
  return bad != 0;
}
#endif

CompilationN/AN/ACompile OKScore: N/A

Testcase #15.401 s839 MB + 108 KBAcceptedScore: 100


Judge Duck Online | 评测鸭在线
Server Time: 2026-11-04 09:40:43 | Loaded in 1 ms | Server Status
个人娱乐项目,仅供学习交流使用 | 捐赠