AI
osmium_dust · · 个人记录
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>贴海报:你的轮廓线 DP</title>
<style>
:root {
--bg:#f4f5ef; --paper:#fffef9; --ink:#26362b;
--muted:#75816c; --line:#dce2d4; --green:#567e38;
}
* { box-sizing:border-box; }
body {
margin:0; color:var(--ink); background:var(--bg);
font-family:system-ui,-apple-system,"Microsoft YaHei",sans-serif;
}
button,input,select { font:inherit; }
button,select,input[type=number] {
padding:8px 11px; border:1px solid var(--line);
border-radius:8px; background:#fff; color:var(--ink);
}
button { cursor:pointer; transition:.15s; }
button:hover:not(:disabled) { border-color:#79965f; }
button:disabled { opacity:.5; cursor:not-allowed; }
button.primary { background:var(--green); color:white; border-color:var(--green); }
button.active { background:#e6efda; border-color:#7a995c; }
input[type=number] { width:62px; }
input[type=range] { accent-color:var(--green); }
code,.mono { font-family:Consolas,ui-monospace,monospace; }
.app { max-width:1280px; margin:auto; padding:28px 20px 40px; }
.kicker { color:var(--green); font-size:11px; font-weight:800; letter-spacing:.14em; }
h1 { margin:8px 0 10px; font-size:30px; }
h2 { margin:0; font-size:16px; }
p { line-height:1.8; }
.subtitle { margin:0 0 22px; color:var(--muted); font-size:14px; }
.panel {
background:var(--paper); border:1px solid var(--line);
border-radius:15px; padding:17px;
box-shadow:0 8px 25px #273b2505;
}
.toolbar { margin-bottom:16px; }
.row { display:flex; align-items:center; flex-wrap:wrap; gap:8px; }
.toolbar .row + .row {
margin-top:12px; padding-top:12px; border-top:1px solid #e9eddf;
}
.small { color:var(--muted); font-size:12px; line-height:1.8; }
.spacer { flex:1; }
.layout { display:grid; grid-template-columns:1fr 1.05fr; gap:16px; align-items:start; }
.stack { display:grid; gap:15px; }
.head { display:flex; justify-content:space-between; align-items:center; gap:10px; margin-bottom:13px; }
.tabs { display:flex; flex-wrap:wrap; gap:6px; margin-bottom:14px; }
.tabs button { font-size:12px; }
.board-wrap { position:relative; border:1px solid #bbc7b0; background:white; }
.board {
display:grid;
grid-template-columns:repeat(var(--cols),minmax(0,1fr));
}
.cell {
position:relative; aspect-ratio:1; display:flex;
justify-content:center; align-items:center;
border-right:1px solid #d9dfd2; border-bottom:1px solid #d9dfd2;
font:32px Georgia,"Times New Roman",serif;
background:white; color:#14240b; cursor:pointer; user-select:none;
}
.cell.past { background:#f3f5ee; }
.cell.expired { background:#e9ede3; }
.cell.window { background:#94b56b; }
.cell.occupied { background:#5c8739; }
.cell.part1 { background:#98511d; color:#160c04; }
.cell.part2 { background:#f28d3b; }
.cell.part3 { background:#c5641b; }
.cell.current { background:#e7def6; color:#594087; font-style:italic; font-weight:bold; }
.cell.blocked {
background:repeating-linear-gradient(
135deg,#d9dfd4 0 6px,#b8c3b1 6px 9px
) !important;
color:#5b6754; font-size:22px;
}
.badge {
position:absolute; right:3px; top:3px; padding:1px 3px;
background:#ffffffb5; color:#345125; border-radius:3px;
font:10px Consolas,monospace;
}
.outline { position:absolute; inset:3px; border:2px dashed #008e9b; pointer-events:none; }
.frontier { position:absolute; inset:0; width:100%; height:100%; pointer-events:none; }
.frontier path {
stroke:#20281d; stroke-width:2.5; fill:none;
vector-effect:non-scaling-stroke;
}
.legend { display:flex; flex-wrap:wrap; gap:12px; margin:12px 0; }
.legend span { display:flex; align-items:center; gap:5px; font-size:11px; color:var(--muted); }
.dot { display:inline-block; width:10px; height:10px; border-radius:2px; }
.playback { margin-top:15px; padding-top:15px; border-top:1px solid var(--line); }
.playback .row { justify-content:center; }
.progress { display:flex; align-items:center; gap:9px; margin-top:13px; }
#progress { flex:1; min-width:50px; }
.stats { display:grid; grid-template-columns:repeat(3,1fr); gap:8px; margin-bottom:13px; }
.stat { padding:11px; background:#eef3e5; border-radius:9px; }
.stat small { font-size:11px; color:var(--muted); display:block; }
.stat strong { font-size:24px; display:block; margin-top:4px; }
#states { width:100%; margin:9px 0; font-size:12px; }
.gate { padding:10px 12px; border-radius:9px; background:#edf3e4; margin:12px 0; font-size:12px; line-height:1.8; }
.gate.fail { color:#9c4a2e; background:#faeee6; }
.table-wrap { overflow-x:auto; margin-top:10px; }
table { width:100%; border-collapse:separate; border-spacing:3px; font:12px Consolas,monospace; }
th,td { text-align:center; min-width:23px; padding:6px 2px; border-radius:3px; }
th { color:#829076; font-size:10px; }
th:first-child,td:first-child { text-align:left; min-width:112px; padding-left:3px; white-space:nowrap; }
td { background:#f0f2eb; color:#a5af9d; }
td.label { color:var(--ink); background:none; }
td.one { background:#d7e7c5; color:#2d4c1c; font-weight:bold; }
tr.mask1 td.one { background:#ebd5c3; color:#753b13; }
tr.mask2 td.one { background:#ffe0bd; color:#9c5016; }
tr.both td.one { background:#e9b88e; color:#76380d; }
tr.next td.one { background:#e3d9f3; color:#674791; }
th.virtual { background:#e5e8e0; }
.formula {
padding:11px; margin-top:12px; border-radius:9px;
background:#283d2c; color:#edf4e4; font-size:12px;
overflow-x:auto; white-space:nowrap;
}
.branches { display:grid; gap:8px; }
.branch { text-align:left; padding:12px; }
.branch.chosen { background:#ecf7f3; border-color:#2b9c91; }
.branch b { display:block; font-size:13px; }
.branch small { display:block; font-size:11px; line-height:1.8; margin-top:5px; }
.note { font-size:12px; line-height:1.85; color:var(--muted); margin-top:11px; }
details { margin-top:16px; }
summary { cursor:pointer; font-size:14px; font-weight:700; }
pre { overflow:auto; padding:14px; background:#f0f3e9; border-radius:9px; font-size:12px; line-height:1.8; }
@media(max-width:900px) {
.layout { grid-template-columns:1fr; }
.app { padding:20px 12px; }
h1 { font-size:26px; }
.cell { font-size:clamp(20px,6vw,36px); }
}
</style>
</head>
<body>
<div class="app">
<div class="kicker">POSTER PACKING / YOUR PROFILE DP</div>
<h1>贴海报 · 公共掩码剪枝</h1>
<p class="subtitle">
含障碍网格中的最多张数:第一行预装入状态,逐格右移,先检查 both,再尝试两种朝向。
</p>
<section class="panel toolbar">
<div class="row">
<span class="small">行</span>
<input id="rows" type="number" min="1" max="8" value="7">
<span class="small">列</span>
<input id="cols" type="number" min="1" max="7" value="7">
<button id="apply" class="primary">新建墙面</button>
<button id="clear">清除障碍</button>
<button id="random">随机障碍</button>
<span class="spacer"></span>
<span class="small">点击格子切换障碍 · 1≤行≤8,1≤列≤7</span>
</div>
<div class="row">
<span class="small">原图复现</span>
<button data-preset="1">图①:1 / 2 / 3</button>
<button data-preset="2">图②:窗口位置一</button>
<button data-preset="3">图③:窗口位置二</button>
<span class="spacer"></span>
<span class="small">目标固定:不重叠,允许留空,最多张数</span>
</div>
</section>
<main class="layout">
<section class="panel">
<div class="head">
<h2>墙面与当前窗口</h2>
<span id="position" class="small mono"></span>
</div>
<div class="tabs">
<button data-view="window">窗口编号</button>
<button data-view="masks">图①的掩码分区</button>
<button data-view="path">所选状态的最优代表路径</button>
</div>
<div class="board-wrap">
<div id="board" class="board"></div>
<svg id="frontier" class="frontier" aria-hidden="true">
<path id="frontierPath"></path>
</svg>
</div>
<div class="legend">
<span><i class="dot" style="background:#94b56b"></i>窗口 / 位为0</span>
<span><i class="dot" style="background:#5c8739"></i>窗口 / 位为1</span>
<span><i class="dot" style="background:#e7def6"></i>当前 x</span>
<span><i class="dot" style="background:#b8c3b1"></i>障碍</span>
<span><i class="dot" style="border:2px dashed #008e9b"></i>预览放法</span>
</div>
<div id="boardNote" class="small"></div>
<div class="playback">
<div class="row">
<button id="reset">初始化</button>
<button id="prev">← 上一步</button>
<button id="play" class="primary">▶ 播放</button>
<button id="next">下一步 →</button>
<button id="finish">到终点</button>
</div>
<div class="progress">
<span id="stepText" class="small mono"></span>
<input id="progress" type="range" min="0" max="42" value="0">
<span class="small">速度</span>
<input id="speed" type="range" min="1" max="6" value="2" style="width:65px">
</div>
</div>
</section>
<div class="stack">
<section class="panel">
<div class="head">
<h2>进入本格时的状态</h2>
<span id="widthText" class="small mono"></span>
</div>
<div class="stats">
<div class="stat">
<small>已执行格子转移</small>
<strong id="stepStat"></strong>
</div>
<div class="stat">
<small>可达状态数</small>
<strong id="stateStat"></strong>
</div>
<div class="stat">
<small id="bestLabel">当前前缀最大值</small>
<strong id="bestStat"></strong>
</div>
</div>
<div id="lastStats" class="small"></div>
<div class="small" style="margin-top:10px">
选择一个 old 状态观察;下面最多列出值最大的 40 个状态:
</div>
<select id="states"></select>
<div id="selectedInfo" class="small mono"></div>
<div id="gate" class="gate"></div>
<div class="small">
以下从左到右是 bit 0 → bit 2m,不是通常二进制字符串的书写方向。
灰色列头表示虚拟格。
</div>
<div class="table-wrap">
<table id="bitTable"></table>
</div>
<div id="windowRange" class="small"></div>
<div class="formula mono">
S' = ((S | P) >> 1) | (b << (2*m))
</div>
<div class="note">
不贴时 P=0,b=当前格是否为障碍;贴海报时 P=对应五格掩码,b=1。
S′ 这一行的位编号属于移位后的新窗口。
</div>
</section>
<section class="panel">
<div class="head">
<h2>严格对应代码的分支</h2>
<span class="small">点击合法分支预览</span>
</div>
<div id="branches" class="branches"></div>
<div class="note">
“下一步”会计算所有可达状态的全部合法转移,而非只执行选中分支。
选中分支仅用于追踪目标状态;状态合并后,最优前驱可能来自另一条路径。
</div>
</section>
</div>
</main>
<details class="panel" open>
<summary>初始化、边界与核心循环</summary>
<p id="initText" class="small"></p>
<pre><code>// 第一行只装入障碍,前面的虚拟格设为 1
dp[((1 << (m+1)) - 1) | (mp[1] << (m+1))] = 0;
// 对 i=2..n, j=1..m,交换滚动表后:
if (j == 1 || now) {
relax((S >> 1) | (now << (2*m)), value);
} else {
relax(S >> 1, value); // 不贴
if ((S & both) == 0) { // 公共部分先判冲突
if (j != 2 && (S & mask2) == 0)
relax(((S | mask2) >> 1) | (1 << (2*m)), value+1);
if ((S & mask1) == 0)
relax(((S | mask1) >> 1) | (1 << (2*m)), value+1);
}
}
// relax:相同状态只保留最大 value
// 最终答案:max(dp[S])</code></pre>
<p class="small">
第一列不可能作为这两种矩形的右下角;第二列不能横贴。
第二行竖贴会碰到初始化的虚拟 1,因此无需额外写 i≥3。
原算法只需两张滚动表;网页为了回退额外保存每一步的状态快照。
</p>
</details>
</div>
<script>
"use strict";
const $ = id => document.getElementById(id);
const colors = [
"#cfb9e5", "#bdd99d", "#a9d7dc", "#e8c58e",
"#e9b2a8", "#bdcdef", "#d9d893", "#b4dbc5"
];
let n = 7, m = 7, N = 49, W = 15, total = 42;
let mask1 = 0, mask2 = 0, both = 0, initial = 0;
let blocked = [], mp = [], frames = [];
let step = 0, picked = null, choice = "skip";
let view = "window", timer = null;
const hex = s => "0x" + s.toString(16).toUpperCase();
function bitList(s) {
const result = [];
for (let i = 0; i < W; i++) {
if ((s >>> i) & 1) result.push(i);
}
return "{" + result.join(",") + "}";
}
function stop() {
if (timer !== null) clearInterval(timer);
timer = null;
$("play").textContent = "▶ 播放";
}
// frames[t] 表示执行了 t 个格子转移后的完整 DP。
// 第一行在初始化阶段读入,所以当前格扫描下标为 m+t。
function currentPosition(t = step) {
return m + t;
}
// type=1:mask1,2列×3行;type=2:mask2,3列×2行。
function rectangle(pos, type) {
const r = Math.floor(pos / m), c = pos % m;
const h = type === 1 ? 3 : 2;
const w = type === 1 ? 2 : 3;
const cells = [];
for (let rr = r - h + 1; rr <= r; rr++) {
for (let cc = c - w + 1; cc <= c; cc++) {
if (rr >= 0 && rr < n && cc >= 0 && cc < m) {
cells.push(rr * m + cc);
}
}
}
return cells;
}
function buildLayer(t) {
const source = frames[t].dp;
const target = new Map();
const pos = currentPosition(t);
const r = Math.floor(pos / m), c = pos % m;
const now = (mp[r] >>> c) & 1;
const stats = {
valid: 0, bothCuts: 0, fullChecks: 0, merges: 0
};
// tail 只记录一条取得该最优值的代表路径。
function relax(ns, value, parent, type) {
stats.valid++;
const old = target.get(ns);
if (!old || value > old.v) {
let tail = parent.tail;
if (type !== 0) {
tail = {
prev: tail,
pos,
type,
id: value
};
}
target.set(ns, { v: value, tail });
}
}
for (const [s, rec] of source) {
// 第一列、障碍格、普通空格的不贴分支都统一在此移位。
relax((s >>> 1) | (now << (2 * m)), rec.v, rec, 0);
// 原代码:j=1 只移位;now=1 只移位。
if (c === 0 || now) continue;
// 原代码中的公共部分剪枝。
if ((s & both) !== 0) {
stats.bothCuts++;
continue;
}
// 原代码先试 mask2,且要求 j != 2。
if (c !== 1) {
stats.fullChecks++;
if ((s & mask2) === 0) {
relax(
((s | mask2) >>> 1) | (1 << (2 * m)),
rec.v + 1, rec, 2
);
}
}
stats.fullChecks++;
if ((s & mask1) === 0) {
relax(
((s | mask1) >>> 1) | (1 << (2 * m)),
rec.v + 1, rec, 1
);
}
}
stats.merges = stats.valid - target.size;
frames.push({ dp: target, stats });
}
function ensure(t) {
while (frames.length <= t) buildLayer(frames.length - 1);
}
function resetModel(nn, mm, obstacles = null, at = 0,
newView = view, preferred = null) {
stop();
n = nn;
m = mm;
N = n * m;
W = 2 * m + 1;
total = (n - 1) * m;
view = newView;
blocked = Array.from(
{ length: N }, (_, id) => !!(obstacles && obstacles[id])
);
mp = Array(n).fill(0);
blocked.forEach((value, id) => {
if (value) mp[Math.floor(id / m)] |= 1 << (id % m);
});
mask1 = 3 | (3 << m) | (1 << (2 * m));
mask2 = (7 << (m - 1)) | (3 << (2 * m - 1));
both = mask1 & mask2;
// 与用户代码完全相同的初始化。
initial = ((1 << (m + 1)) - 1) | (mp[0] << (m + 1));
frames = [{
dp: new Map([[initial, { v: 0, tail: null }]]),
stats: { valid: 0, bothCuts: 0, fullChecks: 0, merges: 0 }
}];
step = Math.max(0, Math.min(total, at));
ensure(step);
picked = preferred;
choice = "skip";
$("rows").value = n;
$("cols").value = m;
render();
}
function rankStates(dp) {
return [...dp.entries()].sort(
(a, b) => b[1].v - a[1].v || a[0] - b[0]
);
}
// 这里只解释某一个源状态的分支。
// 真正计算下一层使用 buildLayer,始终遍历全部状态。
function branchesFor(s) {
if (step === total) return [];
const pos = currentPosition();
const r = Math.floor(pos / m), c = pos % m;
const now = (mp[r] >>> c) & 1;
const branches = [
{
id: "skip", type: 0,
name: now ? "只移位 · 当前格是障碍" :
c === 0 ? "只移位 · 当前是第一列" : "不贴海报",
pm: 0, b: now, add: 0, reason: ""
},
{
id: "horizontal", type: 2,
name: "mask2 · 横贴 3列 × 2行",
pm: mask2, b: 1, add: 1, reason: ""
},
{
id: "vertical", type: 1,
name: "mask1 · 竖贴 2列 × 3行",
pm: mask1, b: 1, add: 1, reason: ""
}
];
for (const q of branches) {
if (q.type !== 0) {
if (c === 0) {
q.reason = "j=1:代码只做移位,不尝试海报。";
} else if (now) {
q.reason = "now=1:当前格为障碍,代码只做移位。";
} else if ((s & both) !== 0) {
q.reason = "S & both 非零:公共部分已冲突,不再检查该方向。";
} else if (q.type === 2 && c === 1) {
q.reason = "j=2:不满足 j!=2,横贴会跨过左边界。";
} else if ((s & q.pm) !== 0) {
q.reason = "完整掩码冲突,冲突位 " + bitList(s & q.pm);
}
}
q.ns = ((s | q.pm) >>> 1) | (q.b << (2 * m));
}
return branches;
}
function drawBoard(rec, q) {
const pos = currentPosition();
const start = pos - W;
const board = $("board");
board.style.setProperty("--cols", m);
board.innerHTML = "";
// 当前状态的一条最优代表摆法。
const owner = Array(N).fill(0);
for (let node = rec?.tail; node; node = node.prev) {
for (const id of rectangle(node.pos, node.type)) {
owner[id] = node.id;
}
}
const proposed = new Set();
if (q && !q.reason && q.type !== 0) {
for (const id of rectangle(pos, q.type)) proposed.add(id);
}
for (let id = 0; id < N; id++) {
const cell = document.createElement("div");
cell.className = "cell";
cell.dataset.id = id;
const wi = id - start;
const inWindow = id < pos && wi >= 0 && wi < W;
const value = inWindow ? (picked >>> wi) & 1 : 0;
if (id < pos) cell.classList.add("past");
if (id < start) cell.classList.add("expired");
let text = "", badge = "";
if (view === "window" && inWindow) {
cell.classList.add("window");
if (value) cell.classList.add("occupied");
text = String(wi);
badge = `<span class="badge">${value}</span>`;
}
if (view === "masks" && inWindow) {
const part =
((mask1 >>> wi) & 1) + 2 * ((mask2 >>> wi) & 1);
if (part) {
cell.classList.add("part" + part);
text = String(part);
}
}
if (view === "path" && owner[id]) {
cell.style.background = colors[(owner[id] - 1) % colors.length];
text = String(owner[id]);
}
if (step < total && id === pos) {
cell.classList.add("current");
text = "x";
}
if (blocked[id]) {
cell.classList.add("blocked");
text = "#";
}
cell.innerHTML =
`<span>${text}</span>${badge}` +
(proposed.has(id) ? '<span class="outline"></span>' : "");
cell.title =
`第 ${Math.floor(id / m) + 1} 行,第 ${id % m + 1} 列` +
`;扫描下标 ${id}` +
(inWindow ? `;旧状态 bit ${wi} = ${value}` : "") +
(owner[id] ? `;代表路径的第 ${owner[id]} 张海报` : "") +
"\n点击切换障碍";
board.appendChild(cell);
}
$("frontier").setAttribute("viewBox", `0 0 ${m * 100} ${n * 100}`);
let d;
if (step === total) {
d = `M 0 ${n * 100} H ${m * 100}`;
} else {
const r = Math.floor(pos / m), c = pos % m;
d = c === 0
? `M 0 ${r * 100} H ${m * 100}`
: `M 0 ${(r + 1) * 100} H ${c * 100}
V ${r * 100} H ${m * 100}`;
}
$("frontierPath").setAttribute("d", d);
const notes = {
window:
"大数字是窗口位编号,角标是 S 的对应位。黑线前已扫描,x 尚未进入状态。",
masks:
"1=仅 mask1,2=仅 mask2,3=both。显示的是掩码位置;能否贴还需通过边界和占用检查。",
path:
"相同数字属于同一张海报。这只是所选状态保存的一条最优路径,不是 DP 的全部摆法。"
};
$("boardNote").textContent = notes[view];
}
function drawBits(q) {
const pos = currentPosition();
const start = pos - W;
let html = "<thead><tr><th>位编号</th>";
for (let i = 0; i < W; i++) {
const id = start + i;
html += `<th class="${id < 0 ? "virtual" : ""}"
title="${id < 0 ? "虚拟边界" : "扫描下标 " + id}">${i}</th>`;
}
html += "</tr></thead><tbody>";
const rows = [
["S", picked, ""],
["mask1", mask1, "mask1"],
["mask2", mask2, "mask2"],
["both", both, "both"],
["S & both", picked & both, "both"]
];
if (q && !q.reason) {
rows.push(["本分支 P", q.pm, ""]);
rows.push(["S′(移位后)", q.ns, "next"]);
}
for (const [name, mask, cls] of rows) {
html += `<tr class="${cls}"><td class="label">${name}</td>`;
for (let i = 0; i < W; i++) {
const value = (mask >>> i) & 1;
html += `<td class="${value ? "one" : ""}">${value}</td>`;
}
html += "</tr>";
}
$("bitTable").innerHTML = html + "</tbody>";
$("windowRange").textContent =
`旧窗口扫描下标:[${start}, ${pos - 1}];` +
`mask1=${mask1},mask2=${mask2},both=${both}。`;
}
function render() {
const frame = frames[step];
const ranked = rankStates(frame.dp);
if (picked === null || !frame.dp.has(picked)) {
picked = ranked[0][0];
}
const rec = frame.dp.get(picked);
const branches = branchesFor(picked);
let q = branches.find(item => item.id === choice);
if (!q || q.reason) {
choice = "skip";
q = branches[0] || null;
}
const pos = currentPosition();
const r = Math.floor(pos / m), c = pos % m;
const ended = step === total;
$("position").textContent = ended
? "扫描结束"
: `i=${r + 1}, j=${c + 1}, x=${pos}`;
$("widthText").textContent = `W=2m+1=${W}`;
$("stepStat").textContent = step + "/" + total;
$("stateStat").textContent = frame.dp.size.toLocaleString();
$("bestLabel").textContent = ended ? "最终答案 res" : "当前前缀最大值";
$("bestStat").textContent = ranked[0][1].v;
const st = frame.stats;
$("lastStats").textContent =
step === 0
? "初始化完成:第一行障碍已装入,尚未执行格子转移。"
: `上一步:合法转移 ${st.valid} 条,合并 ${st.merges} 条;` +
`公共部分剪枝 ${st.bothCuts} 个源状态,完整掩码检查 ${st.fullChecks} 次。`;
const options = ranked.slice(0, 40);
if (!options.some(([s]) => s === picked)) options.push([picked, rec]);
$("states").innerHTML = "";
for (const [s, value] of options) {
const option = document.createElement("option");
option.value = s;
option.textContent = `S=${hex(s)} (${s}) · old[S]=${value.v}`;
option.selected = s === picked;
$("states").appendChild(option);
}
$("selectedInfo").textContent =
`所选 S=${hex(picked)};old[S]=${rec.v};` +
`代表路径已放 ${rec.v} 张。`;
const gate = $("gate");
gate.className = "gate";
if (ended) {
gate.textContent = "扫描结束:按你的代码遍历最终 dp,取最大值作为答案。";
} else if (c === 0) {
gate.textContent = "j=1:只移位并装入当前格障碍,不进入 both 判断。";
} else if ((mp[r] >>> c) & 1) {
gate.textContent = "now=1:只移位,最高位补 1,不进入 both 判断。";
} else if ((picked & both) !== 0) {
gate.classList.add("fail");
gate.textContent =
`S & both = ${picked & both},冲突位 ${bitList(picked & both)}。` +
"图①的公共部分已被占用,两种朝向一起跳过。";
} else {
gate.textContent =
"S & both = 0:公共部分通过,接着按代码顺序检查 mask2、mask1。";
}
drawBits(q);
$("branches").innerHTML = "";
if (ended) {
$("branches").innerHTML =
'<div class="small">没有后续转移。可查看代表路径,或回退观察。</div>';
}
for (const item of branches) {
const button = document.createElement("button");
button.className =
"branch" + (item.id === choice ? " chosen" : "");
button.disabled = !!item.reason;
button.innerHTML =
`<b>${item.name}</b>` +
`<small>${item.reason ||
`合法:S′=${hex(item.ns)} (${item.ns}),候选值=${rec.v + item.add}`}</small>` +
(!item.reason
? `<small class="mono">P=${bitList(item.pm)},b=${item.b}</small>`
: "");
button.onclick = () => {
choice = item.id;
render();
};
$("branches").appendChild(button);
}
$("initText").textContent =
`当前初始化:低 ${m + 1} 位为虚拟边界 1;` +
`第一行障碍 mp[1]=${mp[0]} 左移 ${m + 1} 位。` +
`初始 S₀=${initial} (${hex(initial)}),dp[S₀]=0。` +
`状态中的 1 不区分障碍、已贴海报和虚拟边界。`;
$("progress").max = total;
$("progress").value = step;
$("stepText").textContent = `${step}/${total}`;
$("prev").disabled = step === 0;
$("next").disabled = ended;
$("finish").disabled = ended;
$("play").disabled = ended;
$("play").textContent = timer === null ? "▶ 播放" : "Ⅱ 暂停";
document.querySelectorAll("[data-view]").forEach(button => {
button.classList.toggle("active", button.dataset.view === view);
});
drawBoard(rec, q);
}
function jump(t) {
stop();
step = Math.max(0, Math.min(total, t));
ensure(step);
picked = null;
choice = "skip";
render();
}
function advance(pause = false) {
if (pause) stop();
if (step >= total) {
stop();
return;
}
const branches = branchesFor(picked);
const q = branches.find(item => item.id === choice);
const wanted = q && !q.reason ? q.ns : null;
ensure(step + 1);
step++;
picked = wanted !== null && frames[step].dp.has(wanted)
? wanted : null;
choice = "skip";
if (step === total) stop();
render();
}
function start() {
if (step === total) return;
timer = setInterval(
() => advance(),
1000 / Number($("speed").value)
);
$("play").textContent = "Ⅱ 暂停";
}
$("apply").onclick = () => {
const nn = Math.max(
1, Math.min(8, Math.floor(Number($("rows").value) || 7))
);
const mm = Math.max(
1, Math.min(7, Math.floor(Number($("cols").value) || 7))
);
resetModel(nn, mm);
};
$("clear").onclick = () => resetModel(n, m, null, step);
$("random").onclick = () => {
const obstacles = Array.from(
{ length: N }, () => Math.random() < 0.12
);
resetModel(n, m, obstacles, step);
};
$("board").onclick = event => {
const cell = event.target.closest(".cell");
if (!cell) return;
const obstacles = blocked.slice();
const id = Number(cell.dataset.id);
obstacles[id] = !obstacles[id];
resetModel(n, m, obstacles, step);
};
$("states").onchange = event => {
picked = Number(event.target.value);
choice = "skip";
render();
};
$("reset").onclick = () => jump(0);
$("prev").onclick = () => jump(step - 1);
$("next").onclick = () => advance(true);
$("finish").onclick = () => jump(total);
$("progress").oninput = event => jump(Number(event.target.value));
$("play").onclick = () => {
if (timer === null) start();
else stop();
};
$("speed").oninput = () => {
if (timer !== null) {
stop();
start();
}
};
document.querySelectorAll("[data-view]").forEach(button => {
button.onclick = () => {
view = button.dataset.view;
render();
};
});
document.querySelectorAll("[data-preset]").forEach(button => {
button.onclick = () => {
const id = Number(button.dataset.preset);
// m=7:
// 图①②:x=(4,4),0-based 扫描下标24,执行17步。
// 图③:x=(4,6),0-based 扫描下标26,执行19步。
//
// 选择 S=0,让窗口几何与原图直接对应;
// 完整 DP 仍然保留并计算所有可达状态。
resetModel(
7, 7, null,
id === 3 ? 19 : 17,
id === 1 ? "masks" : "window",
0
);
};
});
// 默认复现图②。
resetModel(7, 7, null, 17, "window", 0);
</script>
</body>
</html>