chart_achievement: 均摊改为按键类型的整数分配,可列举多种可能

- score.py:新增 alloc_flow(最小费用流读回整数分配)、_fill_fluff(CP/Perfect 按剩余容量补满)、
  _alloc_greedy_int(最大余数法取整均摊)、_enum_allocations(按列 DFS 枚举坏音符落点,
  带容量剪枝、节点/时间预算与均匀抽样)、alloc_options(取整均摊 + 流最优/最差 + 枚举结果去重,
  按失分升序);AllocatedResult 增加 options/exhaustive 与 achievement_of(),
  可给出每一种整数分配对应的达成率。
- chart_achievement.py:print_allocated 改为打印所有可能的整数分配
  (序号/达成率/失分/各列 CP-P-G-GD-M),新增 --show N(默认 20,0 = 全部),
  JSON 增加 achievement_min/achievement_max/alloc_values/alloc_exhaustive/alloc_options。
- README:③ 节改写为「整数分配 + 多种可能」,补充 --show 与未枚举完时的说明。
This commit is contained in:
Txiaochen committed 2026-11-14 04:05:47 +08:00
1 parent 72dce56dd1
commit d0763fa796
3 files changed
+481 -64

No files matched your search

+32 -23
View File
@@ -97,41 +97,49 @@ python chart_achievement.py --chart "<...>\000008_03.ma2" --cp 290 --perfect 8 -
DX 分在三种方式下都是确定的:`3×CP + 2×Perfect + 1×Great`。
### ③ 汇总 + 绝赞单列:给总数也能得到确切值
### ③ 汇总 + 绝赞单列:给总数也能列出所有整数分配
```powershell
python chart_achievement.py --game "<...>\Sinmai_Data" --music-id 8 --level 3 --cp 296 --perfect 6 --break 0/6/0/0/0 # 3 = MASTER
python chart_achievement.py --game "<...>\Sinmai_Data" --music-id 8 --level 3 --cp 290 --perfect 8 --great 3 --good 1 --break 6 --show 8 # 3 = MASTER
```
`--cp` / `--perfect` / `--great` / `--good` / `--miss` 给**总**判定数,同时用 `--break`
单独给绝赞那一列的判定数(写法同 ①:`CP/Perfect/Great/Good/Miss`,后面可省略)。
- 绝赞部分**精确**:绝赞奖励分只由绝赞自己的判定决定,单列后这块没有歧义;
- 其余音符按各自**音符数量均摊**:把判定数按剩余容量比例摊到各列,失分取加权平均;
- EX 音符(`XTP`/`XST`/`BXTAP`/`BXSTR`)只能判 Critical 或 Miss,均摊时单独一列,
Great/Good 不会落到 EX 上。
于是达成率是一个**确切数值**(不是区间):
- 其余音符**按键类型分列**:Tap/Star/Touch、EX、Hold 系、Slide 系。同一份总数落在不同列上
失分不同(Tap 的 Great 扣 100、Slide 的扣 300),所以达成率不止一种;
- 于是输出**所有可能的整数分配**,每一种都是「真的能打出来」的,各给一个确切的达成率:
```
判定输入(汇总判定数 + 绝赞单列)
Critical Perfect 296
Perfect 6
合计 302 / 302
绝赞列 (6 个) Perfect 6
其余 296 个音符按音符数量均摊:Tap/Star/Touch 263 · Hold 系 14 · Slide 系 19
判定 Tap/Star/Touch Hold 系 Slide 系
CP 263.00 14.00 19.00
结果
达成率 100.7500% (确切值)
DX 分 900 / 906 (99.34%)
失分 绝赞 0 + 其余 0 = 0 / 189000
绝赞奖励 450 / 600 (75.0000%)
可能的整数分配(每格 CP-P-G-GD-M,就是该按键类型上的音符个数)
# 达成率 失分 Tap/Star/Touch Hold 系 Slide 系
1 100.7090% 550 252-7-3-1-0 14-0-0-0-0 18-1-0-0-0 <- 按容量取整均摊
2 100.5503% 850 254-7-1-1-0 13-0-1-0-0 17-1-1-0-0
3 100.4709% 1000 255-7-1-0-0 11-0-2-1-0 18-1-0-0-0
(共 19 种,这里均匀显示 8 种;用 --show 0 显示全部,或用 --json 取数据)
```
如果这些判定数在这个谱面上**不可能同时出现**(例如 Great 的个数超过非 EX 音符数),
- 每行末尾标 `<- 按容量取整均摊` 的那份,就是把判定数按剩余容量比例摊开再取整的结果
(老版本会显示成 252.17 这样的分数,现在一律是整数);
- `--show N` 控制最多列几行(默认 20,`0` = 全部;超过时均匀抽样并提示);
- 组合太多(例如上千音符的谱面)时只列举能枚举到的那一部分,会提示
`[注意] 组合太多,只枚举了一部分`;但「可能范围」的上下界始终是精确的
(最小 / 最大失分由最小费用流求出);
- EX 音符(`XTP`/`XST`/`BXTAP`/`BXSTR`)只能判 Critical 或 Miss,所以单独一列,
Great/Good 不会落到 EX 上;
- 如果这些判定数在这个谱面上**不可能同时出现**(例如 Great 的个数超过非 EX 音符数),
会直接报错,而不是硬算一个值。
```
结果
达成率 100.7090% (按容量取整均摊的这一份)
可能范围 100.7090% ~ 100.1270% (19 种整数分配,前者最好、后者最差)
DX 分 889 / 906 (98.12%)
失分 绝赞 0 + 其余 550 = 550 / 189000
绝赞奖励 600 / 600 (100.0000%)
```
## 反向:已知达成率 → 判定组合 + DX 分
```powershell
@@ -229,8 +237,9 @@ CP 的物理可能范围(Perfect 只能落在绝赞音符上,所以 CP 不
- 汇总模式(只给总判定数、不给绝赞列)只能给区间——这不是精度问题,是信息量不够:同样的
判定总数,落在绝赞上和落在 Tap 上扣的分不同。要确切值就按类别给(`--tap` / `--hold` /
`--slide` / `--break`),或者只把绝赞单列出来(③)。
- ③ 的「其余音符均摊」是一个模型:真实玩家不可能把 Great 精确地按音符比例摊开。它给的是
一个确定的参考值,且一定落在该谱面真正能打出的达成率区间内。
- ③ 列出的每一种整数分配都是「按列容量 + EX 约束」验证过的真实可能;标着
`<- 按容量取整均摊` 的那份只是其中一个有代表性的取法(最接近按音符数量比例),
不代表真实玩家一定这样打。
- 精确反向只验证坏音符数 ≤ 12 的组合(见上文)。
- 若 `.ma2` 里的 `T_NUM_ALL` 与解析出的计分音符数不一致,会在输出里给警告
(全部 5419 个游戏谱面实测一致)。
+96 -25
View File
@@ -15,6 +15,7 @@ import json
import os
import re
import sys
import unicodedata
from fractions import Fraction
from typing import Dict, List, Optional
@@ -162,8 +163,8 @@ def print_forward(chart: Chart, result) -> None:
print(" 区间下界 = 扣分都落在权重最高的音符上,上界 = 都落在权重最低的音符上。")
if th.counts.get("break", 0) + th.counts.get("break_flat", 0) \
+ th.counts.get("break_slide", 0) + th.counts.get("ex_break", 0):
print(" 想要一个确切数值:再加一列 --break \"CP/Perfect/Great/Good/Miss\" 给绝赞的判定数")
print(" (绝赞精确、其余按数量均摊);或者用 --tap / --hold / --slide / --break 全部按类别给。")
print(" 想要确切的数值:加 --break \"CP/Perfect/Great/Good/Miss\" 单列绝赞,")
print(" 其余音符就会按键类型列出所有整数分配;或者用 --tap / --hold / --slide / --break 全按类别给。")
else:
print(" 想要一个确切数值:用 --tap / --hold / --slide / --break 按类别给判定数。")
print(LINE)
@@ -222,8 +223,40 @@ def _num(value) -> str:
return str(v.numerator) if v.denominator == 1 else "%.2f" % float(v)
def print_allocated(chart: Chart, result) -> None:
def _dwidth(text: str) -> int:
"""终端显示宽度(中文算 2 列)。"""
return sum(2 if unicodedata.east_asian_width(ch) in "WF" else 1 for ch in text)
def _ljust(text: str, width: int) -> str:
return text + " " * max(0, width - _dwidth(text))
def _rjust(text: str, width: int) -> str:
return " " * max(0, width - _dwidth(text)) + text
def _alloc_cell(row: Dict[str, int]) -> str:
return "-".join(str(int(row.get(j, 0))) for j in JUDGMENTS)
def _sample_indexes(total: int, show: int) -> List[int]:
if show <= 0 or total <= show:
return list(range(total))
if show == 1:
return [0]
picked: List[int] = []
for i in range(show):
idx = round(i * (total - 1) / (show - 1))
if idx not in picked:
picked.append(idx)
return picked
def print_allocated(chart: Chart, result, show: int = 20) -> None:
th = result.theory
cols = result.columns
options = list(result.options) or [(result.loss_other, result.allocated)]
print(LINE)
print("判定输入(汇总判定数 + 绝赞单列)")
for j in JUDGMENTS:
@@ -236,42 +269,66 @@ def print_allocated(chart: Chart, result) -> None:
print(" 绝赞列 %-10s %s" % ("(%d 个)" % bcap, " · ".join(parts) if parts else "-"))
else:
print(" 绝赞列 %-10s 该谱面没有绝赞音符(达成率上限 100.0000%%)" % "(0 个)")
cols = result.columns
if cols:
nb = sum(alloc_capacity(th, c) for c in cols)
print(" 其余 %d 个音符按音符数量均摊:%s"
print(" 其余 %d 个音符按键类型分列:%s"
% (nb, " · ".join("%s %d" % (_SHORT_TITLE[c], alloc_capacity(th, c))
for c in cols)))
print(" %-8s" % "判定" + "".join("%14s" % _SHORT_TITLE[c] for c in cols))
for j in JUDGMENTS:
row = [result.allocated.get(c, {}).get(j, Fraction(0)) for c in cols]
if not any(row):
continue
print(" %-8s" % _EXACT_KEY_LABEL[j]
+ "".join("%14.2f" % float(v) for v in row))
print(LINE)
print("结果")
print(" 达成率 %s (确切值)" % pct(result.achievement))
print(" 达成率 %s (按容量取整均摊的这一份)" % pct(result.achievement))
if len(options) > 1:
print(" 可能范围 %s ~ %s (%d 种整数分配,前者最好、后者最差)"
% (pct(result.achievement_of(options[0][0])),
pct(result.achievement_of(options[-1][0])), len(options)))
print(" DX 分 %d / %d (%.2f%%)"
% (result.dx, th.max_dx, 100.0 * result.dx / th.max_dx if th.max_dx else 0.0))
loss_all = result.loss_break + result.loss_other
if th.all_perfect_score:
print(" 失分 绝赞 %d + 其余 %s = %s / %d"
% (result.loss_break, _num(result.loss_other), _num(loss_all),
th.all_perfect_score))
print(" 失分 绝赞 %d + 其余 %d = %d / %d"
% (result.loss_break, result.loss_other, loss_all, th.all_perfect_score))
if th.break_bonus_score:
print(" 绝赞奖励 %d / %d (%.4f%%)"
% (result.bonus_break, th.break_bonus_score,
100.0 * result.bonus_break / th.break_bonus_score))
if cols:
print()
print(" 说明:绝赞的奖励分只由绝赞音符自己的判定决定,绝赞单列后这部分是精确的;")
print(" 其余音符按各自音符数量均摊(EX 音符只能判 Critical/Miss,单独一列),")
print(" 失分取加权平均,所以得到的是一个确定数值。")
print("可能的整数分配(每格 CP-P-G-GD-M,就是该按键类型上的音符个数)")
head = (" " + _rjust("#", 3) + " " + _rjust("达成率", 9) + " "
+ _rjust("失分", 7) + " ")
for c in cols:
head += _ljust(_SHORT_TITLE[c], 16)
print(head.rstrip())
idxs = _sample_indexes(len(options), show)
gi = next((i for i, (loss, _t) in enumerate(options)
if loss == result.loss_other), None)
if gi is not None and gi not in idxs:
idxs = sorted(idxs + [gi])
for n, i in enumerate(idxs, 1):
loss, table = options[i]
note = " <- 按容量取整均摊" if loss == result.loss_other else ""
print((" %3d %9s %7d " % (n, pct(result.achievement_of(loss)), loss)
+ "".join(_ljust(_alloc_cell(table.get(c, {})), 16) for c in cols)).rstrip()
+ note)
if len(idxs) < len(options):
print(" (共 %d 种,这里均匀显示 %d 种;用 --show 0 显示全部,或用 --json 取数据)"
% (len(options), len(idxs)))
if not result.exhaustive:
print(" [注意] 组合太多,只枚举了一部分(按预算抽样),上面的列表不是全部;"
"列出的每一种都是真的,上下界也是精确的。")
print()
print(" 说明:同一份汇总判定数可以落在不同的按键类型上,失分不同,达成率也就不同;")
if result.exhaustive:
print(" 上表列出了这个谱面上所有可能的整数分配,DX 分与判定落在哪一类音符无关。")
else:
print(" 上表只列出了枚举到的一部分整数分配,DX 分与判定落在哪一类音符无关。")
ex_notes = th.counts.get("ex", 0)
if ex_notes:
print(" [注意] 谱面里有 %d 个 EX 音符(ExTap/ExStar),判定表只允许 Critical 或 Miss;"
print(" [注意] 谱面里有 %d 个 EX 音符(ExTap/ExStar),判定表只允许 Critical 或 Miss,"
% ex_notes)
print(" 均摊时已把它们单列,Great/Good 不会落到 EX 上。")
print(" 所以 EX 单独成列,Great/Good 不会落到 EX 上。")
print(LINE)
@@ -401,7 +458,6 @@ def interactive(args) -> None:
except SystemExit:
chart = None
th = theory_from_chart(chart)
print_chart(chart, th)
mode = ask("计算模式:1) 汇总判定数(估计值 + 区间)\n"
" 2) 汇总判定数 + 绝赞单列,其余均摊(确切值)\n"
@@ -589,21 +645,33 @@ def run_allocated(chart: Chart, th: Theory, raw: Dict[str, Optional[int]],
except ValueError as exc:
die(str(exc))
if args.json:
options = list(result.options) or [(result.loss_other, result.allocated)]
print(to_json(chart, th, {
"mode": "forward_allocated",
"judges": judges,
"break_judges": result.break_spec,
"allocated": {c: {j: float(v) for j, v in row.items()}
"allocated": {c: {j: int(v) for j, v in row.items()}
for c, row in result.allocated.items()},
"achievement": float(result.achievement),
"achievement_min": float(result.achievement_of(options[-1][0])),
"achievement_max": float(result.achievement_of(options[0][0])),
"dx_score": result.dx,
"loss_break": result.loss_break,
"loss_other": float(result.loss_other),
"loss_other": result.loss_other,
"bonus_break": result.bonus_break,
"alloc_values": len(options),
"alloc_exhaustive": result.exhaustive,
"alloc_options": [
{"loss_other": loss,
"achievement": float(result.achievement_of(loss)),
"columns": {c: {j: int(v) for j, v in row.items()}
for c, row in table.items()}}
for loss, table in options[:200]
],
}))
return
print_chart(chart, th)
print_allocated(chart, result)
print_allocated(chart, result, getattr(args, "show", 20))
def run_forward(chart: Chart, th: Theory,
@@ -711,6 +779,9 @@ def build_parser() -> argparse.ArgumentParser:
ex.add_argument("--break-great50", type=int, metavar="N",
help="绝赞 Great 里失分 50%% 的个数(Great3rd)")
fw.add_argument("--show", type=int, default=20, metavar="N",
help="均摊模式下最多列出多少种整数分配(默认 20;0 = 全部)")
rv = p.add_argument_group("反向计算:已知达成率")
rv.add_argument("--achievement", metavar="A", help="目标达成率(如 99.5 / 100.5)")
rv.add_argument("--mode", choices=("exact", "range"), default="exact",
+353 -16
View File
@@ -258,8 +258,9 @@ class _MinCostFlow:
def add_edge(self, u: int, v: int, cap: int, cost: int) -> None:
if cap <= 0:
return
self.graph[u].append([v, cap, cost, len(self.graph[v])])
self.graph[v].append([u, 0, -cost, len(self.graph[u]) - 1])
# 第 5 个字段记原始容量,事后按 (cap0 - cap) 就能读出这条边走了多少流量
self.graph[u].append([v, cap, cost, len(self.graph[v]), cap])
self.graph[v].append([u, 0, -cost, len(self.graph[u]) - 1, 0])
def min_cost(self, s: int, t: int, need: int) -> Optional[int]:
if need <= 0:
@@ -280,7 +281,7 @@ class _MinCostFlow:
in_queue[u] = False
du = dist[u]
for i, edge in enumerate(self.graph[u]):
v, cap, cost, _rev = edge
v, cap, cost = edge[0], edge[1], edge[2]
if cap > 0 and du + cost < dist[v]:
dist[v] = du + cost
prev_v[v] = u
@@ -627,22 +628,353 @@ def _alloc_spread(th: Theory, rest: Dict[str, int],
return table
_SPREAD_CACHE: Dict[int, Tuple[int, ...]] = {}
def _spread_order(hi: int) -> Tuple[int, ...]:
"""0..hi 的取值顺序:先两端,再向中间收(hi, 0, hi-1, 1, ...)。
先给两端很关键:某个判定可能只装得进某一列(例如只有 tap 放得下全部
Great),这一层就必须能取到接近 hi 的值,否则搜索一开局就全被容量剪掉。
同时两端交替也保证预算用完时样本仍铺开在整个区间上。
"""
hi = int(hi)
if hi < 0:
hi = 0
cached = _SPREAD_CACHE.get(hi)
if cached is not None:
return cached
order: List[int] = []
lo, up = 0, hi
while lo <= up:
order.append(up)
if lo != up:
order.append(lo)
lo += 1
up -= 1
result = tuple(order)
if hi <= 4096:
_SPREAD_CACHE[hi] = result
return result
def _largest_remainder(weights: Dict[str, int], total: int) -> Optional[Dict[str, int]]:
"""按权重把 total 拆成整数(最大余数法);装不下返回 None。"""
usable = [c for c, w in weights.items() if w > 0]
avail = sum(weights[c] for c in usable)
if total < 0 or avail < total:
return None
shares = {c: Fraction(total * weights[c], avail) for c in usable}
take = {c: int(shares[c]) for c in usable}
remain = total - sum(take.values())
while remain > 0:
for c in sorted(usable, key=lambda c: (-(shares[c] - take[c]), -weights[c], c)):
if remain <= 0:
break
if take[c] < weights[c]:
take[c] += 1
remain -= 1
return take
def alloc_flow(th: Theory, rest: Dict[str, int], cols: Sequence[str],
want_max: bool = False
) -> Optional[Tuple[int, Dict[str, Dict[str, int]]]]:
"""求一个整数可行分配,并让总失分最小 / 最大。
源 -> 判定(容量=该判定个数) -> 列(容量=该列音符数) -> 汇;
只连 ALLOC_OPTIONS 允许的格(EX 列连不到 Great/Good)。
返回 (总失分, 列 -> 判定 -> 整数个数);无解返回 None。
"""
caps = {c: alloc_capacity(th, c) for c in cols}
need = sum(int(rest.get(j, 0) or 0) for j in JUDGMENTS)
if need <= 0:
return (0, {c: {} for c in cols})
src = 0
jb = 1
cb = jb + len(JUDGMENTS)
sink = cb + len(cols)
flow = _MinCostFlow(sink + 1)
for i, j in enumerate(JUDGMENTS):
n = int(rest.get(j, 0) or 0)
if n:
flow.add_edge(src, jb + i, n, 0)
for k, c in enumerate(cols):
if caps[c]:
flow.add_edge(cb + k, sink, caps[c], 0)
links: List[Tuple[int, int, str, str]] = []
for i, j in enumerate(JUDGMENTS):
n = int(rest.get(j, 0) or 0)
if not n:
continue
for k, c in enumerate(cols):
if not caps[c] or j not in ALLOC_OPTIONS[c]:
continue
cost = ALLOC_OPTIONS[c][j]
flow.add_edge(jb + i, cb + k, min(n, caps[c]),
-cost if want_max else cost)
links.append((jb + i, len(flow.graph[jb + i]) - 1, j, c))
if flow.min_cost(src, sink, need) is None:
return None
table: Dict[str, Dict[str, int]] = {c: {} for c in cols}
loss = 0
for u, idx, j, c in links:
edge = flow.graph[u][idx]
used = int(edge[4]) - int(edge[1])
if used:
table[c][j] = table[c].get(j, 0) + used
loss += used * ALLOC_OPTIONS[c][j]
return (loss, table)
def _fill_fluff(cols: Sequence[str], caps: Dict[str, int],
bad: Dict[str, Dict[str, int]], rest: Dict[str, int]
) -> Optional[Dict[str, Dict[str, int]]]:
"""坏音符定好之后,把 CP / Perfect 按剩余容量比例补满各列。
CP 和 Perfect 在得分上完全一样(只有绝赞的奖励分不同,而绝赞是单列的),
所以这里的拆分只是为了「分按键类型」看得清楚。
"""
left = {c: caps[c] - sum(bad.get(c, {}).values()) for c in cols}
if any(v < 0 for v in left.values()):
return None
perfect_rem = int(rest.get("perfect", 0) or 0)
cp_rem = int(rest.get("cp", 0) or 0)
weights = {c: left[c] for c in cols if "perfect" in ALLOC_OPTIONS[c]}
perfect = _largest_remainder(weights, perfect_rem) if perfect_rem else {}
if perfect is None:
return None
total_left = sum(left.values())
if cp_rem != total_left - perfect_rem:
return None
table: Dict[str, Dict[str, int]] = {}
for c in cols:
prof = dict(bad.get(c, {}))
if perfect.get(c):
prof["perfect"] = perfect[c]
cp_here = left[c] - perfect.get(c, 0)
if cp_here:
prof["cp"] = cp_here
table[c] = prof
return table
def _alloc_greedy_int(th: Theory, rest: Dict[str, int], cols: Sequence[str]
) -> Optional[Tuple[int, Dict[str, Dict[str, int]]]]:
"""把分数均摊取整:最大余数法,每列不超过音符数,每个判定正好用完。"""
left = {c: alloc_capacity(th, c) for c in cols}
table: Dict[str, Dict[str, int]] = {c: {} for c in cols}
loss = 0
for j in _ALLOC_FILL_ORDER:
n = int(rest.get(j, 0) or 0)
if not n:
continue
usable = [c for c in cols if j in ALLOC_OPTIONS[c] and left[c] > 0]
take = _largest_remainder({c: left[c] for c in usable}, n)
if take is None:
return None
for c in usable:
if take[c]:
table[c][j] = table[c].get(j, 0) + take[c]
left[c] -= take[c]
loss += take[c] * ALLOC_OPTIONS[c][j]
return (loss, table)
ALLOC_NODE_BUDGET = 150000
ALLOC_TIME_BUDGET = 1.0
ALLOC_BREADTH = 12
ALLOC_FULL_LIMIT = 100000
def _enum_allocations(th: Theory, rest: Dict[str, int], cols: Sequence[str],
node_budget: int = ALLOC_NODE_BUDGET,
time_budget: float = ALLOC_TIME_BUDGET,
breadth: int = ALLOC_BREADTH
) -> Tuple[Dict[int, Dict[str, Dict[str, int]]], bool]:
"""按列 DFS 枚举所有整数分配。
只枚举坏音符(Great/Good/Miss)落在哪一列——CP / Perfect 不影响得分,
定好坏音符后按剩余容量比例补(见 _fill_fluff)。
某一层可取值太多时只均匀取 breadth 个(先中间、再二分),这样预算内也能
覆盖到每个维度,而不是把预算全花在扫第一维上;此时标记为「未穷举」。
返回 (总失分 -> 该失分下的一个分配, 是否真的穷举完)。
"""
caps = {c: alloc_capacity(th, c) for c in cols}
n = len(cols)
allowed = [{j for j in _BAD_JUDGMENTS if j in ALLOC_OPTIONS[c]} for c in cols]
suffix: List[Dict[str, int]] = []
suffix_total: List[int] = []
for i in range(n + 1):
suffix.append({j: sum(caps[cols[k]] for k in range(i, n) if j in allowed[k])
for j in _BAD_JUDGMENTS})
suffix_total.append(sum(caps[cols[k]] for k in range(i, n)))
# 组合空间不大时干脆全部枚举(不影响穷举性),大了才抽样
rem_all = {j: int(rest.get(j, 0) or 0) for j in _BAD_JUDGMENTS}
est = 1
for i in range(n):
ways = 1
for j in _BAD_JUDGMENTS:
if j in allowed[i]:
ways *= min(rem_all[j], caps[cols[i]]) + 1
# 同一列内的坏音符总数还受该列容量限制
cap = caps[cols[i]]
ways = min(ways, (cap + 1) * (cap + 2) * (cap + 3) // 6)
est *= ways
if est > ALLOC_FULL_LIMIT:
break
if est <= ALLOC_FULL_LIMIT:
breadth = 10 ** 9
node_budget = max(node_budget, min(est * 3, 400000))
found: Dict[int, Dict[str, Dict[str, int]]] = {}
state = {"nodes": 0, "stop": False, "truncated": False}
deadline = time.monotonic() + max(0.0, time_budget)
def over_budget() -> bool:
if state["stop"]:
return True
state["nodes"] += 1
if state["nodes"] > node_budget:
state["stop"] = True
elif state["nodes"] % 256 == 0 and time.monotonic() > deadline:
state["stop"] = True
return state["stop"]
def record(bad: Dict[str, Dict[str, int]], loss: int) -> None:
table = _fill_fluff(cols, caps, bad, rest)
if table is None:
return
if loss not in found:
found[loss] = table
def walk(i: int, remaining: Dict[str, int],
bad: Dict[str, Dict[str, int]], loss: int) -> None:
if over_budget():
return
c = cols[i]
cap = caps[c]
if i == n - 1:
# 最后一列:剩下的坏音符只能全放这里
used = sum(remaining.values())
if used > cap:
return
if any(remaining[j] and j not in allowed[i] for j in _BAD_JUDGMENTS):
return
prof = {j: v for j, v in remaining.items() if v}
bad2 = dict(bad)
bad2[c] = prof
record(bad2, loss + sum(v * ALLOC_OPTIONS[c][j] for j, v in prof.items()))
return
js = [j for j in _BAD_JUDGMENTS if j in allowed[i]]
prof: Dict[str, int] = {}
def choose(k: int, used: int) -> None:
if state["stop"]:
return
if k == len(js):
rem2 = dict(remaining)
for j, v in prof.items():
rem2[j] -= v
if any(v < 0 for v in rem2.values()):
return
# 剩下的坏音符只能塞进后面几列(不够的位置由 CP / Perfect 补)
if sum(rem2.values()) > suffix_total[i + 1]:
return
for j in _BAD_JUDGMENTS:
if rem2[j] > suffix[i + 1][j]:
return
bad2 = dict(bad)
bad2[c] = {j: v for j, v in prof.items() if v}
walk(i + 1, rem2, bad2,
loss + sum(v * ALLOC_OPTIONS[c][j] for j, v in prof.items()))
return
j = js[k]
hi = min(int(remaining.get(j, 0)), cap - used)
order = _spread_order(hi)
if len(order) > breadth:
state["truncated"] = True
order = order[:breadth]
for v in order:
prof[j] = v
choose(k + 1, used + v)
if state["stop"]:
break
prof.pop(j, None)
choose(0, 0)
walk(0, {j: int(rest.get(j, 0) or 0) for j in _BAD_JUDGMENTS}, {}, 0)
return (found, not state["stop"] and not state["truncated"])
def alloc_options(th: Theory, rest: Dict[str, int], cols: Sequence[str]
) -> Tuple[List[Tuple[int, Dict[str, Dict[str, int]]]], bool]:
"""列出这批判定数在这个谱面上的所有整数分配(按总失分升序)。
返回 ([(总失分, 分配)], 是否穷举完整)。没穷举时也一定包含最小失分、
最大失分和按容量取整均摊这三档。
"""
found: Dict[int, Dict[str, Dict[str, int]]] = {}
exhaustive = True
if cols and sum(int(rest.get(j, 0) or 0) for j in JUDGMENTS) > 0:
# 先放「按容量均摊」的那份:同一个失分下它是最好解释的代表
for item in (_alloc_greedy_int(th, rest, cols),
alloc_flow(th, rest, cols, False),
alloc_flow(th, rest, cols, True)):
if item is not None and item[0] not in found:
found[item[0]] = item[1]
table, exhaustive = _enum_allocations(th, rest, cols)
for loss, alloc in table.items():
if loss not in found:
found[loss] = alloc
return (sorted(found.items(), key=lambda kv: kv[0]), exhaustive)
@dataclass
class AllocatedResult:
theory: Theory
judges: Dict[str, int] # 汇总判定数
break_spec: Dict[str, int] # 绝赞列的判定数(含档位)
allocated: Dict[str, Dict[str, Fraction]] # 列 -> 判定 -> 个数(均摊,可能带分数)
allocated: Dict[str, Dict[str, int]] # 列 -> 判定 -> 个数(取整均摊)
achievement: Fraction
dx: int
loss_break: int
bonus_break: int
loss_other: Fraction
loss_other: int
options: List[Tuple[int, Dict[str, Dict[str, int]]]] = field(default_factory=list)
exhaustive: bool = True
@property
def columns(self) -> List[str]:
return [c for c in ALLOC_COLUMNS if c in self.allocated]
def achievement_of(self, loss_other: int) -> Fraction:
"""把「其余音符」的总失分换算成达成率(绝赞列固定)。"""
w = self.theory.all_perfect_score
value = Fraction(100) - Fraction(100 * (self.loss_break + loss_other), w)
if self.theory.break_bonus_score:
value += Fraction(self.bonus_break, self.theory.break_bonus_score)
return value
@property
def achievement_min(self) -> Fraction:
"""可达的最低达成率(失分最多那个分配)。"""
return self.achievement_of(self.options[-1][0]) if self.options else self.achievement
@property
def achievement_max(self) -> Fraction:
"""可达的最高达成率(失分最少那个分配)。"""
return self.achievement_of(self.options[0][0]) if self.options else self.achievement
@property
def loss_range(self) -> Tuple[int, int]:
"""其余音符总失分的可达范围(都取整数)。"""
if not self.options:
return (self.loss_other, self.loss_other)
return (self.options[0][0], self.options[-1][0])
def solve_allocated(th: Theory, judges: Dict[str, int],
break_spec: Dict[str, int]) -> AllocatedResult:
@@ -691,23 +1023,28 @@ def solve_allocated(th: Theory, judges: Dict[str, int],
loss_break = sum(CLASS_OPTIONS["break"][k][0] * n for k, n in bspec.items())
bonus_break = sum(CLASS_OPTIONS["break"][k][1] * n for k, n in bspec.items())
allocated = _alloc_spread(th, rest, cols) if nb_total else {c: {} for c in cols}
loss_other = Fraction(0)
for c in cols:
for j, cnt in allocated[c].items():
loss_other += cnt * ALLOC_OPTIONS[c][j]
w = th.all_perfect_score
if w <= 0:
raise ValueError("谱面里没有计分音符")
achievement = Fraction(100) - (100 * (loss_break + loss_other)) / w
if th.break_bonus_score:
achievement += Fraction(bonus_break, th.break_bonus_score)
return AllocatedResult(
if nb_total:
greedy = _alloc_greedy_int(th, rest, cols)
if greedy is None:
raise ValueError("这些判定数在这个谱面上分不下去(列容量不够)")
loss_other, allocated = greedy
options, exhaustive = alloc_options(th, rest, cols)
if not any(loss == loss_other for loss, _ in options):
options = sorted(options + [(loss_other, allocated)], key=lambda kv: kv[0])
else:
loss_other, allocated = 0, {c: {} for c in cols}
options, exhaustive = [(0, {c: {} for c in cols})], True
result = AllocatedResult(
theory=th, judges=clean, break_spec=bspec, allocated=allocated,
achievement=achievement, dx=sum(DX_PER[j] * clean[j] for j in JUDGMENTS),
achievement=Fraction(0), dx=sum(DX_PER[j] * clean[j] for j in JUDGMENTS),
loss_break=loss_break, bonus_break=bonus_break, loss_other=loss_other,
options=options, exhaustive=exhaustive,
)
result.achievement = result.achievement_of(loss_other)
return result