正文
增加 274 行删除 61 行
87 行未改动888990919293949596979899100101102103154 行未改动全部展开25825926026126226326426517 行未改动28328428528628728828929085 行未改动37637737837938038138238314 行未改动3983994004014024034044054064074083 行未改动41241341441541641741841910 行未改动4304314324334344354364378 行未改动4464474484494504514524534544554564574584594602 行未改动4634644654664674684694704714724734744754766 行未改动48348448548648748848949049149249349449549649711 行未改动5095105115125135145155165175 行未改动5235245255265275285295305313 行未改动5355365375385395405415425435445456 行未改动552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590114 行未改动全部展开70570670770870971071171271371471571671771871972072172272372472535 行未改动76176276376476576676776876977077177277377477577677777877978078178216 行未改动79980080180280380480580680780880981081181281381442 行未改动857858859860861862863864865866867868869870871872873874875127 行未改动全部展开1003100410051006100710081009101010119 行未改动1021102210231024102510261027102810296 行未改动1036103710381039104010411042104310445 行未改动105010511052105310541055105610571058105910601061106210631064106510665 行未改动10721073107410751076107710781079108016 行未改动10971098109911001101110211031104110511061107110811095 行未改动11151116111711181119112011211122112369 行未改动119311941195119611971198119912001201120212031204120512062 行未改动1209121012111212121312141215121616 行未改动123312341235123612371238123912401241187 行未改动全部展开1429143014311432143314341435143614376 行未改动14441445144614471448144914501451145271 行未改动15241525152615271528152915301531153220 行未改动155315541555155615571558155915601561156215631564156515661567156815691570157144 行未改动16161617161816191620162116221623162484 行未改动170917101711171217131714171517161717142 行未改动全部展开18601861186218631864186518661867186861 行未改动19301931193219331934193519361937193830 行未改动196919701971197219731974197519761977133 行未改动全部展开2111211221132114211521162117211821192120212121222123212499 行未改动222422252226222722282229223022312232118 行未改动全部展开235123522353235423552356235723582 行未改动87 行未改动.btn-row .btn{margin-top:0;}.hint{font-size:12px;color:var(--muted);line-height:1.6;margin:9px 0 0;}.code-area{width:100%;min-height:180px;padding:10px 12px;margin-top:8px;border:1px solid #cbd5e1;border-radius:9px;background:#0f172a;color:#e2e8f0;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12.5px;line-height:1.6;outline:none;resize:vertical;transition:.15s;}.code-area:focus{border-color:var(--primary);box-shadow:0 0 0 3px rgba(37,99,235,.15);}.code-status{font-size:12px;margin-top:8px;line-height:1.5;min-height:17px;color:var(--muted);}.code-status.err{color:#b91c1c;font-weight:600;}.code-status.ok{color:#15803d;font-weight:600;}154 行未改动全部展开<p class="code-status" id="codeStatus"></p></div></details><section class="card"><h2>参数</h2><label class="row"><span>顶点数 n</span><input type="number" id="numNodes" min="0" max="60" value="7" step="1">17 行未改动<label class="check"><input type="checkbox" id="chkPhysics" checked> 弹性碰撞箱(解压手感)</label><p class="hint">开启后顶点互相碰撞、拖拽带惯性;关闭后顶点静止且可自由重叠。</p></section><section class="card"><h2>编辑模式</h2><div class="seg" id="modeSeg"><button class="seg-btn active" data-mode="drag">拖动</button>85 行未改动const popupHeader= document.getElementById('popupHeader');const popupCapInput = document.getElementById('popupCapInput');const codeInput = document.getElementById('codeInput');const codeStatus = document.getElementById('codeStatus');let W = 900, H = 650;let nodes = [];14 行未改动let highlight = { nodeIds: new Set(), edgeIds: new Set() };let topoColorMap = new Map();let flowHighlight = new Map();/* 每条边的几何元数据:{offset, selfIdx, selfTotal} */let edgeMeta = new Map();const PHYS = {restitution: 0.78,damping: 0.925,wallBounce: 0.62,3 行未改动sleepSpeed: 0.075,iterations: 2};let physicsEnabled = chkPhysics.checked;let physicsOn = false;let lastFrame = 0;10 行未改动const s = v.toFixed(4).replace(/0+$/, '').replace(/\.$/, '');return s || '0';}function shuffle(arr) {for (let i = arr.length - 1; i > 0; i--) {const j = Math.floor(Math.random() * (i + 1));[arr[i], arr[j]] = [arr[j], arr[i]];8 行未改动y: (e.clientY - r.top ) * (H / (r.height || H))};}/* 边的有效容量 */function edgeCap(e) {if (!capEnabled) return 1;return (typeof e.cap === 'number' && Number.isFinite(e.cap)) ? e.cap : 1;}/* 是否为负权边 */function isNegEdge(e) {return directed && capEnabled && typeof e.cap === 'number' && e.cap < 0;}2 行未改动function clearFlow() { flowHighlight = new Map(); }function clearAllVisual() { clearHighlight(); clearTopo(); clearFlow(); closePopup(); }/* ============================================================* 边几何:元数据计算(偏移 / 自环索引)* ============================================================ */function computeEdgeMeta() {edgeMeta = new Map();/* 非自环:按无序节点对分组 */const groups = new Map();for (const e of edges) {if (e.a === e.b) continue;const key = Math.min(e.a, e.b) + '-' + Math.max(e.a, e.b);6 行未改动edgeMeta.set(group[0].id, { offset: 0 });continue;}if (!directed) {/* 无向图:均匀扇开 */const total = group.length;group.forEach((e, i) => {edgeMeta.set(e.id, { offset: (i - (total - 1) / 2) * 30 });});} else {/* 有向图:按方向分开 */const minId = Number(key.split('-')[0]);const forward = group.filter(e => e.a === minId);const backward = group.filter(e => e.a !== minId);const hasF = forward.length > 0;11 行未改动}}}/* 自环:按节点分组 */const selfGroups = new Map();for (const e of edges) {if (e.a !== e.b) continue;if (!selfGroups.has(e.a)) selfGroups.set(e.a, []);5 行未改动});}}/* 直线 / 弯曲边路径 */function edgePath(A, B, offset) {const dx = B.x - A.x, dy = B.y - A.y;const d = Math.hypot(dx, dy) || 1;const ux = dx / d, uy = dy / d;3 行未改动if (Math.abs(offset) < 1) {return `M ${A.x + ux * r1} ${A.y + uy * r1} L ${B.x - ux * r2} ${B.y - uy * r2}`;}const px = -uy, py = ux;const cx = (A.x + B.x) / 2 + px * offset;const cy = (A.y + B.y) / 2 + py * offset;const sdx = cx - A.x, sdy = cy - A.y, sd = Math.hypot(sdx, sdy) || 1;const sx = A.x + sdx / sd * r1, sy = A.y + sdy / sd * r1;6 行未改动function edgeMidpoint(A, B, offset) {if (Math.abs(offset) < 1) {return { x: (A.x + B.x) / 2, y: (A.y + B.y) / 2 };}const dx = B.x - A.x, dy = B.y - A.y;const d = Math.hypot(dx, dy) || 1;const px = -dy / d, py = dx / d;const cx = (A.x + B.x) / 2 + px * offset;const cy = (A.y + B.y) / 2 + py * offset;return {x: 0.25 * A.x + 0.5 * cx + 0.25 * B.x,y: 0.25 * A.y + 0.5 * cy + 0.25 * B.y};}/* 自环:路径 + 中点 */function selfLoopGeometry(node, idx, total) {const R = NODE_R;const count = Math.max(1, total);/* 多个自环均匀分布在节点周围 */const baseAngle = -Math.PI / 2 + (idx * 2 * Math.PI) / count;const spread = 0.62;const a1 = baseAngle - spread;const a2 = baseAngle + spread;const sx = node.x + R * Math.cos(a1);const sy = node.y + R * Math.sin(a1);const ex = node.x + R * Math.cos(a2);const ey = node.y + R * Math.sin(a2);/* 环的“顶点”位置(距离节点中心 2.4R) */const loopDist = R * 2.4;const lx = node.x + Math.cos(baseAngle) * loopDist;const ly = node.y + Math.sin(baseAngle) * loopDist;/* 二次贝塞尔控制点,使曲线经过 (lx, ly) */const ctrlX = 2 * lx - 0.5 * (sx + ex);const ctrlY = 2 * ly - 0.5 * (sy + ey);return {114 行未改动全部展开<marker id="arrowNeg" viewBox="0 0 10 10" refX="10" refY="5"markerWidth="5" markerHeight="5" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 Z" fill="#dc2626"/></marker><marker id="arrowFlow" viewBox="0 0 10 10" refX="10" refY="5"markerWidth="5" markerHeight="5" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 Z" fill="#60a5fa"/></marker></defs><rect data-blank="1" x="0" y="0" width="${W}" height="${H}" fill="url(#grid)"/>`;/* 边 */const edgeDraws = [];for (const e of edges) {const A = nmap.get(e.a), B = nmap.get(e.b);if (!A || !B) continue;const meta = edgeMeta.get(e.id) || { offset: 0, selfIdx: 0, selfTotal: 1 };let d, mid;if (e.a === e.b) {const g = selfLoopGeometry(A, meta.selfIdx || 0, meta.selfTotal || 1);35 行未改动html += `<path data-edge="${e.id}" d="${d}" fill="none" stroke="none"stroke-width="18" pointer-events="stroke" style="cursor:pointer"/>`;}/* 容量标签 */if (capEnabled) {for (const { e, mid } of edgeDraws) {const isNeg = isNegEdge(e);const txt = fmtNum((typeof e.cap === 'number') ? e.cap : 1);const bw = 12 + txt.length * 7.2;const bh = 18;/* 自环的标签放在环顶略偏外 */let lx = mid.x, ly = mid.y - 14;if (e.a !== e.b) {const meta = edgeMeta.get(e.id) || { offset: 0 };if (Math.abs(meta.offset || 0) < 1) {/* 直线边:朝垂直于边的方向偏移(朝上) */const A = nmap.get(e.a), B = nmap.get(e.b);const dx = B.x - A.x, dy = B.y - A.y;const dlen = Math.hypot(dx, dy) || 1;let px = -dy / dlen, py = dx / dlen;16 行未改动</g>`;}}/* 最大流箭头 + 流量数字 */if (flowHighlight.size > 0) {for (const [edgeId, info] of flowHighlight) {const e = edges.find(x => x.id === edgeId);if (!e) continue;const A = nmap.get(e.a), B = nmap.get(e.b);if (!A || !B) continue;if (e.a === e.b) continue; // 自环不参与最大流可视化const meta = edgeMeta.get(e.id) || { offset: 0 };const mid = edgeMidpoint(A, B, meta.offset || 0);42 行未改动}}}/* 连边预览 */if (mode === 'edge' && pending !== null && hoverPt) {const pn = nmap.get(pending);if (pn) {html += `<line x1="${pn.x}" y1="${pn.y}" x2="${hoverPt.x}" y2="${hoverPt.y}"stroke="#2563eb" stroke-width="2" stroke-dasharray="6 6"opacity="0.55" pointer-events="none"/>`;}}/* 顶点 */for (let i = 0; i < nodes.length; i++) {const nd = nodes[i];const isPend = pending === nd.id;const isHot = highlight.nodeIds.has(nd.id);127 行未改动全部展开return maxV > PHYS.sleepSpeed;}/* ============================================================* 图分析(支持自环与重边)* ============================================================ */function analyze() {const n = nodes.length, m = edges.length;const idx = new Map();9 行未改动const a = idx.get(e.a), b = idx.get(e.b);if (a === undefined || b === undefined) continue;if (a === b) {/* 自环:无向度数 +2;有向入度 +1、出度 +1 */adjU[a].push(a);adjU[a].push(a);adjOut[a].push(a);adjIn[a].push(a);6 行未改动}}const degU = adjU.map(a => a.length);/* 连通分量(自环不影响连通性) */const seen = new Array(n).fill(false);let comps = 0;for (let i = 0; i < n; i++) {if (seen[i]) continue;5 行未改动}}const weakConnected = (n === 0) || comps === 1;/* 无向意义下的环:注意自环本身也是环- 若不考虑自环:m_self = 0 时 m > n - comps 表示有环- 若存在自环,必然有环 */let selfLoopCount = 0;for (const e of edges) if (e.a === e.b) selfLoopCount++;const effectiveM = m - selfLoopCount; // 去掉自环的边数(自环不增加连通性)const cycleU = selfLoopCount > 0 || effectiveM > n - comps;/* 有向环:Kahn 算法,自环会让节点永远入度 > 0 */let cycleD = false;{const deg = indeg.slice();const q = [];5 行未改动}cycleD = cnt < n;}/* 强连通 */let stronglyConnected = true;if (n > 0) {const vis = new Array(n).fill(false);const order = [];16 行未改动}stronglyConnected = c === 1;}/* 是否为树:自环或重边都直接判定不是树 */let isTree = false;if (n > 0) {if (!directed) {/* 无向树:连通、无自环、无重边、m == n-1 */let hasMultiOrSelf = false;if (selfLoopCount > 0) hasMultiOrSelf = true;else {const pairSet = new Set();5 行未改动}}isTree = weakConnected && m === n - 1 && !hasMultiOrSelf;} else {/* 有向树:弱连通、恰一个入度 0 的点、所有点入度 <= 1、无自环 */const zeroIn = indeg.filter(d => d === 0).length;const allAtMost1 = indeg.every(d => d <= 1);isTree = weakConnected && zeroIn === 1 && allAtMost1 && selfLoopCount === 0;}69 行未改动else if (nodes.length === 1) selDst.value = String(nodes[0].id);else selDst.value = '';}function updateUI() {numNodesEl.value = nodes.length;if (!chkTree.checked) numEdgesEl.value = edges.length;const n = nodes.length;/* 上限按简单图算;实际允许重边/自环,所以这里只是随机生成的参考上限 */const maxE = directed ? n * (n - 1) : n * (n - 1) / 2;numEdgesEl.max = Math.max(0, maxE);let tagText = directed ? '有向图' : '无向图';2 行未改动tagEl.innerHTML = tagText;refreshSelectors();renderAnalysis();}function refresh() {render();16 行未改动nodes[i].y = cy + ry * Math.sin(ang);}}/* 整理 */function findTreeCentroid() {const adj = new Map();for (const nd of nodes) adj.set(nd.id, []);for (const e of edges) {187 行未改动全部展开const a = idx.get(e.a), b = idx.get(e.b);if (a === undefined || b === undefined) continue;adj[a].push(b);indeg[b]++;/* 自环:自己指向自己,入度已 +1,永远无法拓扑排序 */}let current = [];for (let i = 0; i < n; i++) if (indeg[i] === 0) current.push(i);6 行未改动processed += current.length;const next = [];for (const u of current) {for (const v of adj[u]) {if (v === u) continue; // 自环不减少入度if (--indeg[v] === 0) next.push(v);}}next.sort((x, y) => x - y);71 行未改动while (q.length) {const u = q.shift();inQueue[u] = false;for (const [v, w] of adj[u]) {/* 跳过无意义的大正数松弛 */if (dist[u] + w < dist[v]) {dist[v] = dist[u] + w;parent[v] = u;if (!inQueue[v]) {20 行未改动}return { dist: dist[T], path };}/* 最大流:Edmonds-Karp。自环与负容量边忽略。 */function maxFlow(sId, tId) {const n = nodes.length;const idx = new Map();nodes.forEach((nd, i) => idx.set(nd.id, i));const cap = Array.from({ length: n }, () => new Array(n).fill(0));for (const e of edges) {const a = idx.get(e.a), b = idx.get(e.b);if (a === undefined || b === undefined) continue;if (a === b) continue; // 自环对最大流无贡献const c = edgeCap(e);if (c <= 0) continue;if (directed) cap[a][b] += c;else { cap[a][b] += c; cap[b][a] += c; }44 行未改动}const flowMap = new Map();for (const e of edges) {if (e.a === e.b) continue; // 自环const a = idx.get(e.a), b = idx.get(e.b);if (a === undefined || b === undefined) continue;const netAB = origCap[a][b] - cap[a][b];if (Math.abs(netAB) < 1e-9) continue;84 行未改动for (let k = 0; k < r.path.length - 1; k++) {const u = nodes[r.path[k]].id;const v = nodes[r.path[k + 1]].id;if (u === v) continue;/* 有多条平行边时,选权重最小的那条高亮 */let best = null, bestW = Infinity;for (const e of edges) {if (e.a === e.b) continue;if ((e.a === u && e.b === v) || (e.a === v && e.b === u)) {142 行未改动全部展开refresh();}/* ============================================================* 随机生成(不添加自环与重边,保持整洁)* ============================================================ */function randomGenerate() {const n = clamp(parseInt(numNodesEl.value, 10) || 0, 0, MAX_NODES);numNodesEl.value = n;61 行未改动wake();}/* ============================================================* 代码模式:解析(允许自环和重边)* ============================================================ */function parseCode(text) {const lines = text.split('\n').map(l => l.trim())30 行未改动}if (u < 1 || u > n || v < 1 || v > n) {throw new Error(`第 ${lineNum} 行顶点编号超出范围 [1, ${n}]`);}/* 自环:允许,但计入统计 */let w = 1;if (parts.length >= 3) {w = parseFloat(parts[2]);133 行未改动全部展开} else if (mode === 'edge') {if (pending === null) {pending = id;} else if (pending === id) {/* 同一节点再次点击 → 添加自环 */edges.push({ id: edgeSeq++, a: id, b: id, cap: 1 });pending = null;clearAllVisual();} else {/* 不同节点 → 添加边(允许重边) */edges.push({ id: edgeSeq++, a: pending, b: id, cap: 1 });pending = null;clearAllVisual();}99 行未改动btn.classList.add('active');directed = btn.dataset.type === 'directed';if (!directed) {/* 切到无向图时,负权清零 */let fixed = false;for (const e of edges) {if (typeof e.cap === 'number' && e.cap < 0) {e.cap = 0; fixed = true;118 行未改动全部展开const r = stage.getBoundingClientRect();W = Math.max(240, Math.round(r.width));H = Math.max(240, Math.round(r.height));}randomGenerate();})();</script></body>2 行未改动87 行未改动888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149154 行未改动全部展开30430530630730830931031131231331431531631731831932032132232332432517 行未改动34334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139285 行未改动47847948048148248348448548648748814 行未改动5035045055065075085095105115125135145153 行未改动51952052152252352452552652752852953053153253310 行未改动5445455465475485495505515525535545555565578 行未改动5665675685695705715725735745755765775782 行未改动5815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576 行未改动66466566666766866967067167267367467567611 行未改动6886896906916926936946955 行未改动7017027037047057067077083 行未改动7127137147157167177187197207217226 行未改动729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761114 行未改动全部展开87687787887988088188288388488588688788888989035 行未改动92692792892993093193293393493593693793893994094194294394416 行未改动96196296396496596696796896997097197297397497542 行未改动10181019102010211022102310241025102610271028102910301031103210331034127 行未改动全部展开1162116311641165116611671168116911709 行未改动118011811182118311841185118611876 行未改动119411951196119711981199120012015 行未改动12071208120912101211121212131214121512161217121812195 行未改动1225122612271228122912301231123216 行未改动124912501251125212531254125512561257125812595 行未改动1265126612671268126912701271127269 行未改动13421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514262 行未改动14291430143114321433143414351436143716 行未改动14541455145614571458145914601461187 行未改动全部展开164916501651165216531654165516566 行未改动16631664166516661667166816691670167171 行未改动1743174417451746174717481749175020 行未改动17711772177317741775177617771778177917801781178217831784178517861787178844 行未改动18331834183518361837183818391840184184 行未改动19261927192819291930193119321933142 行未改动全部展开20762077207820792080208120822083208461 行未改动21462147214821492150215121522153215430 行未改动21852186218721882189219021912192133 行未改动全部展开23262327232823292330233123322333233423352336233799 行未改动24372438243924402441244224432444118 行未改动全部展开2563256425652566256725682569257025712 行未改动87 行未改动.btn-row .btn{margin-top:0;}.hint{font-size:12px;color:var(--muted);line-height:1.6;margin:9px 0 0;}/* ================= 滑块 ================= */.slider-row{margin-bottom:14px;}.slider-row:last-of-type{margin-bottom:0;}.slider-row label{display:flex;justify-content:space-between;align-items:center;font-size:12.5px;color:#334155;margin-bottom:6px;gap:8px;}.slider-row label .name{font-weight:500;}.slider-row label .val{font-family:ui-monospace,Menlo,monospace;font-size:12px;color:var(--primary);font-weight:700;background:#eff6ff;padding:1px 8px;border-radius:5px;min-width:52px;text-align:center;}.slider-row input[type=range]{width:100%;height:5px;border-radius:3px;background:#e2e8f0;outline:none;-webkit-appearance:none;appearance:none;cursor:pointer;padding:0;margin:0;}.slider-row input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:16px;height:16px;border-radius:50%;background:var(--primary);cursor:pointer;border:2px solid #fff;box-shadow:0 1px 4px rgba(37,99,235,.45);transition:transform .12s ease;}.slider-row input[type=range]::-webkit-slider-thumb:hover{transform:scale(1.15);}.slider-row input[type=range]::-webkit-slider-thumb:active{transform:scale(1.25);}.slider-row input[type=range]::-moz-range-thumb{width:14px;height:14px;border-radius:50%;background:var(--primary);cursor:pointer;border:2px solid #fff;box-shadow:0 1px 4px rgba(37,99,235,.45);}.slider-row input[type=range]::-moz-range-track{height:5px;border-radius:3px;background:#e2e8f0;}.slider-row .desc{font-size:11px;color:#94a3b8;margin-top:5px;line-height:1.4;}.code-area{width:100%;min-height:180px;padding:10px 12px;margin-top:8px;border:1px solid #cbd5e1;border-radius:9px;background:#0f172a;color:#e2e8f0;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12.5px;line-height:1.6;outline:none;resize:vertical;transition:.15s;}.code-area:focus{border-color:var(--primary);box-shadow:0 0 0 3px rgba(37,99,235,.15);}.code-area[readonly]{background:#0b1220;cursor:text;}.code-status{font-size:12px;margin-top:8px;line-height:1.5;min-height:17px;color:var(--muted);}.code-status.err{color:#b91c1c;font-weight:600;}.code-status.ok{color:#15803d;font-weight:600;}154 行未改动全部展开<p class="code-status" id="codeStatus"></p></div></details><details class="card" id="exportCard"><summary>📤 数据导出</summary><div><div style="font-size:12px;color:#64748b;line-height:1.7;background:#eef2f7;border-radius:8px;padding:8px 10px;">当前图的文本表示,可直接复制粘贴回代码模式,或保存到本地。<br><span style="color:#94a3b8">启用容量时导出 u v w,否则导出 u v。</span></div><textarea id="exportArea" class="code-area" readonly spellcheck="false"style="min-height:160px;background:#0b1220;"></textarea><button class="btn primary" id="btnExportCopy" style="margin-top:8px">📋 复制到剪贴板</button><p class="code-status" id="exportStatus"></p></div></details><section class="card"><h2>参数</h2><label class="row"><span>顶点数 n</span><input type="number" id="numNodes" min="0" max="60" value="7" step="1">17 行未改动<label class="check"><input type="checkbox" id="chkPhysics" checked> 弹性碰撞箱(解压手感)</label><p class="hint">开启后顶点互相碰撞、拖拽带惯性;关闭后顶点静止且可自由重叠。</p></section><section class="card" id="physTuningCard"><h2>物理调参</h2><div class="slider-row"><label><span class="name">速度阻尼(阻力)</span><span class="val" id="dampingVal">0.925</span></label><input type="range" id="dampingSlider" min="0.5" max="1" step="0.005" value="0.925"><div class="desc">每帧速度保留比例。越小阻力越大,顶点越快停下;越大越顺滑。</div></div><div class="slider-row"><label><span class="name">拖拽阻尼</span><span class="val" id="dragDragVal">0.88</span></label><input type="range" id="dragDragSlider" min="0.3" max="1" step="0.01" value="0.88"><div class="desc">拖动顶点时速度衰减。越小拖动越稳,越大松手飞得越远。</div></div><div class="slider-row"><label><span class="name">碰撞弹性</span><span class="val" id="restitutionVal">0.78</span></label><input type="range" id="restitutionSlider" min="0" max="1" step="0.02" value="0.78"><div class="desc">两顶点碰撞后能量保留比例。0 = 完全非弹性,1 = 完全弹性。</div></div><div class="slider-row"><label><span class="name">撞墙弹性</span><span class="val" id="wallBounceVal">0.62</span></label><input type="range" id="wallBounceSlider" min="0" max="1" step="0.02" value="0.62"><div class="desc">撞到画布边界时能量保留比例。</div></div><button class="btn" id="btnPhysReset" style="margin-top:10px">↻ 恢复默认</button></section><section class="card"><h2>编辑模式</h2><div class="seg" id="modeSeg"><button class="seg-btn active" data-mode="drag">拖动</button>85 行未改动const popupHeader= document.getElementById('popupHeader');const popupCapInput = document.getElementById('popupCapInput');const codeInput = document.getElementById('codeInput');const codeStatus = document.getElementById('codeStatus');const exportArea = document.getElementById('exportArea');const exportStatus = document.getElementById('exportStatus');const exportCard = document.getElementById('exportCard');let W = 900, H = 650;let nodes = [];14 行未改动let highlight = { nodeIds: new Set(), edgeIds: new Set() };let topoColorMap = new Map();let flowHighlight = new Map();let edgeMeta = new Map();/* ============================================================* 物理参数(可通过滑块调整)* ============================================================ */const PHYS = {restitution: 0.78,damping: 0.925,wallBounce: 0.62,3 行未改动sleepSpeed: 0.075,iterations: 2};const PHYS_DEFAULTS = {restitution: 0.78,damping: 0.925,wallBounce: 0.62,dragDrag: 0.88,};let physicsEnabled = chkPhysics.checked;let physicsOn = false;let lastFrame = 0;10 行未改动const s = v.toFixed(4).replace(/0+$/, '').replace(/\.$/, '');return s || '0';}function fullNumStr(v) {if (typeof v !== 'number' || !Number.isFinite(v)) return '1';if (Number.isInteger(v)) return String(v);return String(v);}function shuffle(arr) {for (let i = arr.length - 1; i > 0; i--) {const j = Math.floor(Math.random() * (i + 1));[arr[i], arr[j]] = [arr[j], arr[i]];8 行未改动y: (e.clientY - r.top ) * (H / (r.height || H))};}function edgeCap(e) {if (!capEnabled) return 1;return (typeof e.cap === 'number' && Number.isFinite(e.cap)) ? e.cap : 1;}function isNegEdge(e) {return directed && capEnabled && typeof e.cap === 'number' && e.cap < 0;}2 行未改动function clearFlow() { flowHighlight = new Map(); }function clearAllVisual() { clearHighlight(); clearTopo(); clearFlow(); closePopup(); }/* ============================================================* 物理调参滑块* ============================================================ */const dampingSlider = document.getElementById('dampingSlider');const dampingVal = document.getElementById('dampingVal');const dragDragSlider= document.getElementById('dragDragSlider');const dragDragVal = document.getElementById('dragDragVal');const restitutionSlider = document.getElementById('restitutionSlider');const restitutionVal = document.getElementById('restitutionVal');const wallBounceSlider = document.getElementById('wallBounceSlider');const wallBounceVal = document.getElementById('wallBounceVal');function syncPhysSliders() {dampingSlider.value = PHYS.damping;dampingVal.textContent = PHYS.damping.toFixed(3);dragDragSlider.value = PHYS.dragDrag;dragDragVal.textContent = PHYS.dragDrag.toFixed(2);restitutionSlider.value = PHYS.restitution;restitutionVal.textContent = PHYS.restitution.toFixed(2);wallBounceSlider.value = PHYS.wallBounce;wallBounceVal.textContent = PHYS.wallBounce.toFixed(2);}dampingSlider.addEventListener('input', () => {PHYS.damping = parseFloat(dampingSlider.value);dampingVal.textContent = PHYS.damping.toFixed(3);wake();});dragDragSlider.addEventListener('input', () => {PHYS.dragDrag = parseFloat(dragDragSlider.value);dragDragVal.textContent = PHYS.dragDrag.toFixed(2);wake();});restitutionSlider.addEventListener('input', () => {PHYS.restitution = parseFloat(restitutionSlider.value);restitutionVal.textContent = PHYS.restitution.toFixed(2);wake();});wallBounceSlider.addEventListener('input', () => {PHYS.wallBounce = parseFloat(wallBounceSlider.value);wallBounceVal.textContent = PHYS.wallBounce.toFixed(2);wake();});document.getElementById('btnPhysReset').addEventListener('click', () => {Object.assign(PHYS, PHYS_DEFAULTS);syncPhysSliders();wake();});/* ============================================================* 边几何* ============================================================ */function canonicalPerp(A, B) {const dx = B.x - A.x, dy = B.y - A.y;const d = Math.hypot(dx, dy) || 1;const ux = dx / d, uy = dy / d;const sign = A.id < B.id ? 1 : -1;return { x: -uy * sign, y: ux * sign };}function computeEdgeMeta() {edgeMeta = new Map();const groups = new Map();for (const e of edges) {if (e.a === e.b) continue;const key = Math.min(e.a, e.b) + '-' + Math.max(e.a, e.b);6 行未改动edgeMeta.set(group[0].id, { offset: 0 });continue;}if (!directed) {const total = group.length;group.forEach((e, i) => {edgeMeta.set(e.id, { offset: (i - (total - 1) / 2) * 30 });});} else {const minId = Number(key.split('-')[0]);const forward = group.filter(e => e.a === minId);const backward = group.filter(e => e.a !== minId);const hasF = forward.length > 0;11 行未改动}}}const selfGroups = new Map();for (const e of edges) {if (e.a !== e.b) continue;if (!selfGroups.has(e.a)) selfGroups.set(e.a, []);5 行未改动});}}function edgePath(A, B, offset) {const dx = B.x - A.x, dy = B.y - A.y;const d = Math.hypot(dx, dy) || 1;const ux = dx / d, uy = dy / d;3 行未改动if (Math.abs(offset) < 1) {return `M ${A.x + ux * r1} ${A.y + uy * r1} L ${B.x - ux * r2} ${B.y - uy * r2}`;}const perp = canonicalPerp(A, B);const cx = (A.x + B.x) / 2 + perp.x * offset;const cy = (A.y + B.y) / 2 + perp.y * offset;const sdx = cx - A.x, sdy = cy - A.y, sd = Math.hypot(sdx, sdy) || 1;const sx = A.x + sdx / sd * r1, sy = A.y + sdy / sd * r1;6 行未改动function edgeMidpoint(A, B, offset) {if (Math.abs(offset) < 1) {return { x: (A.x + B.x) / 2, y: (A.y + B.y) / 2 };}const perp = canonicalPerp(A, B);const cx = (A.x + B.x) / 2 + perp.x * offset;const cy = (A.y + B.y) / 2 + perp.y * offset;return {x: 0.25 * A.x + 0.5 * cx + 0.25 * B.x,y: 0.25 * A.y + 0.5 * cy + 0.25 * B.y};}function selfLoopGeometry(node, idx, total) {const R = NODE_R;const count = Math.max(1, total);const baseAngle = -Math.PI / 2 + (idx * 2 * Math.PI) / count;const spread = 0.62;const a1 = baseAngle - spread;const a2 = baseAngle + spread;const sx = node.x + R * Math.cos(a1);const sy = node.y + R * Math.sin(a1);const ex = node.x + R * Math.cos(a2);const ey = node.y + R * Math.sin(a2);const loopDist = R * 2.4;const lx = node.x + Math.cos(baseAngle) * loopDist;const ly = node.y + Math.sin(baseAngle) * loopDist;const ctrlX = 2 * lx - 0.5 * (sx + ex);const ctrlY = 2 * ly - 0.5 * (sy + ey);return {114 行未改动全部展开<marker id="arrowNeg" viewBox="0 0 10 10" refX="10" refY="5"markerWidth="5" markerHeight="5" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 Z" fill="#dc2626"/></marker></defs><rect data-blank="1" x="0" y="0" width="${W}" height="${H}" fill="url(#grid)"/>`;const edgeDraws = [];for (const e of edges) {const A = nmap.get(e.a), B = nmap.get(e.b);if (!A || !B) continue;const meta = edgeMeta.get(e.id) || { offset: 0, selfIdx: 0, selfTotal: 1 };let d, mid;if (e.a === e.b) {const g = selfLoopGeometry(A, meta.selfIdx || 0, meta.selfTotal || 1);35 行未改动html += `<path data-edge="${e.id}" d="${d}" fill="none" stroke="none"stroke-width="18" pointer-events="stroke" style="cursor:pointer"/>`;}if (capEnabled) {for (const { e, mid } of edgeDraws) {const isNeg = isNegEdge(e);const txt = fmtNum((typeof e.cap === 'number') ? e.cap : 1);const bw = 12 + txt.length * 7.2;const bh = 18;let lx = mid.x, ly = mid.y - 14;if (e.a !== e.b) {const meta = edgeMeta.get(e.id) || { offset: 0 };if (Math.abs(meta.offset || 0) < 1) {const A = nmap.get(e.a), B = nmap.get(e.b);const dx = B.x - A.x, dy = B.y - A.y;const dlen = Math.hypot(dx, dy) || 1;let px = -dy / dlen, py = dx / dlen;16 行未改动</g>`;}}if (flowHighlight.size > 0) {for (const [edgeId, info] of flowHighlight) {const e = edges.find(x => x.id === edgeId);if (!e) continue;const A = nmap.get(e.a), B = nmap.get(e.b);if (!A || !B) continue;if (e.a === e.b) continue;const meta = edgeMeta.get(e.id) || { offset: 0 };const mid = edgeMidpoint(A, B, meta.offset || 0);42 行未改动}}}if (mode === 'edge' && pending !== null && hoverPt) {const pn = nmap.get(pending);if (pn) {html += `<line x1="${pn.x}" y1="${pn.y}" x2="${hoverPt.x}" y2="${hoverPt.y}"stroke="#2563eb" stroke-width="2" stroke-dasharray="6 6"opacity="0.55" pointer-events="none"/>`;}}for (let i = 0; i < nodes.length; i++) {const nd = nodes[i];const isPend = pending === nd.id;const isHot = highlight.nodeIds.has(nd.id);127 行未改动全部展开return maxV > PHYS.sleepSpeed;}/* ============================================================* 图分析* ============================================================ */function analyze() {const n = nodes.length, m = edges.length;const idx = new Map();9 行未改动const a = idx.get(e.a), b = idx.get(e.b);if (a === undefined || b === undefined) continue;if (a === b) {adjU[a].push(a);adjU[a].push(a);adjOut[a].push(a);adjIn[a].push(a);6 行未改动}}const degU = adjU.map(a => a.length);const seen = new Array(n).fill(false);let comps = 0;for (let i = 0; i < n; i++) {if (seen[i]) continue;5 行未改动}}const weakConnected = (n === 0) || comps === 1;let selfLoopCount = 0;for (const e of edges) if (e.a === e.b) selfLoopCount++;const effectiveM = m - selfLoopCount;const cycleU = selfLoopCount > 0 || effectiveM > n - comps;let cycleD = false;{const deg = indeg.slice();const q = [];5 行未改动}cycleD = cnt < n;}let stronglyConnected = true;if (n > 0) {const vis = new Array(n).fill(false);const order = [];16 行未改动}stronglyConnected = c === 1;}let isTree = false;if (n > 0) {if (!directed) {let hasMultiOrSelf = false;if (selfLoopCount > 0) hasMultiOrSelf = true;else {const pairSet = new Set();5 行未改动}}isTree = weakConnected && m === n - 1 && !hasMultiOrSelf;} else {const zeroIn = indeg.filter(d => d === 0).length;const allAtMost1 = indeg.every(d => d <= 1);isTree = weakConnected && zeroIn === 1 && allAtMost1 && selfLoopCount === 0;}69 行未改动else if (nodes.length === 1) selDst.value = String(nodes[0].id);else selDst.value = '';}/* ============================================================* 数据导出* ============================================================ */function generateExportText() {const idToNum = new Map();nodes.forEach((nd, i) => idToNum.set(nd.id, i + 1));const lines = [];lines.push(`${nodes.length} ${edges.length}`);for (const e of edges) {const u = idToNum.get(e.a);const v = idToNum.get(e.b);if (u === undefined || v === undefined) continue;if (capEnabled) {const w = (typeof e.cap === 'number' && Number.isFinite(e.cap)) ? e.cap : 1;lines.push(`${u} ${v} ${fullNumStr(w)}`);} else {lines.push(`${u} ${v}`);}}return lines.join('\n');}function updateExport() {exportArea.value = generateExportText();}function showExportStatus(msg, isErr) {exportStatus.className = 'code-status ' + (isErr ? 'err' : 'ok');exportStatus.textContent = msg;clearTimeout(showExportStatus._timer);showExportStatus._timer = setTimeout(() => {exportStatus.textContent = '';exportStatus.className = 'code-status';}, 2200);}async function copyExport() {const text = exportArea.value;if (!text) { showExportStatus('没有可复制的内容', true); return; }try {if (navigator.clipboard && navigator.clipboard.writeText) {await navigator.clipboard.writeText(text);showExportStatus('✓ 已复制到剪贴板', false);} else {throw new Error('no clipboard');}} catch (err) {try {const wasReadonly = exportArea.readOnly;exportArea.readOnly = false;exportArea.select();exportArea.setSelectionRange(0, text.length);const ok = document.execCommand('copy');exportArea.readOnly = wasReadonly;window.getSelection().removeAllRanges();if (ok) showExportStatus('✓ 已复制到剪贴板', false);else showExportStatus('复制失败,请手动选中复制', true);} catch (e2) {showExportStatus('复制失败,请手动选中复制', true);}}}document.getElementById('btnExportCopy').addEventListener('click', copyExport);exportCard.addEventListener('toggle', () => {if (exportCard.open) updateExport();});function updateUI() {numNodesEl.value = nodes.length;if (!chkTree.checked) numEdgesEl.value = edges.length;const n = nodes.length;const maxE = directed ? n * (n - 1) : n * (n - 1) / 2;numEdgesEl.max = Math.max(0, maxE);let tagText = directed ? '有向图' : '无向图';2 行未改动tagEl.innerHTML = tagText;refreshSelectors();renderAnalysis();updateExport();}function refresh() {render();16 行未改动nodes[i].y = cy + ry * Math.sin(ang);}}function findTreeCentroid() {const adj = new Map();for (const nd of nodes) adj.set(nd.id, []);for (const e of edges) {187 行未改动全部展开const a = idx.get(e.a), b = idx.get(e.b);if (a === undefined || b === undefined) continue;adj[a].push(b);indeg[b]++;}let current = [];for (let i = 0; i < n; i++) if (indeg[i] === 0) current.push(i);6 行未改动processed += current.length;const next = [];for (const u of current) {for (const v of adj[u]) {if (v === u) continue;if (--indeg[v] === 0) next.push(v);}}next.sort((x, y) => x - y);71 行未改动while (q.length) {const u = q.shift();inQueue[u] = false;for (const [v, w] of adj[u]) {if (dist[u] + w < dist[v]) {dist[v] = dist[u] + w;parent[v] = u;if (!inQueue[v]) {20 行未改动}return { dist: dist[T], path };}function maxFlow(sId, tId) {const n = nodes.length;const idx = new Map();nodes.forEach((nd, i) => idx.set(nd.id, i));const cap = Array.from({ length: n }, () => new Array(n).fill(0));for (const e of edges) {const a = idx.get(e.a), b = idx.get(e.b);if (a === undefined || b === undefined) continue;if (a === b) continue;const c = edgeCap(e);if (c <= 0) continue;if (directed) cap[a][b] += c;else { cap[a][b] += c; cap[b][a] += c; }44 行未改动}const flowMap = new Map();for (const e of edges) {if (e.a === e.b) continue;const a = idx.get(e.a), b = idx.get(e.b);if (a === undefined || b === undefined) continue;const netAB = origCap[a][b] - cap[a][b];if (Math.abs(netAB) < 1e-9) continue;84 行未改动for (let k = 0; k < r.path.length - 1; k++) {const u = nodes[r.path[k]].id;const v = nodes[r.path[k + 1]].id;if (u === v) continue;let best = null, bestW = Infinity;for (const e of edges) {if (e.a === e.b) continue;if ((e.a === u && e.b === v) || (e.a === v && e.b === u)) {142 行未改动全部展开refresh();}/* ============================================================* 随机生成* ============================================================ */function randomGenerate() {const n = clamp(parseInt(numNodesEl.value, 10) || 0, 0, MAX_NODES);numNodesEl.value = n;61 行未改动wake();}/* ============================================================* 代码模式解析* ============================================================ */function parseCode(text) {const lines = text.split('\n').map(l => l.trim())30 行未改动}if (u < 1 || u > n || v < 1 || v > n) {throw new Error(`第 ${lineNum} 行顶点编号超出范围 [1, ${n}]`);}let w = 1;if (parts.length >= 3) {w = parseFloat(parts[2]);133 行未改动全部展开} else if (mode === 'edge') {if (pending === null) {pending = id;} else if (pending === id) {edges.push({ id: edgeSeq++, a: id, b: id, cap: 1 });pending = null;clearAllVisual();} else {edges.push({ id: edgeSeq++, a: pending, b: id, cap: 1 });pending = null;clearAllVisual();}99 行未改动btn.classList.add('active');directed = btn.dataset.type === 'directed';if (!directed) {let fixed = false;for (const e of edges) {if (typeof e.cap === 'number' && e.cap < 0) {e.cap = 0; fixed = true;118 行未改动全部展开const r = stage.getBoundingClientRect();W = Math.max(240, Math.round(r.width));H = Math.max(240, Math.round(r.height));}syncPhysSliders();randomGenerate();})();</script></body>2 行未改动