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:
1 parent
72dce56dd1
commit
d0763fa796
3 files changed
+482
-65
No files matched your search
@@ -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
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user