正文
增加 872 行删除 291 行
17 行未改动18192021222324252627285 行未改动343536373839404134 行未改动76777879808182838414 行未改动9910010110210310410510610710810911011111211311411520 行未改动13613713813914014114214314414514614714814915015115215315415515615715815910 行未改动17017117217317417517617717817 行未改动1961971981992002012022032042052062072082092102112122138 行未改动22222322422522622722822923023123223323423523623723834 行未改动2732742752762772782792802816 行未改动28828929029129229329429529629729829930023 行未改动3243253263273283293303313323333343356 行未改动3423433443453463473483493503513523533543553564 行未改动3613623633643653663673683693703713723733743753763773783793808 行未改动38939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547622 行未改动49950050150250350450550650750813 行未改动5225235245255265275285295309 行未改动5405415425435445455465477 行未改动55555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564616 行未改动66366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570 行未改动77677777877978078178278378478578678778878979079179279379479545 行未改动8418428438448458468478488498508517 行未改动85986086186286386486586686786832 行未改动90190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193212 行未改动9459469479489499509519523 行未改动9569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939947 行未改动100210031004100510061007100810091010101110121013101410151016101710187 行未改动102610271028102910301031103210331034103510361037103810391040104110421043104410 行未改动10551056105710581059106010611062106310641065106610676 行未改动1074107510761077107810791080108110821083108410851086108710881089109010911092109310945 行未改动11001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711486 行未改动115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312049 行未改动1214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125713 行未改动12711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813195 行未改动132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113926 行未改动1399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014318 行未改动1440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148311 行未改动149514961497149814991500150115025 行未改动1508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153317 行未改动1551155215531554155515561557155815591560156115621563156415654 行未改动15701571157215731574157515761577157815791580158115821583158415851586158715883 行未改动159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162825 行未改动16541655165616571658165916601661166211 行未改动16741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170615 行未改动1722172317241725172617271728172916 行未改动17461747174817491750175117521753175417551756175717581759176023 行未改动1784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180610 行未改动18171818181918201821182218231824182514 行未改动184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118624 行未改动18671868186918701871187218731874187518761877187818791880188118827 行未改动1890189118921893189418951896189718981899190082 行未改动198319841985198619871988198919902 行未改动17 行未改动-webkit-font-smoothing:antialiased;}.app{display:flex;height:100vh;}/* ================= 侧栏 ================= */.panel{width:340px;flex:0 0 340px;background:#fff;border-right:1px solid var(--border);padding:18px 16px 40px;overflow-y:auto;display:flex;flex-direction:column;gap:12px;}.panel h1{font-size:17px;margin:0 0 4px;letter-spacing:.3px;display:flex;align-items:center;gap:8px;}.panel h1::before{5 行未改动font-size:11px;text-transform:uppercase;letter-spacing:.1em;color:var(--muted);margin:0 0 10px;font-weight:700;}.seg{display:flex;background:#e2e8f0;border-radius:9px;padding:3px;gap:3px;}.seg-btn{flex:1;border:0;background:transparent;padding:7px 4px;border-radius:7px;font-size:13px;cursor:pointer;color:#475569;font-family:inherit;font-weight:500;transition:.15s;34 行未改动.btn-row .btn{margin-top:0;}.hint{font-size:12px;color:var(--muted);line-height:1.6;margin:9px 0 0;}/* ================= 分析 ================= */.stats{display:flex;gap:8px;margin-bottom:10px;}.stat{flex:1;background:#fff;border:1px solid var(--border);border-radius:9px;padding:8px;text-align:center;}.stat span{display:block;font-size:11px;color:var(--muted);margin-bottom:2px;}.stat b{font-size:18px;}14 行未改动padding:3px 7px;color:#475569;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;}.empty{font-size:12.5px;color:var(--muted);margin:0;line-height:1.7;}/* ================= 算法结果 ================= */.algo-result{margin-top:10px;font-size:12.5px;color:#334155;background:#fff;border:1px solid var(--border);border-radius:9px;padding:10px 11px;line-height:1.75;word-break:break-word;min-height:44px;}.algo-result .k{color:#2563eb;font-weight:700;font-family:ui-monospace,Menlo,monospace;}.algo-result .err{color:#b91c1c;font-weight:600;}.algo-result .inf{color:#b45309;font-weight:700;font-family:ui-monospace,Menlo,monospace;}.algo-result .seq{display:inline-block;font-family:ui-monospace,Menlo,monospace;background:#eff6ff;color:#1d4ed8;border-radius:5px;padding:1px 5px;margin:1px 0;}20 行未改动padding:2px 8px;border-radius:6px;border:1px solid transparent;font-weight:700;}.topo-note{font-size:11px;color:var(--muted);margin-top:9px;line-height:1.5;}/* ================= 画布 ================= */.stage{flex:1;position:relative;min-width:0;background:#fbfdff;}svg{display:block;width:100%;height:100%;touch-action:none;}.tag{position:absolute;left:14px;bottom:12px;font-size:12px;color:#94a3b8;background:rgba(255,255,255,.85);padding:5px 10px;border-radius:8px;border:1px solid var(--border);pointer-events:none;}.tag b{color:#f59e0b;}/* ================= 边设置弹窗 ================= */.edge-popup{position:absolute;display:none;z-index:100;background:#fff;border:1px solid #cbd5e1;border-radius:10px;box-shadow:0 10px 28px rgba(15,23,42,.18);padding:12px;min-width:210px;font-size:13px;}.edge-popup .popup-header{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:#64748b;font-weight:700;margin-bottom:8px;10 行未改动font-size:12.5px;color:#334155;flex:0 0 auto;}.edge-popup input[type=number]{flex:1;min-width:0;padding:6px 9px;border:1px solid #cbd5e1;border-radius:7px;font-size:13px;font-family:inherit;outline:none;text-align:right;color:var(--text);background:#fff;transition:.15s;}.edge-popup input[type=number]:focus{border-color:#2563eb;box-shadow:0 0 0 3px rgba(37,99,235,.12);17 行未改动</head><body><div class="app"><aside class="panel"><h1>图论可视化</h1><section class="card"><h2>图类型</h2><div class="seg" id="typeSeg"><button class="seg-btn active" data-type="undirected">无向图</button><button class="seg-btn" data-type="directed">有向图</button></div></section><section class="card"><h2>参数</h2><label class="row"><span>顶点数 n</span><input type="number" id="numNodes" min="0" max="60" value="7" step="1">8 行未改动<section class="card"><h2>容量 / 边权</h2><label class="check"><input type="checkbox" id="chkCap"> 启用容量 / 边权(默认 1)</label><p class="hint">开启后,图中边会显示容量数值;<b>右键点击任意边</b>可修改其容量或删除它。</p></section><section class="card"><h2>物理引擎</h2><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>34 行未改动<div class="edge-popup" id="edgePopup"><div class="popup-header" id="popupHeader">边设置</div><div class="popup-row"><label>容量 / 边权</label><input type="number" id="popupCapInput" min="0" max="9999" step="1" value="1"></div><div class="popup-actions"><button class="save" id="popupSave">保存</button><button class="delete" id="popupDelete">删除</button>6 行未改动<script>(() => {'use strict';/* ============================================================* 常量与状态* ============================================================ */const NODE_R = 20;const MAX_NODES = 60;const LAYER_PALETTE = [{ fill:'#dbeafe', stroke:'#2563eb', text:'#1e40af' },{ fill:'#d1fae5', stroke:'#059669', text:'#065f46' },23 行未改动const selDst = document.getElementById('selDst');const edgePopup = document.getElementById('edgePopup');const popupHeader= document.getElementById('popupHeader');const popupCapInput = document.getElementById('popupCapInput');let W = 900, H = 650;let nodes = []; // {id, x, y, vx, vy}let edges = []; // {id, a, b, cap}let nodeSeq = 1;let edgeSeq = 1;6 行未改动let capEnabled = false;let popupEdgeId = null;/* 三种可视化高亮(互斥) */let highlight = { nodeIds: new Set(), edgeIds: new Set() };let topoColorMap = new Map();let flowHighlight = new Map();/* ============================================================* 物理参数* ============================================================ */const PHYS = {restitution: 0.78,damping: 0.925,4 行未改动sleepSpeed: 0.075,iterations: 2};let physicsEnabled = chkPhysics.checked;let physicsOn = false;let lastFrame = 0;/* ============================================================* 小工具* ============================================================ */const clamp = (v, a, b) => Math.max(a, Math.min(b, v));const getNode = id => nodes.find(n => n.id === id);const idxOf = id => nodes.findIndex(n => n.id === id);const nameOf = id => { const i = idxOf(id); return i >= 0 ? `v${i + 1}` : '?'; };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 hasEdge(a, b) {if (directed) return edges.some(e => e.a === a && e.b === b);return edges.some(e => (e.a === a && e.b === b) || (e.a === b && e.b === a));}/* 边的有效容量:开启容量模式时使用存储值,否则为 1 */function edgeCap(e) {if (!capEnabled) return 1;return (typeof e.cap === 'number' && e.cap >= 0) ? e.cap : 1;}function clearHighlight() { highlight = { nodeIds: new Set(), edgeIds: new Set() }; }function clearTopo() { topoColorMap = new Map(); }function clearFlow() { flowHighlight = new Map(); }function clearAllVisual() { clearHighlight(); clearTopo(); clearFlow(); closePopup(); }/* ============================================================* 几何* ============================================================ */function edgePath(A, B, curved, arrowRoom) {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 r1 = NODE_R;const r2 = NODE_R + (arrowRoom ? 3 : 0);if (!curved) {return `M ${A.x + ux * r1} ${A.y + uy * r1} L ${B.x - ux * r2} ${B.y - uy * r2}`;}const lo = A.id < B.id ? A : B;const hi = A.id < B.id ? B : A;const cdx = hi.x - lo.x, cdy = hi.y - lo.y;const cd = Math.hypot(cdx, cdy) || 1;const cpx = -cdy / cd, cpy = cdx / cd;const sign = (A.id < B.id) ? 1 : -1;const off = 28 * sign;const cx = (A.x + B.x) / 2 + cpx * off;const cy = (A.y + B.y) / 2 + cpy * off;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;const edx = cx - B.x, edy = cy - B.y, ed = Math.hypot(edx, edy) || 1;const ex = B.x + edx / ed * r2, ey = B.y + edy / ed * r2;return `M ${sx} ${sy} Q ${cx} ${cy} ${ex} ${ey}`;}function edgeMidpoint(A, B, curved) {if (!curved) {return { x: (A.x + B.x) / 2, y: (A.y + B.y) / 2 };}const lo = A.id < B.id ? A : B;const hi = A.id < B.id ? B : A;const cdx = hi.x - lo.x, cdy = hi.y - lo.y;const cd = Math.hypot(cdx, cdy) || 1;const cpx = -cdy / cd, cpy = cdx / cd;const sign = (A.id < B.id) ? 1 : -1;const off = 28 * sign;const cx = (A.x + B.x) / 2 + cpx * off;const cy = (A.y + B.y) / 2 + cpy * off;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 openPopup(edge, clientX, clientY) {popupEdgeId = edge.id;const ia = idxOf(edge.a), ib = idxOf(edge.b);popupHeader.textContent = `边 v${ia + 1} ${directed ? '→' : '—'} v${ib + 1}`;popupCapInput.value = edge.cap ?? 1;/* 先显示,再测量尺寸以便修正位置 */edgePopup.style.display = 'block';const stageRect = stage.getBoundingClientRect();let x = clientX - stageRect.left + 12;22 行未改动function savePopup() {if (popupEdgeId === null) return;const edge = edges.find(x => x.id === popupEdgeId);if (!edge) { closePopup(); return; }const v = parseInt(popupCapInput.value, 10);edge.cap = (isNaN(v) || v < 0) ? 1 : Math.min(v, 9999);closePopup();clearAllVisual();refresh();}13 行未改动if (e.key === 'Enter') { e.preventDefault(); savePopup(); }else if (e.key === 'Escape') { e.preventDefault(); closePopup(); }});/* 点击弹窗外部自动关闭 */document.addEventListener('pointerdown', e => {if (edgePopup.style.display === 'block' && !edgePopup.contains(e.target)) {closePopup();}9 行未改动requestAnimationFrame(() => { rafPending = false; render(); });}function render() {const nmap = new Map(nodes.map(n => [n.id, n]));let html = `<defs>7 行未改动<marker id="arrowHot" 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="#f59e0b"/></marker></defs><rect data-blank="1" x="0" y="0" width="${W}" height="${H}" fill="url(#grid)"/>`;/* ---------------- 边 ---------------- */for (const e of edges) {const A = nmap.get(e.a), B = nmap.get(e.b);if (!A || !B) continue;const curved = directed && edges.some(o => o.a === e.b && o.b === e.a);const d = edgePath(A, B, curved, directed);const hot = highlight.edgeIds.has(e.id);const hasFlow = flowHighlight.has(e.id);/* 边宽随容量变化(仅容量模式) */let sw = 2;if (capEnabled) {const c = (typeof e.cap === 'number') ? e.cap : 1;sw = Math.min(6, 2 + 0.35 * Math.max(0, c - 1));}if (hot) sw = Math.max(sw, 3.2);const stroke = hot ? '#f59e0b' : '#94a3b8';const marker = hot && directed ? 'url(#arrowHot)' : (directed ? 'url(#arrow)' : '');html += `<path d="${d}" fill="none" stroke="${stroke}" stroke-width="${sw}"stroke-linecap="round" pointer-events="none"${marker ? `marker-end="${marker}"` : ''}/>`;/* 有流量的边:叠加半透明蓝色底层高亮 */if (hasFlow) {html += `<path d="${d}" fill="none" stroke="rgba(59,130,246,0.35)"stroke-width="${sw + 4}" stroke-linecap="round" pointer-events="none"/>`;}html += `<path data-edge="${e.id}" d="${d}" fill="none" stroke="none"stroke-width="16" pointer-events="stroke" style="cursor:pointer"/>`;}/* ---------------- 容量标签 ---------------- */if (capEnabled) {for (const e of edges) {const A = nmap.get(e.a), B = nmap.get(e.b);if (!A || !B) continue;const len = Math.hypot(B.x - A.x, B.y - A.y);if (len < 76) continue; // 太短的边不显示标签const curved = directed && edges.some(o => o.a === e.b && o.b === e.a);const mid = edgeMidpoint(A, B, curved);let lx = mid.x, ly = mid.y;if (!curved) {const dx = B.x - A.x, dy = B.y - A.y;const d = Math.hypot(dx, dy) || 1;let px = -dy / d, py = dx / d;if (py > 0) { px = -px; py = -py; } // 让标签朝上lx += px * 15;ly += py * 15;}const txt = String((typeof e.cap === 'number') ? e.cap : 1);const bw = 10 + txt.length * 7.5;const bh = 18;html += `<g pointer-events="none"><rect x="${lx - bw / 2}" y="${ly - bh / 2}" width="${bw}" height="${bh}" rx="5"fill="#ffffff" stroke="#bfdbfe" stroke-width="1"/><text x="${lx}" y="${ly}" text-anchor="middle" dominant-baseline="central"font-size="11.5" font-weight="700" fill="#1d4ed8"font-family="ui-monospace,Menlo,monospace">${txt}</text></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;const curved = directed && edges.some(o => o.a === e.b && o.b === e.a);const mid = edgeMidpoint(A, B, curved);let dx, dy;if (info.dir === 'a→b') { dx = B.x - A.x; dy = B.y - A.y; }else { dx = A.x - B.x; dy = A.y - B.y; }16 行未改动stroke="rgba(37,99,235,0.95)" stroke-width="1.4"stroke-linejoin="round" pointer-events="none"/>`;if (info.amount > 1) {html += `<text x="${mid.x + px * 17}" y="${mid.y + py * 17}"text-anchor="middle" dominant-baseline="central"font-size="11" font-weight="700" fill="#1d4ed8"pointer-events="none"font-family="ui-monospace,Menlo,monospace">${info.amount}</text>`;}}}/* ---------------- 连边预览 ---------------- */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);const lc = topoColorMap.get(nd.id);let fill = '#ffffff', stroke = '#64748b', sw = 2, txt = '#0f172a';if (isPend) {fill = '#dbeafe'; stroke = '#2563eb'; sw = 2.5;} else if (isHot) {fill = '#fef3c7'; stroke = '#f59e0b'; sw = 2.8;} else if (lc) {fill = lc.fill; stroke = lc.stroke; sw = 2.6; txt = lc.text;}const cursor = mode === 'erase' ? 'pointer': mode === 'edge' ? 'crosshair': 'grab';70 行未改动for (let i = 0; i < nodes.length; i++) {const a = nodes[i];for (let j = i + 1; j < nodes.length; j++) {const b = nodes[j];let dx = b.x - a.x;let dy = b.y - a.y;let d = Math.hypot(dx, dy);if (d >= minD) continue;if (d < 0.001) {const ang = Math.random() * Math.PI * 2;dx = Math.cos(ang); dy = Math.sin(ang); d = 0.001;} else {dx /= d; dy /= d;}const overlap = minD - d;const aFix = (a === dragged) ? 0 : 1;const bFix = (b === dragged) ? 0 : 1;45 行未改动for (const e of edges) {const a = idx.get(e.a), b = idx.get(e.b);if (a === undefined || b === undefined) continue;adjU[a].push(b); adjU[b].push(a);adjOut[a].push(b); adjIn[b].push(a);outdeg[a]++; indeg[b]++;}const degU = adjU.map(a => a.length);const seen = new Array(n).fill(false);7 行未改动for (const v of adjU[u]) if (!seen[v]) { seen[v] = true; stack.push(v); }}}const weakConnected = (n === 0) || comps === 1;const cycleU = m > n - comps;let cycleD = false;{const deg = indeg.slice();const q = [];32 行未改动let isTree = false;if (n > 0) {if (!directed) {isTree = weakConnected && m === n - 1;} else {const zeroIn = indeg.filter(d => d === 0).length;const allAtMost1 = indeg.every(d => d <= 1);isTree = weakConnected && zeroIn === 1 && allAtMost1;}}return {n, m, comps, weakConnected, stronglyConnected,hasCycle: directed ? cycleD : cycleU,isTree, indeg, outdeg, degU};}function renderAnalysis() {const r = analyze();if (r.n === 0) {analysisEl.innerHTML =`<p class="empty">画布为空。请设置顶点数后点击「随机生成」,或直接在空白处单击添加顶点。</p>`;return;}const badge = (ok, yes, no) =>`<span class="badge ${ok ? 'yes' : 'no'}">${ok ? yes : no}</span>`;let html = `<div class="stats">12 行未改动html += `<li><span class="lbl">强连通</span><span class="rgt">${badge(r.stronglyConnected, '是', '否')}</span></li>`;html += `<li><span class="lbl">是否含环</span><span class="rgt">${badge(r.hasCycle, '有环', '无环')}</span></li>`;html += `<li><span class="lbl">是否为有向树</span><span class="rgt">${badge(r.isTree, '是 ✔', '否 ✘')}</span></li>`;}html += `</ul>`;html += `<p class="deg-title">${directed ? '各顶点入度 / 出度' : '各顶点度数'}</p><div class="deg-list">`;nodes.forEach((nd, i) => {3 行未改动html += `<span class="deg">v${i + 1} : ${r.degU[i]}</span>`;}});html += `</div>`;analysisEl.innerHTML = html;}/* ============================================================* UI 同步* ============================================================ */function refreshSelectors() {const oldSrc = selSrc.value;const oldDst = selDst.value;const opts = nodes.map((nd, i) => `<option value="${nd.id}">v${i + 1}</option>`).join('');selSrc.innerHTML = opts || '<option value="">—</option>';selDst.innerHTML = opts || '<option value="">—</option>';const hasSrc = nodes.some(nd => String(nd.id) === oldSrc);selSrc.value = hasSrc ? oldSrc : (nodes.length ? String(nodes[0].id) : '');const hasDst = nodes.some(nd => String(nd.id) === oldDst);if (hasDst) {selDst.value = oldDst;} else if (nodes.length > 1) {selDst.value = String(nodes[nodes.length - 1].id);} 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;7 行未改动tagEl.innerHTML = tagText;refreshSelectors();renderAnalysis();}function refresh() {render();updateUI();}/* ============================================================* 布局:圆形* ============================================================ */function layoutCircle() {const n = nodes.length;if (n === 0) return;7 行未改动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) {adj.get(e.a).push(e.b);adj.get(e.b).push(e.a);}function bfs(start) {const dist = new Map([[start, 0]]);const parent = new Map([[start, null]]);const queue = [start];10 行未改动}}return { last, parent };}const start = nodes[0].id;const r1 = bfs(start);const r2 = bfs(r1.last);let cur = r2.last;const path = [cur];while (cur !== r1.last) {cur = r2.parent.get(cur);6 行未改动function computeTreeLayout(rootId) {const adj = new Map();for (const nd of nodes) adj.set(nd.id, []);for (const e of edges) {if (directed) {adj.get(e.a).push(e.b);} else {adj.get(e.a).push(e.b);adj.get(e.b).push(e.a);}}const children = new Map();const visited = new Set([rootId]);const depth = new Map([[rootId, 0]]);const queue = [rootId];while (queue.length) {const u = queue.shift();const kids = [];for (const v of adj.get(u) || []) {5 行未改动}}children.set(u, kids);}const xs = new Map();let cursor = 0;function place(id) {const kids = children.get(id) || [];if (kids.length === 0) {const x = cursor;cursor += 1;xs.set(id, x);return x;}let sum = 0;for (const c of kids) sum += place(c);const x = sum / kids.length;xs.set(id, x);return x;}place(rootId);return { xs, depth, numLeaves: cursor };}function applyTreeLayout(rootId) {const { xs, depth, numLeaves } = computeTreeLayout(rootId);let maxDepth = 0;for (const d of depth.values()) maxDepth = Math.max(maxDepth, d);const paddingX = 60;const paddingY = 70;const availW = Math.max(1, W - paddingX * 2);const availH = Math.max(1, H - paddingY * 2 - NODE_R);const spacingX = numLeaves <= 1 ? 0 : Math.min(160, availW / (numLeaves - 1));const spacingY = maxDepth <= 0 ? 0 : Math.min(130, availH / maxDepth);const totalW = (numLeaves - 1) * spacingX;const offsetX = (W - totalW) / 2;const offsetY = paddingY;for (const nd of nodes) {const x = xs.get(nd.id);const d = depth.get(nd.id);if (x === undefined || d === undefined) continue;6 行未改动function applyLayeredLayout() {const adj = new Map();for (const nd of nodes) adj.set(nd.id, []);for (const e of edges) {adj.get(e.a).push(e.b);adj.get(e.b).push(e.a);}const level = new Map();const sorted = [...nodes].sort((a, b) =>(adj.get(b.id) || []).length - (adj.get(a.id) || []).length);for (const startNode of sorted) {if (level.has(startNode.id)) continue;level.set(startNode.id, 0);const queue = [startNode.id];while (queue.length) {const u = queue.shift();for (const v of adj.get(u) || []) {if (!level.has(v)) {level.set(v, level.get(u) + 1);queue.push(v);}}}}let maxLevel = 0;for (const l of level.values()) maxLevel = Math.max(maxLevel, l);const byLevel = new Map();for (const nd of nodes) {const l = level.get(nd.id) || 0;if (!byLevel.has(l)) byLevel.set(l, []);byLevel.get(l).push(nd.id);}const paddingX = 60;const paddingY = 70;const availW = Math.max(1, W - paddingX * 2);const availH = Math.max(1, H - paddingY * 2 - NODE_R);const numLevels = maxLevel + 1;const spacingY = numLevels <= 1 ? 0 : Math.min(130, availH / (numLevels - 1));for (const [l, ids] of byLevel) {const spacingX = ids.length <= 1 ? 0 : Math.min(160, availW / (ids.length - 1));const totalW = (ids.length - 1) * spacingX;const startX = (W - totalW) / 2;9 行未改动}function tidyLayout() {if (nodes.length === 0) return;const r = analyze();if (r.isTree) {let rootId;if (directed) {const indeg = new Map();nodes.forEach(nd => indeg.set(nd.id, 0));for (const e of edges) indeg.set(e.b, indeg.get(e.b) + 1);for (const [id, d] of indeg) {if (d === 0) { rootId = id; break; }}} else {rootId = findTreeCentroid();}if (rootId !== undefined) {applyTreeLayout(rootId);}} else {applyLayeredLayout();}nodes.forEach(nd => { nd.vx = 0; nd.vy = 0; });refresh();}/* ============================================================* 图算法核心* ============================================================ *//* ---------- 拓扑排序(Kahn,按层返回) ---------- */function topoSort() {if (!directed) {return { ok: false, msg: '拓扑排序仅适用于有向图。请先切换到「有向图」。' };}const n = nodes.length;if (n === 0) return { ok: false, msg: '画布为空,请先添加顶点。' };const idx = new Map();13 行未改动current.sort((x, y) => x - y);const levels = [];let processed = 0;while (current.length) {levels.push(current);processed += current.length;const next = [];for (const u of current) {for (const v of adj[u]) {if (--indeg[v] === 0) next.push(v);}}next.sort((x, y) => x - y);current = next;}if (processed < n) {return { ok: false, msg: '图中存在环,不存在拓扑排序。' };}return { ok: true, levels };}/* ---------- 最短路(Dijkstra,权重 = 边容量) ---------- */function shortestPath(sId, tId) {const n = nodes.length;const idx = new Map();nodes.forEach((nd, i) => idx.set(nd.id, i));/* 邻接表:[邻居, 权重] */const adj = Array.from({ length: n }, () => []);for (const e of edges) {const a = idx.get(e.a), b = idx.get(e.b);if (a === undefined || b === undefined) continue;const w = edgeCap(e);adj[a].push([b, w]);if (!directed) adj[b].push([a, w]);}const S = idx.get(sId), T = idx.get(tId);if (S === undefined || T === undefined) return null;if (S === T) return { dist: 0, path: [S] };const dist = new Array(n).fill(Infinity);const parent = new Array(n).fill(-1);const visited = new Array(n).fill(false);dist[S] = 0;5 行未改动}if (u === -1) break;visited[u] = true;if (u === T) break;for (const [v, w] of adj[u]) {if (!visited[v] && dist[u] + w < dist[v]) {dist[v] = dist[u] + w;parent[v] = u;}}}if (dist[T] === Infinity) return { dist: Infinity, path: null };const path = [];let v = T;while (v !== -1) {path.unshift(v);if (v === S) break;v = parent[v];}return { dist: dist[T], path };}/* ---------- 最大流(Edmonds-Karp,容量 = 边容量) ----------* 返回 { value, flowMap }* flowMap: Map<edgeId, { dir: 'a→b' | 'b→a', amount: number }>*/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;const c = edgeCap(e);if (c <= 0) continue;if (directed) {cap[a][b] += c;} else {cap[a][b] += c;cap[b][a] += c;}}const origCap = cap.map(r => r.slice());const S = idx.get(sId), T = idx.get(tId);if (S === undefined || T === undefined) return null;if (S === T) return { value: 0, flowMap: new Map() };let flow = 0;const INF = 1e9;while (true) {const parent = new Array(n).fill(-1);parent[S] = S;const q = [S];while (q.length && parent[T] === -1) {const u = q.shift();for (let v = 0; v < n; v++) {if (parent[v] === -1 && cap[u][v] > 0) {parent[v] = u;q.push(v);}}6 行未改动const u = parent[v];bottleneck = Math.min(bottleneck, cap[u][v]);v = u;}v = T;while (v !== S) {const u = parent[v];cap[u][v] -= bottleneck;cap[v][u] += bottleneck;v = u;}flow += bottleneck;if (bottleneck === 0) break;}/* 从残量网络反推每条边的净流量与方向 */const flowMap = new Map();for (const e of edges) {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 (netAB > 0) {flowMap.set(e.id, { dir: 'a→b', amount: netAB });} else if (netAB < 0) {flowMap.set(e.id, { dir: 'b→a', amount: -netAB });}}return { value: flow, flowMap };}8 行未改动}function showTopo() {const r = topoSort();if (!r.ok) {algoResult.innerHTML = `<span class="err">${r.msg}</span>`;clearTopo(); clearFlow();render();return;}topoColorMap = new Map();r.levels.forEach((level, li) => {const pal = LAYER_PALETTE[li % LAYER_PALETTE.length];for (const ni of level) {topoColorMap.set(nodes[ni].id, { ...pal, layer: li + 1 });}});let html = `<b>拓扑排序(共 ${r.levels.length} 层)</b>`;r.levels.forEach((level, li) => {const pal = LAYER_PALETTE[li % LAYER_PALETTE.length];const chips = level.map(ni =>`<span class="chip" style="background:${pal.fill};color:${pal.text};border-color:${pal.stroke}">v${ni + 1}</span>`).join('');html += `<div class="topo-level"><span class="lv-tag" style="background:${pal.stroke}">第 ${li + 1} 层</span><span class="lv-nodes">${chips}</span></div>`;});html += `<div class="topo-note">同层顶点互不可达(不存在层内边);层号越靠前的顶点越先被处理。</div>`;algoResult.innerHTML = html;clearHighlight();clearFlow();render();}function showPath() {11 行未改动if (!r) { algoResult.innerHTML = '<span class="err">选择的顶点无效。</span>'; return; }const sName = nameOf(sel.s), dName = nameOf(sel.d);if (r.dist === Infinity) {algoResult.innerHTML =`${sName} → ${dName} 的最短路:<span class="inf">INF</span>(不可达)`;clearHighlight();5 行未改动const edgeIds = new Set();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;const e = edges.find(e =>(e.a === u && e.b === v) || (e.a === v && e.b === u));if (e) edgeIds.add(e.id);}highlight = { nodeIds, edgeIds };const pathStr = r.path.map(i => `<span class="seq">v${i + 1}</span>`).join('<span class="arrow">→</span>');const distLabel = capEnabled? `最短路径权重:<span class="k">${r.dist}</span>(按边权累加)`: `最短路长度:<span class="k">${r.dist}</span> 条边`;algoResult.innerHTML =`<b>${sName} → ${dName}</b><br>` +`${distLabel}<br>` +`路径:${pathStr}`;render();}17 行未改动clearFlow(); render(); return;}flowHighlight = result.flowMap;const sName = nameOf(sel.s), dName = nameOf(sel.d);const usedEdges = flowHighlight.size;let extra = '';if (!directed) extra += '<br><span style="color:#94a3b8;font-size:11.5px">(无向边双向容量各 = 边容量)</span>';if (capEnabled) extra += '<br><span style="color:#94a3b8;font-size:11.5px">(按自定义容量计算)</span>';else extra += '<br><span style="color:#94a3b8;font-size:11.5px">(所有边容量 = 1)</span>';let flowInfo;if (usedEdges > 0) {4 行未改动}algoResult.innerHTML =`<b>${sName} → ${dName}</b><br>` +`最大流:<span class="k">${result.value}</span> 单位${extra}${flowInfo}`;render();}/* ============================================================* 手动增删* ============================================================ */function setNodeCount(target) {target = clamp(target, 0, MAX_NODES);while (nodes.length < target) {let best = { x: W / 2, y: H / 2 }, bestD = -1;for (let t = 0; t < 24; t++) {const x = NODE_R + 24 + Math.random() * Math.max(1, W - 2 * NODE_R - 48);3 行未改动if (d > bestD) { bestD = d; best = { x, y }; }}nodes.push({ id: nodeSeq++, x: best.x, y: best.y, vx: 0, vy: 0 });}while (nodes.length > target) {const nd = nodes.pop();edges = edges.filter(e => e.a !== nd.id && e.b !== nd.id);}if (pending !== null && !nodes.some(n => n.id === pending)) pending = null;clearAllVisual();refresh();}function setEdgeCount(target) {const n = nodes.length;const maxE = directed ? n * (n - 1) : n * (n - 1) / 2;target = clamp(target, 0, maxE);if (target > edges.length) {const pool = [];for (let i = 0; i < n; i++) {for (let j = i + 1; j < n; j++) {const a = nodes[i].id, b = nodes[j].id;if (!hasEdge(a, b)) pool.push([a, b]);if (directed && !hasEdge(b, a)) pool.push([b, a]);}}shuffle(pool);for (const [a, b] of pool) {if (edges.length >= target) break;if (!hasEdge(a, b)) edges.push({ id: edgeSeq++, a, b, cap: 1 });}} else if (target < edges.length) {const shuffled = shuffle(edges.slice());const keep = new Set(shuffled.slice(0, target).map(e => e.id));25 行未改动numNodesEl.value = n;const wantTree = chkTree.checked;const wantConn = chkConn.checked;const maxE = directed ? n * (n - 1) : n * (n - 1) / 2;const m = wantTree? Math.max(0, n - 1): clamp(parseInt(numEdgesEl.value, 10) || 0, 0, maxE);11 行未改动edgeSeq = 1;const used = new Set();const keyOf = (a, b) =>directed ? `${a}>${b}` : (a < b ? `${a}-${b}` : `${b}-${a}`);const addE = (a, b) => {if (a === b || a === undefined || b === undefined) return false;const k = keyOf(a, b);if (used.has(k)) return false;used.add(k);edges.push({ id: edgeSeq++, a, b, cap: 1 });return true;};const ids = nodes.map(nd => nd.id);if (n > 1 && (wantTree || (wantConn && m >= n - 1))) {const perm = shuffle(ids.slice());for (let i = 1; i < n; i++) {const p = Math.floor(Math.random() * i);const a = perm[p], b = perm[i];if (directed && !wantTree) {if (Math.random() < 0.5) addE(a, b); else addE(b, a);} else {addE(a, b);}}}if (!wantTree) {const pool = [];for (let i = 0; i < n; i++) {for (let j = i + 1; j < n; j++) {15 行未改动wake();}/* ============================================================* 指针交互* ============================================================ */svg.addEventListener('pointerdown', e => {if (e.pointerType === 'mouse' && e.button !== 0) return;16 行未改动} else if (mode === 'edge') {if (pending === null) {pending = id;} else if (pending === id) {pending = null;} else {if (!hasEdge(pending, id)) {edges.push({ id: edgeSeq++, a: pending, b: id, cap: 1 });clearAllVisual();}pending = null;}hoverPt = pt;refresh();23 行未改动const nx = clamp(pt.x - drag.ox, NODE_R + 4, W - NODE_R - 4);const ny = clamp(pt.y - drag.oy, NODE_R + 4, H - NODE_R - 4);if (physicsEnabled) {let vx = nx - nd.x;let vy = ny - nd.y;const sp = Math.hypot(vx, vy);if (sp > PHYS.maxSpeed) {vx = vx / sp * PHYS.maxSpeed;vy = vy / sp * PHYS.maxSpeed;}nd.vx = vx;nd.vy = vy;nd.x = nx;nd.y = ny;wake();} else {nd.x = nx;nd.y = ny;nd.vx = 0; nd.vy = 0;scheduleRender();}return;10 行未改动drag = null;if (physicsEnabled) wake();else updateUI();}if (blankDown) {const pt = svgPoint(e);if (Math.hypot(pt.x - blankDown.x, pt.y - blankDown.y) < 6) {if (nodes.length < MAX_NODES) {14 行未改动});window.addEventListener('pointercancel', () => { drag = null; blankDown = null; });/* ============================================================* 右键:编辑边容量 / 删除边* ============================================================ */svg.addEventListener('contextmenu', e => {e.preventDefault();if (!capEnabled) return; // 容量模式未启用,不做任何事const edgeEl = e.target.closest ? e.target.closest('[data-edge]') : null;if (!edgeEl) { closePopup(); return; }const edgeId = Number(edgeEl.dataset.edge);const edge = edges.find(x => x.id === edgeId);if (!edge) return;openPopup(edge, e.clientX, e.clientY);});/* ============================================================4 行未改动if (!btn) return;document.querySelectorAll('#typeSeg .seg-btn').forEach(b => b.classList.remove('active'));btn.classList.add('active');directed = btn.dataset.type === 'directed';pending = null;clearAllVisual();refresh();});const HINTS = {drag: '拖动顶点调整位置;在空白处单击可新增顶点。松手后顶点会带有惯性并相互弹开。',edge: '依次点击两个顶点添加一条边;再次点击同一点可取消选择。',erase: '点击顶点或边将其删除(删除顶点会同时删除其所有连边)。'};document.getElementById('modeSeg').addEventListener('click', e => {const btn = e.target.closest('.seg-btn');7 行未改动});chkPhysics.addEventListener('change', () => {physicsEnabled = chkPhysics.checked;if (physicsEnabled) {wake();} else {nodes.forEach(nd => { nd.vx = 0; nd.vy = 0; });updateUI();}updateUI();82 行未改动const r = stage.getBoundingClientRect();W = Math.max(240, Math.round(r.width));H = Math.max(240, Math.round(r.height));}randomGenerate();})();</script></body>2 行未改动17 行未改动181920212223242526275 行未改动33343536373839404142434445464748495051525334 行未改动88899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215314 行未改动16816917017117217317417517617717817918018118218318420 行未改动20520620720820921021121221321421521621721821922022122222322422522610 行未改动23723823924024124224324424517 行未改动2632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243258 行未改动33433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139234 行未改动4274284294304314324334344356 行未改动44244344444544644744844945045145223 行未改动4764774784794804814824834844854864874884894904914926 行未改动4995005015025035045055065075085095105115125135144 行未改动5195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565578 行未改动56656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878922 行未改动81281381481581681781881982082182282382482513 行未改动8398408418428438448458469 行未改动8568578588598608618628638647 行未改动87287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797816 行未改动995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104570 行未改动1116111711181119112011211122112311241125112611271128112911301131113245 行未改动1178117911801181118211831184118511861187118811891190119111921193119411951196119711987 行未改动1206120712081209121012111212121312141215121612171218121932 行未改动12521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312 行未改动13061307130813091310131113121313131413151316131713183 行未改动13221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014217 行未改动1429143014311432143314341435143614371438143914401441144214431444144514467 行未改动145414551456145714581459146014611462146314641465146614671468146910 行未改动148014811482148314841485148614871488148914906 行未改动14971498149915001501150215031504150515061507150815091510151115125 行未改动151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115526 行未改动15591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715989 行未改动16081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164313 行未改动1657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617075 行未改动17131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118126 行未改动181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618478 行未改动1856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189011 行未改动1902190319041905190619071908190919101911191219131914191519161917191819195 行未改动1925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196217 行未改动198019811982198319841985198619871988198919901991199219934 行未改动1998199920002001200220032004200520062007200820092010201120122013201420153 行未改动201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205825 行未改动2084208520862087208820892090209111 行未改动210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213015 行未改动2146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230916 行未改动23262327232823292330233123322333233423352336233723382339234023 行未改动236423652366236723682369237023712372237323742375237623772378237923802381238210 行未改动2393239423952396239723982399240014 行未改动24152416241724182419242024212422242324242425242624272428242924304 行未改动243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224637 行未改动247124722473247424752476247724782479248082 行未改动2563256425652566256725682569257025712 行未改动17 行未改动-webkit-font-smoothing:antialiased;}.app{display:flex;height:100vh;}.panel{width:350px;flex:0 0 350px;background:#fff;border-right:1px solid var(--border);padding:18px 16px 40px;overflow-y:auto;display:flex;flex-direction:column;gap:12px;}.panel h1{font-size:17px;margin:0 0 4px;letter-spacing:.3px;display:flex;align-items:center;gap:8px;}.panel h1::before{5 行未改动font-size:11px;text-transform:uppercase;letter-spacing:.1em;color:var(--muted);margin:0 0 10px;font-weight:700;}details.card summary{cursor:pointer;font-size:13px;font-weight:700;color:var(--text);list-style:none;display:flex;align-items:center;gap:7px;margin:-12px;padding:12px;border-radius:12px;user-select:none;}details.card summary::-webkit-details-marker{display:none;}details.card summary::before{content:"▶";font-size:9px;color:#64748b;transition:transform .18s ease;display:inline-block;}details.card[open] summary::before{transform:rotate(90deg);}details.card[open] summary{border-bottom:1px solid var(--border);border-radius:12px 12px 0 0;margin-bottom:10px;}.seg{display:flex;background:#e2e8f0;border-radius:9px;padding:3px;gap:3px;}.seg-btn{flex:1;border:0;background:transparent;padding:7px 4px;border-radius:7px;font-size:13px;cursor:pointer;color:#475569;font-family:inherit;font-weight:500;transition:.15s;34 行未改动.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;}.stats{display:flex;gap:8px;margin-bottom:10px;}.stat{flex:1;background:#fff;border:1px solid var(--border);border-radius:9px;padding:8px;text-align:center;}.stat span{display:block;font-size:11px;color:var(--muted);margin-bottom:2px;}.stat b{font-size:18px;}14 行未改动padding:3px 7px;color:#475569;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;}.empty{font-size:12.5px;color:var(--muted);margin:0;line-height:1.7;}.algo-result{margin-top:10px;font-size:12.5px;color:#334155;background:#fff;border:1px solid var(--border);border-radius:9px;padding:10px 11px;line-height:1.75;word-break:break-word;min-height:44px;}.algo-result .k{color:#2563eb;font-weight:700;font-family:ui-monospace,Menlo,monospace;}.algo-result .err{color:#b91c1c;font-weight:600;}.algo-result .inf{color:#b45309;font-weight:700;font-family:ui-monospace,Menlo,monospace;}.algo-result .neg{color:#dc2626;font-weight:700;font-family:ui-monospace,Menlo,monospace;}.algo-result .seq{display:inline-block;font-family:ui-monospace,Menlo,monospace;background:#eff6ff;color:#1d4ed8;border-radius:5px;padding:1px 5px;margin:1px 0;}20 行未改动padding:2px 8px;border-radius:6px;border:1px solid transparent;font-weight:700;}.topo-note{font-size:11px;color:var(--muted);margin-top:9px;line-height:1.5;}.stage{flex:1;position:relative;min-width:0;background:#fbfdff;}svg{display:block;width:100%;height:100%;touch-action:none;}.tag{position:absolute;left:14px;bottom:12px;font-size:12px;color:#94a3b8;background:rgba(255,255,255,.85);padding:5px 10px;border-radius:8px;border:1px solid var(--border);pointer-events:none;}.tag b{color:#f59e0b;}.edge-popup{position:absolute;display:none;z-index:100;background:#fff;border:1px solid #cbd5e1;border-radius:10px;box-shadow:0 10px 28px rgba(15,23,42,.18);padding:12px;min-width:230px;font-size:13px;}.edge-popup .popup-header{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:#64748b;font-weight:700;margin-bottom:8px;10 行未改动font-size:12.5px;color:#334155;flex:0 0 auto;}.edge-popup input[type=number]{flex:1;min-width:0;padding:6px 9px;border:1px solid #cbd5e1;border-radius:7px;font-size:13px;font-family:ui-monospace,Menlo,monospace;outline:none;text-align:right;color:var(--text);background:#fff;transition:.15s;}.edge-popup input[type=number]:focus{border-color:#2563eb;box-shadow:0 0 0 3px rgba(37,99,235,.12);17 行未改动</head><body><div class="app"><aside class="panel"><h1>图论可视化 2D</h1><section class="card"><h2>图类型</h2><div class="seg" id="typeSeg"><button class="seg-btn active" data-type="undirected">无向图</button><button class="seg-btn" data-type="directed">有向图</button></div></section><details class="card" id="codeCard"><summary>📝 代码模式</summary><div><div style="font-size:12px;color:#64748b;line-height:1.7;background:#eef2f7;border-radius:8px;padding:8px 10px;margin-bottom:2px;"><b style="color:#334155">格式</b>(顶点编号 1..n):<br>第一行:<code style="background:#fff;padding:1px 5px;border-radius:4px;color:#1d4ed8;">n m</code><br>随后 m 行,每行:<code style="background:#fff;padding:1px 5px;border-radius:4px;color:#1d4ed8;">u v</code> 或 <code style="background:#fff;padding:1px 5px;border-radius:4px;color:#1d4ed8;">u v w</code><br><b style="color:#334155">w 支持任意实数</b>;<b style="color:#dc2626">有向图支持负权</b>。<br><b style="color:#334155">支持自环与重边</b>(u=v 或同一对顶点多次出现)。<br><span style="color:#94a3b8">支持 # 开头的注释行。</span></div><textarea id="codeInput" class="code-area" spellcheck="false"placeholder="6 91 1 21 2 2.51 2 3.71 3 3.142 3 0.52 4 1.23 5 4.84 5 35 6 1.5"></textarea><div class="btn-row" style="margin-top:8px"><button class="btn" id="btnCodeSample">📄 示例</button><button class="btn" id="btnCodeClear">清空输入</button></div><button class="btn primary" id="btnCodeApply" style="margin-top:8px">▶ 应用代码 (Ctrl+Enter)</button><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">8 行未改动<section class="card"><h2>容量 / 边权</h2><label class="check"><input type="checkbox" id="chkCap"> 启用容量 / 边权(默认 1)</label><p class="hint">支持任意实数。<b>有向图可输入负权</b>(最短路会切换为 SPFA,能检测负环)。无向图负权会形成负环,因此禁止。</p></section><section class="card"><h2>物理引擎</h2><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>34 行未改动<div class="edge-popup" id="edgePopup"><div class="popup-header" id="popupHeader">边设置</div><div class="popup-row"><label>容量 / 边权</label><input type="number" id="popupCapInput" step="any" value="1"></div><div class="popup-actions"><button class="save" id="popupSave">保存</button><button class="delete" id="popupDelete">删除</button>6 行未改动<script>(() => {'use strict';const NODE_R = 20;const MAX_NODES = 60;const MAX_WEIGHT = 1e9;const LAYER_PALETTE = [{ fill:'#dbeafe', stroke:'#2563eb', text:'#1e40af' },{ fill:'#d1fae5', stroke:'#059669', text:'#065f46' },23 行未改动const selDst = document.getElementById('selDst');const edgePopup = document.getElementById('edgePopup');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 = [];let edges = []; // {id, a, b, cap}let nodeSeq = 1;let edgeSeq = 1;6 行未改动let capEnabled = false;let popupEdgeId = null;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,4 行未改动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;const clamp = (v, a, b) => Math.max(a, Math.min(b, v));const getNode = id => nodes.find(n => n.id === id);const idxOf = id => nodes.findIndex(n => n.id === id);const nameOf = id => { const i = idxOf(id); return i >= 0 ? `v${i + 1}` : '?'; };function fmtNum(v) {if (typeof v !== 'number' || !Number.isFinite(v)) return '?';if (Number.isInteger(v)) return String(v);const abs = Math.abs(v);if (abs !== 0 && (abs < 1e-3 || abs >= 1e6)) return v.toExponential(2);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;}function clearHighlight() { highlight = { nodeIds: new Set(), edgeIds: new Set() }; }function clearTopo() { topoColorMap = new Map(); }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);if (!groups.has(key)) groups.set(key, []);groups.get(key).push(e);}for (const [key, group] of groups) {if (group.length === 1) {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;const hasB = backward.length > 0;if (hasF && hasB) {forward.forEach((e, i) => edgeMeta.set(e.id, { offset: 28 + i * 30 }));backward.forEach((e, i) => edgeMeta.set(e.id, { offset: -28 - i * 30 }));} else {const list = hasF ? forward : backward;const total = list.length;list.forEach((e, i) => {edgeMeta.set(e.id, { offset: (i - (total - 1) / 2) * 30 });});}}}const selfGroups = new Map();for (const e of edges) {if (e.a !== e.b) continue;if (!selfGroups.has(e.a)) selfGroups.set(e.a, []);selfGroups.get(e.a).push(e);}for (const [nodeId, list] of selfGroups) {list.forEach((e, i) => {edgeMeta.set(e.id, { selfIdx: i, selfTotal: list.length, offset: 0 });});}}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;const r1 = NODE_R;const r2 = NODE_R + (directed ? 3 : 0);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;const edx = cx - B.x, edy = cy - B.y, ed = Math.hypot(edx, edy) || 1;const ex = B.x + edx / ed * r2, ey = B.y + edy / ed * r2;return `M ${sx} ${sy} Q ${cx} ${cy} ${ex} ${ey}`;}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 {path: `M ${sx} ${sy} Q ${ctrlX} ${ctrlY} ${ex} ${ey}`,midX: lx,midY: ly,endX: ex,endY: ey};}/* ============================================================* 弹窗* ============================================================ */function openPopup(edge, clientX, clientY) {popupEdgeId = edge.id;const ia = idxOf(edge.a), ib = idxOf(edge.b);if (edge.a === edge.b) {popupHeader.textContent = `自环 v${ia + 1} ↺`;} else {popupHeader.textContent = `边 v${ia + 1} ${directed ? '→' : '—'} v${ib + 1}`;}popupCapInput.value = fmtNum(edge.cap ?? 1);if (directed) popupCapInput.removeAttribute('min');else popupCapInput.setAttribute('min', '0');edgePopup.style.display = 'block';const stageRect = stage.getBoundingClientRect();let x = clientX - stageRect.left + 12;22 行未改动function savePopup() {if (popupEdgeId === null) return;const edge = edges.find(x => x.id === popupEdgeId);if (!edge) { closePopup(); return; }let v = parseFloat(popupCapInput.value);if (!Number.isFinite(v)) v = 1;if (!directed && v < 0) v = 0;v = Math.min(v, MAX_WEIGHT);v = Math.max(v, -MAX_WEIGHT);edge.cap = v;closePopup();clearAllVisual();refresh();}13 行未改动if (e.key === 'Enter') { e.preventDefault(); savePopup(); }else if (e.key === 'Escape') { e.preventDefault(); closePopup(); }});document.addEventListener('pointerdown', e => {if (edgePopup.style.display === 'block' && !edgePopup.contains(e.target)) {closePopup();}9 行未改动requestAnimationFrame(() => { rafPending = false; render(); });}function render() {computeEdgeMeta();const nmap = new Map(nodes.map(n => [n.id, n]));let html = `<defs>7 行未改动<marker id="arrowHot" 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="#f59e0b"/></marker><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);d = g.path;mid = { x: g.midX, y: g.midY };} else {d = edgePath(A, B, meta.offset || 0);mid = edgeMidpoint(A, B, meta.offset || 0);}edgeDraws.push({ e, d, mid });}for (const { e, d } of edgeDraws) {const hot = highlight.edgeIds.has(e.id);const hasFlow = flowHighlight.has(e.id);const isNeg = isNegEdge(e);let sw = 2;if (capEnabled) {const c = (typeof e.cap === 'number' && Number.isFinite(e.cap)) ? e.cap : 1;sw = Math.min(6, 2 + 0.35 * Math.max(0, Math.abs(c) - 1));}if (hot) sw = Math.max(sw, 3.2);let stroke = '#94a3b8';let marker = directed ? 'url(#arrow)' : '';if (hot) { stroke = '#f59e0b'; marker = directed ? 'url(#arrowHot)' : ''; }else if (isNeg) { stroke = '#dc2626'; marker = directed ? 'url(#arrowNeg)' : ''; }html += `<path d="${d}" fill="none" stroke="${stroke}" stroke-width="${sw}"stroke-linecap="round" pointer-events="none"${marker ? `marker-end="${marker}"` : ''}/>`;if (hasFlow) {html += `<path d="${d}" fill="none" stroke="rgba(59,130,246,0.35)"stroke-width="${sw + 4}" stroke-linecap="round" pointer-events="none"/>`;}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;if (py > 0) { px = -px; py = -py; }lx = mid.x + px * 15;ly = mid.y + py * 15;}}const bgFill = isNeg ? '#fef2f2' : '#ffffff';const bgStroke = isNeg ? '#fecaca' : '#bfdbfe';const txtFill = isNeg ? '#dc2626' : '#1d4ed8';html += `<g pointer-events="none"><rect x="${lx - bw / 2}" y="${ly - bh / 2}" width="${bw}" height="${bh}" rx="5"fill="${bgFill}" stroke="${bgStroke}" stroke-width="1"/><text x="${lx}" y="${ly}" text-anchor="middle" dominant-baseline="central"font-size="11" font-weight="700" fill="${txtFill}"font-family="ui-monospace,Menlo,monospace">${txt}</text></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);let dx, dy;if (info.dir === 'a→b') { dx = B.x - A.x; dy = B.y - A.y; }else { dx = A.x - B.x; dy = A.y - B.y; }16 行未改动stroke="rgba(37,99,235,0.95)" stroke-width="1.4"stroke-linejoin="round" pointer-events="none"/>`;if (info.amount > 1) {const numOffset = tipLen * 0.5 + 13;let numX = mid.x + ux * numOffset;let numY = mid.y + uy * numOffset;const distToTarget = Math.hypot(B.x - numX, B.y - numY);if (distToTarget < NODE_R + 14) {numX = mid.x - ux * numOffset;numY = mid.y - uy * numOffset;}const txt = fmtNum(info.amount);const bw = 12 + txt.length * 6.8;const bh = 16;html += `<g pointer-events="none"><rect x="${numX - bw / 2}" y="${numY - bh / 2}" width="${bw}" height="${bh}" rx="5"fill="rgba(255,255,255,0.94)" stroke="rgba(37,99,235,0.55)" stroke-width="1"/><text x="${numX}" y="${numY}" text-anchor="middle" dominant-baseline="central"font-size="10.5" font-weight="700" fill="#1d4ed8"font-family="ui-monospace,Menlo,monospace">${txt}</text></g>`;}}}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);const lc = topoColorMap.get(nd.id);let fill = '#ffffff', stroke = '#64748b', sw = 2, txt = '#0f172a';if (isPend) { fill = '#dbeafe'; stroke = '#2563eb'; sw = 2.5; }else if (isHot) { fill = '#fef3c7'; stroke = '#f59e0b'; sw = 2.8; }else if (lc) { fill = lc.fill; stroke = lc.stroke; sw = 2.6; txt = lc.text; }const cursor = mode === 'erase' ? 'pointer': mode === 'edge' ? 'crosshair': 'grab';70 行未改动for (let i = 0; i < nodes.length; i++) {const a = nodes[i];for (let j = i + 1; j < nodes.length; j++) {const b = nodes[j];let dx = b.x - a.x;let dy = b.y - a.y;let d = Math.hypot(dx, dy);if (d >= minD) continue;if (d < 0.001) {const ang = Math.random() * Math.PI * 2;dx = Math.cos(ang); dy = Math.sin(ang); d = 0.001;} else { dx /= d; dy /= d; }const overlap = minD - d;const aFix = (a === dragged) ? 0 : 1;const bFix = (b === dragged) ? 0 : 1;45 行未改动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) {adjU[a].push(a);adjU[a].push(a);adjOut[a].push(a);adjIn[a].push(a);outdeg[a]++;indeg[a]++;} else {adjU[a].push(b); adjU[b].push(a);adjOut[a].push(b); adjIn[b].push(a);outdeg[a]++; indeg[b]++;}}const degU = adjU.map(a => a.length);const seen = new Array(n).fill(false);7 行未改动for (const v of adjU[u]) if (!seen[v]) { seen[v] = true; stack.push(v); }}}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 = [];32 行未改动let isTree = false;if (n > 0) {if (!directed) {let hasMultiOrSelf = false;if (selfLoopCount > 0) hasMultiOrSelf = true;else {const pairSet = new Set();for (const e of edges) {if (e.a === e.b) { hasMultiOrSelf = true; break; }const k = e.a < e.b ? `${e.a}-${e.b}` : `${e.b}-${e.a}`;if (pairSet.has(k)) { hasMultiOrSelf = true; break; }pairSet.add(k);}}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;}}return {n, m, comps, weakConnected, stronglyConnected,hasCycle: directed ? cycleD : cycleU,isTree, indeg, outdeg, degU,selfLoopCount};}function renderAnalysis() {const r = analyze();if (r.n === 0) {analysisEl.innerHTML =`<p class="empty">画布为空。请设置顶点数后点击「随机生成」,或在代码模式中粘贴数据。</p>`;return;}const badge = (ok, yes, no) =>`<span class="badge ${ok ? 'yes' : 'no'}">${ok ? yes : no}</span>`;let html = `<div class="stats">12 行未改动html += `<li><span class="lbl">强连通</span><span class="rgt">${badge(r.stronglyConnected, '是', '否')}</span></li>`;html += `<li><span class="lbl">是否含环</span><span class="rgt">${badge(r.hasCycle, '有环', '无环')}</span></li>`;html += `<li><span class="lbl">是否为有向树</span><span class="rgt">${badge(r.isTree, '是 ✔', '否 ✘')}</span></li>`;}if (r.selfLoopCount > 0) {html += `<li><span class="lbl">自环数量</span><span class="rgt"><span class="badge no">${r.selfLoopCount}</span></span></li>`;}html += `</ul>`;html += `<p class="deg-title">${directed ? '各顶点入度 / 出度' : '各顶点度数'}</p><div class="deg-list">`;nodes.forEach((nd, i) => {3 行未改动html += `<span class="deg">v${i + 1} : ${r.degU[i]}</span>`;}});html += `</div>`;analysisEl.innerHTML = html;}function refreshSelectors() {const oldSrc = selSrc.value;const oldDst = selDst.value;const opts = nodes.map((nd, i) => `<option value="${nd.id}">v${i + 1}</option>`).join('');selSrc.innerHTML = opts || '<option value="">—</option>';selDst.innerHTML = opts || '<option value="">—</option>';const hasSrc = nodes.some(nd => String(nd.id) === oldSrc);selSrc.value = hasSrc ? oldSrc : (nodes.length ? String(nodes[0].id) : '');const hasDst = nodes.some(nd => String(nd.id) === oldDst);if (hasDst) selDst.value = oldDst;else if (nodes.length > 1) selDst.value = String(nodes[nodes.length - 1].id);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;7 行未改动tagEl.innerHTML = tagText;refreshSelectors();renderAnalysis();updateExport();}function refresh() {render();updateUI();}/* ============================================================* 布局* ============================================================ */function layoutCircle() {const n = nodes.length;if (n === 0) return;7 行未改动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) {if (e.a === e.b) continue;adj.get(e.a).push(e.b);adj.get(e.b).push(e.a);}function bfs(start) {const dist = new Map([[start, 0]]);const parent = new Map([[start, null]]);const queue = [start];10 行未改动}}return { last, parent };}const start = nodes[0].id;const r1 = bfs(start);const r2 = bfs(r1.last);let cur = r2.last;const path = [cur];while (cur !== r1.last) {cur = r2.parent.get(cur);6 行未改动function computeTreeLayout(rootId) {const adj = new Map();for (const nd of nodes) adj.set(nd.id, []);for (const e of edges) {if (e.a === e.b) continue;if (directed) adj.get(e.a).push(e.b);else { adj.get(e.a).push(e.b); adj.get(e.b).push(e.a); }}const children = new Map();const visited = new Set([rootId]);const depth = new Map([[rootId, 0]]);const queue = [rootId];while (queue.length) {const u = queue.shift();const kids = [];for (const v of adj.get(u) || []) {5 行未改动}}children.set(u, kids);}const xs = new Map();let cursor = 0;function place(id) {const kids = children.get(id) || [];if (kids.length === 0) { const x = cursor; cursor += 1; xs.set(id, x); return x; }let sum = 0;for (const c of kids) sum += place(c);const x = sum / kids.length;xs.set(id, x);return x;}place(rootId);return { xs, depth, numLeaves: cursor };}function applyTreeLayout(rootId) {const { xs, depth, numLeaves } = computeTreeLayout(rootId);let maxDepth = 0;for (const d of depth.values()) maxDepth = Math.max(maxDepth, d);const paddingX = 60, paddingY = 70;const availW = Math.max(1, W - paddingX * 2);const availH = Math.max(1, H - paddingY * 2 - NODE_R);const spacingX = numLeaves <= 1 ? 0 : Math.min(160, availW / (numLeaves - 1));const spacingY = maxDepth <= 0 ? 0 : Math.min(130, availH / maxDepth);const totalW = (numLeaves - 1) * spacingX;const offsetX = (W - totalW) / 2;const offsetY = paddingY;for (const nd of nodes) {const x = xs.get(nd.id);const d = depth.get(nd.id);if (x === undefined || d === undefined) continue;6 行未改动function applyLayeredLayout() {const adj = new Map();for (const nd of nodes) adj.set(nd.id, []);for (const e of edges) {if (e.a === e.b) continue;adj.get(e.a).push(e.b);adj.get(e.b).push(e.a);}const level = new Map();const sorted = [...nodes].sort((a, b) =>(adj.get(b.id) || []).length - (adj.get(a.id) || []).length);for (const startNode of sorted) {if (level.has(startNode.id)) continue;level.set(startNode.id, 0);const queue = [startNode.id];while (queue.length) {const u = queue.shift();for (const v of adj.get(u) || []) {if (!level.has(v)) { level.set(v, level.get(u) + 1); queue.push(v); }}}}let maxLevel = 0;for (const l of level.values()) maxLevel = Math.max(maxLevel, l);const byLevel = new Map();for (const nd of nodes) {const l = level.get(nd.id) || 0;if (!byLevel.has(l)) byLevel.set(l, []);byLevel.get(l).push(nd.id);}const paddingX = 60, paddingY = 70;const availW = Math.max(1, W - paddingX * 2);const availH = Math.max(1, H - paddingY * 2 - NODE_R);const numLevels = maxLevel + 1;const spacingY = numLevels <= 1 ? 0 : Math.min(130, availH / (numLevels - 1));for (const [l, ids] of byLevel) {const spacingX = ids.length <= 1 ? 0 : Math.min(160, availW / (ids.length - 1));const totalW = (ids.length - 1) * spacingX;const startX = (W - totalW) / 2;9 行未改动}function tidyLayout() {if (nodes.length === 0) return;const r = analyze();if (r.isTree) {let rootId;if (directed) {const indeg = new Map();nodes.forEach(nd => indeg.set(nd.id, 0));for (const e of edges) {if (e.a === e.b) continue;indeg.set(e.b, indeg.get(e.b) + 1);}for (const [id, d] of indeg) if (d === 0) { rootId = id; break; }} else {rootId = findTreeCentroid();}if (rootId !== undefined) applyTreeLayout(rootId);} else {applyLayeredLayout();}nodes.forEach(nd => { nd.vx = 0; nd.vy = 0; });refresh();}/* ============================================================* 图算法核心* ============================================================ */function topoSort() {if (!directed) return { ok: false, msg: '拓扑排序仅适用于有向图。' };const n = nodes.length;if (n === 0) return { ok: false, msg: '画布为空,请先添加顶点。' };const idx = new Map();13 行未改动current.sort((x, y) => x - y);const levels = [];let processed = 0;while (current.length) {levels.push(current);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);current = next;}if (processed < n) return { ok: false, msg: '图中存在环(或有自环),不存在拓扑排序。' };return { ok: true, levels };}function buildAdj() {const n = nodes.length;const idx = new Map();nodes.forEach((nd, i) => idx.set(nd.id, i));const adj = Array.from({ length: n }, () => []);for (const e of edges) {const a = idx.get(e.a), b = idx.get(e.b);if (a === undefined || b === undefined) continue;const w = edgeCap(e);adj[a].push([b, w]);if (!directed) adj[b].push([a, w]);}return { n, idx, adj };}function shortestPath(sId, tId) {const { n, idx, adj } = buildAdj();const S = idx.get(sId), T = idx.get(tId);if (S === undefined || T === undefined) return null;if (S === T) return { dist: 0, path: [S] };if (directed) return spfa(adj, S, T, n);return dijkstra(adj, S, T, n);}function dijkstra(adj, S, T, n) {const dist = new Array(n).fill(Infinity);const parent = new Array(n).fill(-1);const visited = new Array(n).fill(false);dist[S] = 0;5 行未改动}if (u === -1) break;visited[u] = true;if (u === T) break;for (const [v, w] of adj[u]) {if (!visited[v] && dist[u] + w < dist[v]) {dist[v] = dist[u] + w;parent[v] = u;}}}if (dist[T] === Infinity) return { dist: Infinity, path: null };const path = [];let v = T;while (v !== -1) { path.unshift(v); if (v === S) break; v = parent[v]; }return { dist: dist[T], path };}function spfa(adj, S, T, n) {const dist = new Array(n).fill(Infinity);const parent = new Array(n).fill(-1);const inQueue = new Array(n).fill(false);const enqueueCnt = new Array(n).fill(0);dist[S] = 0;const q = [S];inQueue[S] = true;enqueueCnt[S] = 1;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]) {q.push(v);inQueue[v] = true;enqueueCnt[v]++;if (enqueueCnt[v] > n) return { negativeCycle: true };}}}}if (dist[T] === Infinity) return { dist: Infinity, path: null };const path = [];let v = T;const guard = new Set();while (v !== -1) {path.unshift(v);if (v === S) break;if (guard.has(v)) break;guard.add(v);v = parent[v];}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; }}const origCap = cap.map(r => r.slice());const S = idx.get(sId), T = idx.get(tId);if (S === undefined || T === undefined) return null;if (S === T) return { value: 0, flowMap: new Map() };let flow = 0;const INF = 1e18;const EPS = 1e-9;let safety = 0;while (safety++ < 5000) {const parent = new Array(n).fill(-1);parent[S] = S;const q = [S];while (q.length && parent[T] === -1) {const u = q.shift();for (let v = 0; v < n; v++) {if (parent[v] === -1 && cap[u][v] > EPS) {parent[v] = u;q.push(v);}}6 行未改动const u = parent[v];bottleneck = Math.min(bottleneck, cap[u][v]);v = u;}if (bottleneck <= EPS) break;v = T;while (v !== S) {const u = parent[v];cap[u][v] -= bottleneck;cap[v][u] += bottleneck;v = u;}flow += bottleneck;}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;if (netAB > 0) flowMap.set(e.id, { dir: 'a→b', amount: netAB });else flowMap.set(e.id, { dir: 'b→a', amount: -netAB });}return { value: flow, flowMap };}8 行未改动}function showTopo() {const r = topoSort();if (!r.ok) {algoResult.innerHTML = `<span class="err">${r.msg}</span>`;clearTopo(); clearFlow();render();return;}topoColorMap = new Map();r.levels.forEach((level, li) => {const pal = LAYER_PALETTE[li % LAYER_PALETTE.length];for (const ni of level) {topoColorMap.set(nodes[ni].id, { ...pal, layer: li + 1 });}});let html = `<b>拓扑排序(共 ${r.levels.length} 层)</b>`;r.levels.forEach((level, li) => {const pal = LAYER_PALETTE[li % LAYER_PALETTE.length];const chips = level.map(ni =>`<span class="chip" style="background:${pal.fill};color:${pal.text};border-color:${pal.stroke}">v${ni + 1}</span>`).join('');html += `<div class="topo-level"><span class="lv-tag" style="background:${pal.stroke}">第 ${li + 1} 层</span><span class="lv-nodes">${chips}</span></div>`;});html += `<div class="topo-note">同层顶点互不可达;层号越靠前越先被处理。</div>`;algoResult.innerHTML = html;clearHighlight(); clearFlow();render();}function showPath() {11 行未改动if (!r) { algoResult.innerHTML = '<span class="err">选择的顶点无效。</span>'; return; }const sName = nameOf(sel.s), dName = nameOf(sel.d);if (r.negativeCycle) {algoResult.innerHTML =`<b>${sName} → ${dName}</b><br>` +`<span class="neg">检测到负环:最短路径无定义(−∞)</span>` +`<br><span style="font-size:11.5px;color:#94a3b8">SPFA 检测到源点可达的负环,请修改边权或图结构。</span>`;clearHighlight();render();return;}if (r.dist === Infinity) {algoResult.innerHTML =`${sName} → ${dName} 的最短路:<span class="inf">INF</span>(不可达)`;clearHighlight();5 行未改动const edgeIds = new Set();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)) {const w = edgeCap(e);if (w < bestW) { bestW = w; best = e; }}}if (best) edgeIds.add(best.id);}highlight = { nodeIds, edgeIds };const pathStr = r.path.map(i => `<span class="seq">v${i + 1}</span>`).join('<span class="arrow">→</span>');const distClass = r.dist < 0 ? 'neg' : 'k';const algoName = directed ? 'SPFA' : 'Dijkstra';let distLabel;if (capEnabled) {distLabel = `最短路径权重:<span class="${distClass}">${fmtNum(r.dist)}</span>` +` <span style="color:#94a3b8;font-size:11px">(${algoName})</span>`;} else {distLabel = `最短路长度:<span class="k">${r.dist}</span> 条边`;}algoResult.innerHTML =`<b>${sName} → ${dName}</b><br>${distLabel}<br>路径:${pathStr}`;render();}17 行未改动clearFlow(); render(); return;}flowHighlight = result.flowMap;const sName = nameOf(sel.s), dName = nameOf(sel.d);const usedEdges = flowHighlight.size;let extra = '';if (!directed) extra += '<br><span style="color:#94a3b8;font-size:11.5px">(无向边双向容量各 = 边容量)</span>';if (capEnabled) extra += '<br><span style="color:#94a3b8;font-size:11.5px">(按自定义实数容量计算;负容量边与自环忽略)</span>';else extra += '<br><span style="color:#94a3b8;font-size:11.5px">(所有边容量 = 1)</span>';let flowInfo;if (usedEdges > 0) {4 行未改动}algoResult.innerHTML =`<b>${sName} → ${dName}</b><br>` +`最大流:<span class="k">${fmtNum(result.value)}</span> 单位${extra}${flowInfo}`;render();}/* ============================================================* 增删* ============================================================ */function setNodeCount(target) {target = clamp(target, 0, MAX_NODES);while (nodes.length < target) {let best = { x: W / 2, y: H / 2 }, bestD = -1;for (let t = 0; t < 24; t++) {const x = NODE_R + 24 + Math.random() * Math.max(1, W - 2 * NODE_R - 48);3 行未改动if (d > bestD) { bestD = d; best = { x, y }; }}nodes.push({ id: nodeSeq++, x: best.x, y: best.y, vx: 0, vy: 0 });}while (nodes.length > target) {const nd = nodes.pop();edges = edges.filter(e => e.a !== nd.id && e.b !== nd.id);}if (pending !== null && !nodes.some(n => n.id === pending)) pending = null;clearAllVisual();refresh();}function setEdgeCount(target) {const n = nodes.length;const maxE = directed ? n * (n - 1) : n * (n - 1) / 2;target = clamp(target, 0, maxE);if (target > edges.length) {const pool = [];for (let i = 0; i < n; i++) {for (let j = i + 1; j < n; j++) {const a = nodes[i].id, b = nodes[j].id;const key = a < b ? `${a}-${b}` : `${b}-${a}`;const has = edges.some(e => {if (e.a === e.b) return false;const k = e.a < e.b ? `${e.a}-${e.b}` : `${e.b}-${e.a}`;return k === key;});if (!has) pool.push([a, b]);if (directed && !edges.some(e => e.a === a && e.b === b)) pool.push([a, b]);}}shuffle(pool);for (const [a, b] of pool) {if (edges.length >= target) break;edges.push({ id: edgeSeq++, a, b, cap: 1 });}} else if (target < edges.length) {const shuffled = shuffle(edges.slice());const keep = new Set(shuffled.slice(0, target).map(e => e.id));25 行未改动numNodesEl.value = n;const wantTree = chkTree.checked;const wantConn = chkConn.checked;const maxE = directed ? n * (n - 1) : n * (n - 1) / 2;const m = wantTree? Math.max(0, n - 1): clamp(parseInt(numEdgesEl.value, 10) || 0, 0, maxE);11 行未改动edgeSeq = 1;const used = new Set();const keyOf = (a, b) =>directed ? `${a}>${b}` : (a < b ? `${a}-${b}` : `${b}-${a}`);const addE = (a, b) => {if (a === b || a === undefined || b === undefined) return false;const k = keyOf(a, b);if (used.has(k)) return false;used.add(k);edges.push({ id: edgeSeq++, a, b, cap: 1 });return true;};const ids = nodes.map(nd => nd.id);if (n > 1 && (wantTree || (wantConn && m >= n - 1))) {const perm = shuffle(ids.slice());for (let i = 1; i < n; i++) {const p = Math.floor(Math.random() * i);const a = perm[p], b = perm[i];if (directed && !wantTree) {if (Math.random() < 0.5) addE(a, b); else addE(b, a);} else addE(a, b);}}if (!wantTree) {const pool = [];for (let i = 0; i < n; i++) {for (let j = i + 1; j < n; j++) {15 行未改动wake();}/* ============================================================* 代码模式解析* ============================================================ */function parseCode(text) {const lines = text.split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#'));if (lines.length === 0) throw new Error('输入为空');const firstParts = lines[0].split(/\s+/);if (firstParts.length < 2) throw new Error('第一行必须是 "n m" 格式');const n = parseInt(firstParts[0], 10);const m = parseInt(firstParts[1], 10);if (!Number.isInteger(n) || !Number.isInteger(m)) throw new Error('n 和 m 必须是整数');if (n < 0 || n > MAX_NODES) throw new Error(`顶点数必须在 0-${MAX_NODES} 之间`);if (m < 0) throw new Error('边数不能为负');if (lines.length - 1 < m) {throw new Error(`需要 ${m} 行边数据,但只找到 ${lines.length - 1} 行`);}let weighted = false;let hasNegative = false;let selfLoopCount = 0;const parsedEdges = [];for (let i = 0; i < m; i++) {const lineNum = i + 2;const parts = lines[i + 1].split(/\s+/);if (parts.length < 2) throw new Error(`第 ${lineNum} 行格式错误:至少需要两个整数`);const u = parseInt(parts[0], 10);const v = parseInt(parts[1], 10);if (!Number.isInteger(u) || !Number.isInteger(v)) {throw new Error(`第 ${lineNum} 行顶点编号必须是整数`);}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]);if (!Number.isFinite(w)) {throw new Error(`第 ${lineNum} 行边权必须是有效数字`);}if (w < 0) {if (!directed) {throw new Error(`第 ${lineNum} 行:无向图不支持负权边(会形成负环)`);}if (w < -MAX_WEIGHT) {throw new Error(`第 ${lineNum} 行边权不能小于 -${MAX_WEIGHT}`);}hasNegative = true;} else if (w > MAX_WEIGHT) {throw new Error(`第 ${lineNum} 行边权不能超过 ${MAX_WEIGHT}`);}weighted = true;}if (u === v) selfLoopCount++;parsedEdges.push({ u, v, w });}return { n, m, weighted, hasNegative, selfLoopCount, edges: parsedEdges };}function applyCode() {try {const data = parseCode(codeInput.value);nodes = []; edges = []; nodeSeq = 1; edgeSeq = 1;for (let i = 0; i < data.n; i++) {nodes.push({ id: nodeSeq++, x: 0, y: 0, vx: 0, vy: 0 });}layoutCircle();for (const e of data.edges) {edges.push({ id: edgeSeq++, a: e.u, b: e.v, cap: e.w });}if (data.weighted && !capEnabled) {capEnabled = true;chkCap.checked = true;}clearAllVisual();pending = null;if (nodes.length > 0) {tidyLayout();wake();} else {refresh();}codeStatus.className = 'code-status ok';let msg = `✓ 已加载:${data.n} 个顶点,${data.m} 条边`;if (data.weighted) msg += '(带实数权,容量已启用)';if (data.hasNegative) msg += ' · 含负权';if (data.selfLoopCount > 0) msg += ` · ${data.selfLoopCount} 个自环`;msg += directed ? ' · 有向' : ' · 无向';codeStatus.textContent = msg;} catch (err) {codeStatus.className = 'code-status err';codeStatus.textContent = '✗ ' + err.message;}}function loadCodeSample() {const sampleDirected = `7 111 1 1.51 2 5.51 2 -2.12 3 2.43 4 3.34 4 0.84 5 2.45 6 5.15 7 -2.86 7 4.92 4 1.2`;const sampleUndirected = `6 91 1 2.51 2 3.51 2 1.82 3 2.23 4 4.13 4 0.74 5 1.75 6 2.32 5 3.9`;codeInput.value = directed ? sampleDirected : sampleUndirected;codeStatus.className = 'code-status';codeStatus.textContent = '';}document.getElementById('btnCodeApply').addEventListener('click', applyCode);document.getElementById('btnCodeSample').addEventListener('click', loadCodeSample);document.getElementById('btnCodeClear').addEventListener('click', () => {codeInput.value = '';codeStatus.className = 'code-status';codeStatus.textContent = '';codeInput.focus();});codeInput.addEventListener('keydown', e => {if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {e.preventDefault();applyCode();}});/* ============================================================* 指针交互* ============================================================ */svg.addEventListener('pointerdown', e => {if (e.pointerType === 'mouse' && e.button !== 0) return;16 行未改动} 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();}hoverPt = pt;refresh();23 行未改动const nx = clamp(pt.x - drag.ox, NODE_R + 4, W - NODE_R - 4);const ny = clamp(pt.y - drag.oy, NODE_R + 4, H - NODE_R - 4);if (physicsEnabled) {let vx = nx - nd.x, vy = ny - nd.y;const sp = Math.hypot(vx, vy);if (sp > PHYS.maxSpeed) {vx = vx / sp * PHYS.maxSpeed;vy = vy / sp * PHYS.maxSpeed;}nd.vx = vx; nd.vy = vy;nd.x = nx; nd.y = ny;wake();} else {nd.x = nx; nd.y = ny;nd.vx = 0; nd.vy = 0;scheduleRender();}return;10 行未改动drag = null;if (physicsEnabled) wake();else updateUI();}if (blankDown) {const pt = svgPoint(e);if (Math.hypot(pt.x - blankDown.x, pt.y - blankDown.y) < 6) {if (nodes.length < MAX_NODES) {14 行未改动});window.addEventListener('pointercancel', () => { drag = null; blankDown = null; });svg.addEventListener('contextmenu', e => {e.preventDefault();if (!capEnabled) return;const edgeEl = e.target.closest ? e.target.closest('[data-edge]') : null;if (!edgeEl) { closePopup(); return; }const edgeId = Number(edgeEl.dataset.edge);const edge = edges.find(x => x.id === edgeId);if (!edge) return;openPopup(edge, e.clientX, e.clientY);});/* ============================================================4 行未改动if (!btn) return;document.querySelectorAll('#typeSeg .seg-btn').forEach(b => b.classList.remove('active'));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;}}if (fixed) {algoResult.innerHTML = '<span class="err">切换到无向图后,原有的负权边已被置为 0。</span>';}}pending = null;clearAllVisual();refresh();});const HINTS = {drag: '拖动顶点调整位置;在空白处单击可新增顶点。松手后顶点会带有惯性并相互弹开。',edge: '依次点击两个顶点添加边;再次点击同一点可添加自环。允许重边(多次点击同一对顶点)。',erase: '点击顶点或边将其删除(删除顶点会同时删除其所有连边)。'};document.getElementById('modeSeg').addEventListener('click', e => {const btn = e.target.closest('.seg-btn');7 行未改动});chkPhysics.addEventListener('change', () => {physicsEnabled = chkPhysics.checked;if (physicsEnabled) wake();else {nodes.forEach(nd => { nd.vx = 0; nd.vy = 0; });updateUI();}updateUI();82 行未改动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 行未改动