"""ALE-Bench ahc026 (Stack of Boxes): exact Python port of the official tools/src/lib.rs (parse_output + compute_score_details). Score = max(1, 10000 - V); WA (illegal op / unfinished) -> Invalid.""" import re from run import Invalid MAX_CHARS = 200_000 _UINT = re.compile(r"\+?[0-9]+\Z") def _tokens(ans): s = ans.get("output") if not isinstance(s, str): raise Invalid("output must be a string") if len(s) > MAX_CHARS: raise Invalid(f"output longer than {MAX_CHARS} characters") if any(not (" " <= ch <= "~" or ch in "\t\n\r") for ch in s): raise Invalid("output may contain printable ASCII, spaces, tabs and newlines only") return s.split() def _read(toks, k, lb, ub): if k >= len(toks): raise Invalid("Unexpected EOF") tok = toks[k] if not _UINT.match(tok): raise Invalid(f"Parse error: {tok}") v = int(tok) if v < lb or v > ub: raise Invalid(f"Out of range: {v}") return v def parse_input(text): t = list(map(int, text.split())) n, m = t[0], t[1] h = n // m return n, m, [t[2 + i * h: 2 + (i + 1) * h] for i in range(m)] def check(inst, ans): toks = _tokens(ans) n, m, bs = parse_input(inst["input"]) ops, k = [], 0 while k < len(toks): ops.append((_read(toks, k, 1, n), _read(toks, k + 1, 0, m))) k += 2 if len(ops) > 5000: raise Invalid("Too many output") where = {} for i, st in enumerate(bs): for b in st: where[b] = i cost, t = 0, 0 for v, to in ops: if v not in where: raise Invalid(f"Box {v} has already been taken out.") i = where[v] j = bs[i].index(v) if to == 0: if j + 1 != len(bs[i]): raise Invalid(f"Box {v} is not at the top of the stack.") if v != t + 1: raise Invalid(f"Before carrying out box {v}, all boxes less than {v} must be carried out.") bs[i].pop() del where[v] t += 1 else: cost += len(bs[i]) - j + 1 to -= 1 if i != to: moved = bs[i][j:] bs[to].extend(moved) del bs[i][j:] for b in moved: where[b] = to if t < n: raise Invalid(f"Not finished ({t} / {n})") score = max(1, 10000 - cost) return float(score), {"energy": cost, "operations": len(ops)}