跳到正文

科技·工程

图-查看器

WightyIflia约 143 分钟
原文

这是 2026年10月2日 存档的第 3 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年10月1日
收录
2026年10月1日
更新
2026年11月28日
篇幅
约 143 分钟
获赞
1

版本

  1. v6当前
  2. v5
  3. v4
  4. v3
更早的 2 个版本
  1. v2
  2. v1
HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>图论可视化 · 2D + 图算法 + 代码模式</title>
<style>
  :root{
    --bg:#f1f5f9; --border:#e2e8f0;
    --text:#0f172a; --muted:#64748b; --primary:#2563eb;
  }
  *{box-sizing:border-box;}
  html,body{height:100%;margin:0;}
  body{
    font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;
    background:var(--bg); color:var(--text); overflow:hidden;
    -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{
    content:"";width:8px;height:20px;border-radius:4px;
    background:linear-gradient(180deg,#2563eb,#38bdf8);
  }
  .card{background:#f8fafc;border:1px solid var(--border);border-radius:12px;padding:12px;}
  .card h2{
    font-size:11px;text-transform:uppercase;letter-spacing:.1em;color:var(--muted);
    margin:0 0 10px;font-weight:700;
  }

  /* details 折叠卡片 */
  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;
  }
  .seg-btn:hover{color:#1e293b;}
  .seg-btn.active{background:#fff;color:var(--primary);box-shadow:0 1px 3px rgba(15,23,42,.13);font-weight:600;}

  .row{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px;font-size:13px;color:#334155;}
  .row input[type=number]{
    width:86px;padding:6px 9px;border:1px solid #cbd5e1;border-radius:7px;
    font-size:13px;font-family:inherit;text-align:right;background:#fff;color:var(--text);
    outline:none;transition:.15s;
  }
  .row input[type=number]:focus{border-color:var(--primary);box-shadow:0 0 0 3px rgba(37,99,235,.12);}
  .row input:disabled{background:#eef2f7;color:#94a3b8;}
  .row select{
    flex:1;min-width:0;padding:6px 8px;border:1px solid #cbd5e1;border-radius:7px;
    font-size:13px;font-family:inherit;background:#fff;color:var(--text);
    outline:none;cursor:pointer;transition:.15s;
  }
  .row select:focus{border-color:var(--primary);box-shadow:0 0 0 3px rgba(37,99,235,.12);}

  .check{display:flex;align-items:center;gap:8px;font-size:13px;color:#334155;margin:7px 0;cursor:pointer;user-select:none;}
  .check input{width:15px;height:15px;accent-color:var(--primary);cursor:pointer;}

  .btn{
    width:100%;padding:9px 10px;border-radius:9px;border:1px solid #cbd5e1;background:#fff;
    color:#334155;font-size:13px;font-family:inherit;cursor:pointer;font-weight:500;transition:.15s;
  }
  .btn:hover{background:#f1f5f9;}
  .btn:active{transform:translateY(1px);}
  .btn + .btn{margin-top:7px;}
  .btn.primary{background:var(--primary);border-color:var(--primary);color:#fff;font-weight:600;margin-top:4px;}
  .btn.primary:hover{background:#1d4ed8;}
  .btn.danger{color:#dc2626;border-color:#fecaca;}
  .btn.danger:hover{background:#fef2f2;}
  .btn-row{display:flex;gap:8px;}
  .btn-row .btn{margin-top:0;}

  .hint{font-size:12px;color:var(--muted);line-height:1.6;margin:9px 0 0;}

  /* 代码输入 */
  .code-area{
    width:100%;min-height:180px;padding:10px 12px;margin-top:8px;
    border:1px solid #cbd5e1;border-radius:9px;background:#0f172a;color:#e2e8f0;
    font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
    font-size:12.5px;line-height:1.6;outline:none;resize:vertical;
    transition:.15s;
  }
  .code-area:focus{border-color:var(--primary);box-shadow:0 0 0 3px rgba(37,99,235,.15);}
  .code-status{font-size:12px;margin-top:8px;line-height:1.5;min-height:17px;color:var(--muted);}
  .code-status.err{color:#b91c1c;font-weight:600;}
  .code-status.ok{color:#15803d;font-weight:600;}

  /* ================= 分析 ================= */
  .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;}
  .facts{list-style:none;padding:0;margin:0 0 10px;display:flex;flex-direction:column;gap:6px;font-size:13px;}
  .facts li{
    display:flex;align-items:center;justify-content:space-between;gap:8px;
    background:#fff;border:1px solid var(--border);border-radius:8px;padding:7px 10px;
  }
  .facts li .lbl{color:#334155;}
  .facts li .rgt{display:flex;align-items:center;gap:6px;color:var(--muted);font-size:11.5px;}
  .badge{font-size:12px;padding:2px 9px;border-radius:999px;font-weight:600;white-space:nowrap;}
  .badge.yes{background:#dcfce7;color:#15803d;}
  .badge.no{background:#fee2e2;color:#b91c1c;}
  .deg-title{font-size:11px;color:var(--muted);margin:0 0 6px;letter-spacing:.05em;}
  .deg-list{display:flex;flex-wrap:wrap;gap:5px;}
  .deg{
    font-size:11.5px;background:#fff;border:1px solid var(--border);border-radius:6px;
    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;
  }
  .algo-result .arrow{color:#94a3b8;margin:0 3px;}
  .algo-result .flow-legend{
    display:inline-flex;align-items:center;gap:5px;
    font-size:11.5px;color:#1e40af;background:#eff6ff;
    border-radius:6px;padding:2px 8px;margin-top:6px;
  }
  .algo-result .flow-legend::before{
    content:"";display:inline-block;width:0;height:0;
    border-left:8px solid rgba(37,99,235,.9);
    border-top:5px solid transparent;border-bottom:5px solid transparent;
  }

  .topo-level{display:flex;align-items:flex-start;gap:8px;margin-top:8px;}
  .lv-tag{
    font-size:10.5px;color:#fff;padding:3px 8px;border-radius:6px;
    white-space:nowrap;font-weight:700;letter-spacing:.02em;flex:0 0 auto;
  }
  .lv-nodes{display:flex;flex-wrap:wrap;gap:4px;padding-top:1px;}
  .chip{
    font-size:11.5px;font-family:ui-monospace,Menlo,monospace;
    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;
    display:flex;align-items:center;gap:6px;
  }
  .edge-popup .popup-header::before{
    content:"";display:inline-block;width:4px;height:12px;border-radius:2px;
    background:linear-gradient(180deg,#2563eb,#38bdf8);
  }
  .edge-popup .popup-row{
    display:flex;align-items:center;gap:8px;margin-bottom:10px;
  }
  .edge-popup .popup-row label{
    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);
  }
  .edge-popup .popup-actions{display:flex;gap:6px;}
  .edge-popup .popup-actions button{
    flex:1;padding:6px 8px;border-radius:7px;border:1px solid #cbd5e1;
    background:#fff;font-size:12px;font-family:inherit;cursor:pointer;
    font-weight:500;transition:.15s;color:#334155;
  }
  .edge-popup .popup-actions button:hover{background:#f1f5f9;}
  .edge-popup .popup-actions button.save{
    background:#2563eb;border-color:#2563eb;color:#fff;font-weight:600;
  }
  .edge-popup .popup-actions button.save:hover{background:#1d4ed8;}
  .edge-popup .popup-actions button.delete{
    color:#dc2626;border-color:#fecaca;
  }
  .edge-popup .popup-actions button.delete:hover{background:#fef2f2;}
</style>
</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>
          若存在 w 则自动启用容量 / 边权。<br>
          <span style="color:#94a3b8">支持 # 开头的注释行。</span>
        </div>
        <textarea id="codeInput" class="code-area" spellcheck="false"
placeholder="6 8
1 2 4
1 3 3
2 3 1
2 4 2
3 5 6
4 5 3
4 6 2
5 6 4"></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>

    <section class="card">
      <h2>参数</h2>
      <label class="row"><span>顶点数 n</span>
        <input type="number" id="numNodes" min="0" max="60" value="7" step="1">
      </label>
      <label class="row"><span>边数 m</span>
        <input type="number" id="numEdges" min="0" max="30" value="9" step="1">
      </label>
      <label class="check"><input type="checkbox" id="chkTree"> 生成树(连通无环,m = n−1)</label>
      <label class="check"><input type="checkbox" id="chkConn" checked> 保证连通</label>
      <button class="btn primary" id="btnRandom">🎲 随机生成</button>
    </section>

    <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>
        <button class="seg-btn" data-mode="edge">连边</button>
        <button class="seg-btn" data-mode="erase">删除</button>
      </div>
      <p class="hint" id="modeHint">拖动顶点调整位置;在空白处单击可新增顶点。松手后顶点会带有惯性并相互弹开。</p>
      <div class="btn-row">
        <button class="btn" id="btnLayout">圆形</button>
        <button class="btn" id="btnTidy">📐 整理</button>
      </div>
      <button class="btn danger" id="btnClear" style="margin-top:8px">清空</button>
    </section>

    <section class="card">
      <h2>图算法</h2>
      <button class="btn" id="btnTopo">拓扑排序(分层着色)</button>
      <label class="row" style="margin-top:9px"><span>起点 / 源点</span>
        <select id="selSrc"></select>
      </label>
      <label class="row"><span>终点 / 汇点</span>
        <select id="selDst"></select>
      </label>
      <button class="btn" id="btnPath">🔍 计算最短路</button>
      <button class="btn" id="btnFlow">💧 计算最大流</button>
      <div class="algo-result" id="algoResult">选择两个顶点后,可计算它们之间的最短路与最大流。</div>
    </section>

    <section class="card">
      <h2>分析结果</h2>
      <div id="analysis"></div>
    </section>
  </aside>

  <main class="stage" id="stage">
    <svg id="canvas"></svg>
    <div class="tag" id="tag">无向图</div>
    <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>
        <button id="popupCancel">取消</button>
      </div>
    </div>
  </main>
</div>

<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' },
    { fill:'#fef3c7', stroke:'#d97706', text:'#92400e' },
    { fill:'#fce7f3', stroke:'#db2777', text:'#9d174d' },
    { fill:'#ede9fe', stroke:'#7c3aed', text:'#5b21b6' },
    { fill:'#cffafe', stroke:'#0891b2', text:'#155e75' },
    { fill:'#ffedd5', stroke:'#ea580c', text:'#9a3412' },
    { fill:'#ecfccb', stroke:'#65a30d', text:'#3f6212' },
    { fill:'#fee2e2', stroke:'#dc2626', text:'#991b1b' },
    { fill:'#e0e7ff', stroke:'#4f46e5', text:'#3730a3' },
  ];

  const svg        = document.getElementById('canvas');
  const stage      = document.getElementById('stage');
  const tagEl      = document.getElementById('tag');
  const numNodesEl = document.getElementById('numNodes');
  const numEdgesEl = document.getElementById('numEdges');
  const chkTree    = document.getElementById('chkTree');
  const chkConn    = document.getElementById('chkConn');
  const chkPhysics = document.getElementById('chkPhysics');
  const chkCap     = document.getElementById('chkCap');
  const analysisEl = document.getElementById('analysis');
  const modeHint   = document.getElementById('modeHint');
  const algoResult = document.getElementById('algoResult');
  const selSrc     = document.getElementById('selSrc');
  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');

  let W = 900, H = 650;

  let nodes = [];      // {id, x, y, vx, vy}
  let edges = [];      // {id, a, b, cap}
  let nodeSeq = 1;
  let edgeSeq = 1;

  let directed = false;
  let mode = 'drag';
  let pending = null;
  let hoverPt = null;
  let drag = null;
  let blankDown = null;

  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,
    wallBounce:  0.62,
    correction:  0.85,
    dragDrag:    0.88,
    maxSpeed:    46,
    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]];
    }
    return arr;
  }

  function svgPoint(e) {
    const r = svg.getBoundingClientRect();
    return {
      x: (e.clientX - r.left) * (W / (r.width  || W)),
      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));
  }

  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;
    let y = clientY - stageRect.top + 12;

    const pw = edgePopup.offsetWidth;
    const ph = edgePopup.offsetHeight;

    if (x + pw > stageRect.width - 8) x = stageRect.width - pw - 8;
    if (y + ph > stageRect.height - 8) y = stageRect.height - ph - 8;
    if (x < 8) x = 8;
    if (y < 8) y = 8;

    edgePopup.style.left = x + 'px';
    edgePopup.style.top  = y + 'px';

    popupCapInput.focus();
    popupCapInput.select();
  }

  function closePopup() {
    popupEdgeId = null;
    edgePopup.style.display = 'none';
  }

  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();
  }

  function deletePopupEdge() {
    if (popupEdgeId === null) return;
    const id = popupEdgeId;
    closePopup();
    removeEdge(id);
  }

  document.getElementById('popupSave').addEventListener('click', savePopup);
  document.getElementById('popupDelete').addEventListener('click', deletePopupEdge);
  document.getElementById('popupCancel').addEventListener('click', closePopup);

  popupCapInput.addEventListener('keydown', e => {
    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();
    }
  }, true);

  /* ============================================================
   *  渲染
   * ============================================================ */
  let rafPending = false;
  function scheduleRender() {
    if (rafPending) return;
    rafPending = true;
    requestAnimationFrame(() => { rafPending = false; render(); });
  }

  function render() {
    const nmap = new Map(nodes.map(n => [n.id, n]));

    let html = `
      <defs>
        <pattern id="grid" width="26" height="26" patternUnits="userSpaceOnUse">
          <path d="M 26 0 L 0 0 0 26" fill="none" stroke="#e8eef6" stroke-width="1"/>
        </pattern>
        <marker id="arrow" 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="#94a3b8"/>
        </marker>
        <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; }
        const dd = Math.hypot(dx, dy) || 1;
        const ux = dx / dd, uy = dy / dd;

        const tipLen = 14, wingLen = 11;
        const tipX = mid.x + ux * tipLen * 0.5;
        const tipY = mid.y + uy * tipLen * 0.5;
        const baseX = mid.x - ux * tipLen * 0.5;
        const baseY = mid.y - uy * tipLen * 0.5;
        const px = -uy, py = ux;
        const leftX  = baseX + px * wingLen * 0.5;
        const leftY  = baseY + py * wingLen * 0.5;
        const rightX = baseX - px * wingLen * 0.5;
        const rightY = baseY - py * wingLen * 0.5;

        html += `<polygon points="${tipX},${tipY} ${leftX},${leftY} ${rightX},${rightY}"
                         fill="rgba(59,130,246,0.70)"
                         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 = String(info.amount);
          const bw = 10 + txt.length * 7;
          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="11" 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';

      html += `<g data-node="${nd.id}" style="cursor:${cursor}">
        <circle cx="${nd.x}" cy="${nd.y}" r="${NODE_R}"
                fill="${fill}" stroke="${stroke}" stroke-width="${sw}"/>
        <text x="${nd.x}" y="${nd.y}" text-anchor="middle" dominant-baseline="central"
              font-size="13" font-weight="600" fill="${txt}" pointer-events="none"
              font-family="ui-monospace,Menlo,monospace">${i + 1}</text>
      </g>`;
    }

    svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
    svg.innerHTML = html;
  }

  /* ============================================================
   *  物理引擎
   * ============================================================ */
  function wake() {
    if (!physicsEnabled) return;
    if (physicsOn) return;
    physicsOn = true;
    lastFrame = performance.now();
    requestAnimationFrame(physLoop);
  }

  function physLoop(now) {
    let dt = (now - lastFrame) / 16.6667;
    lastFrame = now;
    dt = Math.min(dt, 2.5);
    if (dt < 0.001) dt = 1;

    const moving = stepPhysics(dt);
    render();

    if (physicsEnabled && (moving || drag)) {
      requestAnimationFrame(physLoop);
    } else {
      physicsOn = false;
      updateUI();
    }
  }

  function stepPhysics(dt) {
    if (!physicsEnabled) return false;

    const dragged = drag ? getNode(drag.id) : null;
    const minD = NODE_R * 2;

    const L = NODE_R + 3, R = W - NODE_R - 3;
    const T = NODE_R + 3, B = H - NODE_R - 3;
    const dampFactor = Math.pow(PHYS.damping, dt);

    for (const nd of nodes) {
      if (nd === dragged) {
        const k = Math.pow(PHYS.dragDrag, dt);
        nd.vx *= k; nd.vy *= k;
        continue;
      }
      nd.x += nd.vx * dt;
      nd.y += nd.vy * dt;
      nd.vx *= dampFactor;
      nd.vy *= dampFactor;

      if (nd.x < L) { nd.x = L; nd.vx = Math.abs(nd.vx) * PHYS.wallBounce; }
      if (nd.x > R) { nd.x = R; nd.vx = -Math.abs(nd.vx) * PHYS.wallBounce; }
      if (nd.y < T) { nd.y = T; nd.vy = Math.abs(nd.vy) * PHYS.wallBounce; }
      if (nd.y > B) { nd.y = B; nd.vy = -Math.abs(nd.vy) * PHYS.wallBounce; }
    }

    for (let it = 0; it < PHYS.iterations; it++) {
      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;
          const total = aFix + bFix;
          if (total === 0) continue;

          const corr = overlap * PHYS.correction / total;
          a.x -= dx * corr * aFix;  a.y -= dy * corr * aFix;
          b.x += dx * corr * bFix;  b.y += dy * corr * bFix;

          const rvx = b.vx - a.vx;
          const rvy = b.vy - a.vy;
          const vn  = rvx * dx + rvy * dy;
          if (vn < 0) {
            const jimp = -(1 + PHYS.restitution) * vn / total;
            a.vx -= jimp * dx * aFix;  a.vy -= jimp * dy * aFix;
            b.vx += jimp * dx * bFix;  b.vy += jimp * dy * bFix;
          }
        }
      }
    }

    let maxV = 0;
    for (const nd of nodes) {
      if (nd === dragged) continue;
      const sp = Math.hypot(nd.vx, nd.vy);
      if (sp > PHYS.maxSpeed) {
        const s = PHYS.maxSpeed / sp;
        nd.vx *= s; nd.vy *= s;
      }
      if (sp > maxV) maxV = sp;
    }
    return maxV > PHYS.sleepSpeed;
  }

  /* ============================================================
   *  图分析
   * ============================================================ */
  function analyze() {
    const n = nodes.length, m = edges.length;
    const idx = new Map();
    nodes.forEach((nd, i) => idx.set(nd.id, i));

    const adjU   = Array.from({ length: n }, () => []);
    const adjOut = Array.from({ length: n }, () => []);
    const adjIn  = Array.from({ length: n }, () => []);
    const indeg  = new Array(n).fill(0);
    const outdeg = 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;
      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);
    let comps = 0;
    for (let i = 0; i < n; i++) {
      if (seen[i]) continue;
      comps++;
      const stack = [i]; seen[i] = true;
      while (stack.length) {
        const u = stack.pop();
        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 = [];
      for (let i = 0; i < n; i++) if (deg[i] === 0) q.push(i);
      let cnt = 0;
      while (q.length) {
        const u = q.shift(); cnt++;
        for (const v of adjOut[u]) if (--deg[v] === 0) q.push(v);
      }
      cycleD = cnt < n;
    }

    let stronglyConnected = true;
    if (n > 0) {
      const vis = new Array(n).fill(false);
      const order = [];
      const dfs1 = u => {
        vis[u] = true;
        for (const v of adjOut[u]) if (!vis[v]) dfs1(v);
        order.push(u);
      };
      for (let i = 0; i < n; i++) if (!vis[i]) dfs1(i);

      const vis2 = new Array(n).fill(false);
      const dfs2 = u => {
        vis2[u] = true;
        for (const v of adjIn[u]) if (!vis2[v]) dfs2(v);
      };
      let c = 0;
      for (let i = order.length - 1; i >= 0; i--) {
        const u = order[i];
        if (!vis2[u]) { c++; dfs2(u); }
      }
      stronglyConnected = c === 1;
    }

    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">
      <div class="stat"><span>顶点数 n</span><b>${r.n}</b></div>
      <div class="stat"><span>边数 m</span><b>${r.m}</b></div>
    </div><ul class="facts">`;

    if (!directed) {
      html += `<li><span class="lbl">连通性</span>
        <span class="rgt">${r.weakConnected ? '' : `(${r.comps} 个连通分量)`}${badge(r.weakConnected, '连通', '不连通')}</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>`;
    } else {
      html += `<li><span class="lbl">弱连通</span>
        <span class="rgt">${r.weakConnected ? '' : `(${r.comps} 个分量)`}${badge(r.weakConnected, '是', '否')}</span></li>`;
      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) => {
      if (directed) {
        html += `<span class="deg">v${i + 1} ↑${r.indeg[i]} ↓${r.outdeg[i]}</span>`;
      } else {
        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;

    const n = nodes.length;
    const maxE = directed ? n * (n - 1) : n * (n - 1) / 2;
    numEdgesEl.max = Math.max(0, maxE);

    let tagText = directed ? '有向图' : '无向图';
    if (!physicsEnabled) tagText += ' · <b>物理已关闭</b>';
    if (capEnabled)      tagText += ' · <b>容量已启用</b>';
    tagEl.innerHTML = tagText;

    refreshSelectors();
    renderAnalysis();
  }

  function refresh() {
    render();
    updateUI();
  }

  /* ============================================================
   *  布局:圆形
   * ============================================================ */
  function layoutCircle() {
    const n = nodes.length;
    if (n === 0) return;
    const cx = W / 2, cy = H / 2;
    if (n === 1) { nodes[0].x = cx; nodes[0].y = cy; return; }
    const rx = Math.max(70, Math.min(W * 0.36, n * 36));
    const ry = Math.max(70, Math.min(H * 0.36, n * 36));
    for (let i = 0; i < n; i++) {
      const ang = -Math.PI / 2 + (2 * Math.PI * i) / n;
      nodes[i].x = cx + rx * Math.cos(ang);
      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];
      let last = start;
      while (queue.length) {
        const u = queue.shift();
        last = u;
        for (const v of adj.get(u) || []) {
          if (!dist.has(v)) {
            dist.set(v, dist.get(u) + 1);
            parent.set(v, u);
            queue.push(v);
          }
        }
      }
      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);
      if (cur === undefined || cur === null) break;
      path.push(cur);
    }
    return path[Math.floor(path.length / 2)];
  }

  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) || []) {
        if (!visited.has(v)) {
          visited.add(v);
          kids.push(v);
          depth.set(v, depth.get(u) + 1);
          queue.push(v);
        }
      }
      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;
      nd.x = offsetX + x * spacingX;
      nd.y = offsetY + d * spacingY;
      nd.vx = 0; nd.vy = 0;
    }
  }

  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;
      ids.forEach((id, i) => {
        const nd = getNode(id);
        if (nd) {
          nd.x = startX + i * spacingX;
          nd.y = paddingY + l * spacingY;
          nd.vx = 0; nd.vy = 0;
        }
      });
    }
  }

  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();
  }

  /* ============================================================
   *  图算法核心
   * ============================================================ */

  function topoSort() {
    if (!directed) {
      return { ok: false, msg: '拓扑排序仅适用于有向图。请先切换到「有向图」。' };
    }
    const n = nodes.length;
    if (n === 0) return { ok: false, msg: '画布为空,请先添加顶点。' };

    const idx = new Map();
    nodes.forEach((nd, i) => idx.set(nd.id, i));

    const indeg = new Array(n).fill(0);
    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;
      adj[a].push(b);
      indeg[b]++;
    }

    let current = [];
    for (let i = 0; i < n; i++) if (indeg[i] === 0) current.push(i);
    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 };
  }

  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;

    for (let iter = 0; iter < n; iter++) {
      let u = -1, best = Infinity;
      for (let i = 0; i < n; i++) {
        if (!visited[i] && dist[i] < best) { best = dist[i]; u = i; }
      }
      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 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);
          }
        }
      }
      if (parent[T] === -1) break;

      let bottleneck = INF;
      let v = T;
      while (v !== S) {
        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 };
  }

  /* ============================================================
   *  算法结果展示
   * ============================================================ */
  function getSelected() {
    const s = selSrc.value, d = selDst.value;
    if (!s || !d) return null;
    return { s: Number(s), d: Number(d) };
  }

  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() {
    clearTopo();
    clearFlow();

    const sel = getSelected();
    if (!sel) { algoResult.innerHTML = '<span class="err">请先添加顶点并选择起点 / 终点。</span>'; render(); return; }
    if (sel.s === sel.d) {
      algoResult.innerHTML = `<span class="err">起点与终点相同,距离为 0。</span>`;
      clearHighlight(); render(); return;
    }

    const r = shortestPath(sel.s, sel.d);
    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();
      render();
      return;
    }

    const nodeIds = new Set(r.path.map(i => nodes[i].id));
    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();
  }

  function showFlow() {
    clearTopo();
    clearHighlight();

    const sel = getSelected();
    if (!sel) {
      algoResult.innerHTML = '<span class="err">请先添加顶点并选择源点 / 汇点。</span>';
      clearFlow(); render(); return;
    }
    if (sel.s === sel.d) {
      algoResult.innerHTML = `<span class="err">源点与汇点相同,最大流为 0。</span>`;
      clearFlow(); render(); return;
    }

    const result = maxFlow(sel.s, sel.d);
    if (!result) {
      algoResult.innerHTML = '<span class="err">选择的顶点无效。</span>';
      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) {
      flowInfo = `<br><span style="font-size:11.5px;color:#64748b">共 ${usedEdges} 条边承载流量</span>` +
                 `<span class="flow-legend">蓝色箭头 = 流向</span>`;
    } else {
      flowInfo = `<br><span style="font-size:11.5px;color:#64748b">没有任何边承载流量</span>`;
    }

    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);
        const y = NODE_R + 24 + Math.random() * Math.max(1, H - 2 * NODE_R - 48);
        let d = Infinity;
        for (const nd of nodes) d = Math.min(d, Math.hypot(nd.x - x, nd.y - y));
        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));
      edges = edges.filter(e => keep.has(e.id));
    }
    clearAllVisual();
    refresh();
  }

  function removeNode(id) {
    nodes = nodes.filter(n => n.id !== id);
    edges = edges.filter(e => e.a !== id && e.b !== id);
    if (pending === id) pending = null;
    clearAllVisual();
    refresh();
  }

  function removeEdge(id) {
    edges = edges.filter(e => e.id !== id);
    clearAllVisual();
    refresh();
  }

  /* ============================================================
   *  随机生成
   * ============================================================ */
  function randomGenerate() {
    const n = clamp(parseInt(numNodesEl.value, 10) || 0, 0, MAX_NODES);
    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);

    nodes = [];
    nodeSeq = 1;
    for (let i = 0; i < n; i++) nodes.push({ id: nodeSeq++, x: 0, y: 0, vx: 0, vy: 0 });
    layoutCircle();
    nodes.forEach(nd => {
      nd.vx = (Math.random() - 0.5) * 3.2;
      nd.vy = (Math.random() - 0.5) * 3.2;
    });

    edges = [];
    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++) {
          pool.push([ids[i], ids[j]]);
          if (directed) pool.push([ids[j], ids[i]]);
        }
      }
      shuffle(pool);
      for (const [a, b] of pool) {
        if (edges.length >= m) break;
        addE(a, b);
      }
    }

    pending = null;
    clearAllVisual();
    algoResult.innerHTML = '选择两个顶点后,可计算它们之间的最短路与最大流。';
    refresh();
    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('边数不能为负');
    const maxE = directed ? n * (n - 1) : n * (n - 1) / 2;
    if (m > maxE) throw new Error(`${directed ? '有向图' : '无向图'}最多只能有 ${maxE} 条边`);

    if (lines.length - 1 < m) {
      throw new Error(`需要 ${m} 行边数据,但只找到 ${lines.length - 1} 行`);
    }

    let weighted = false;
    const parsedEdges = [];
    const seen = new Set();

    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}]`);
      }
      if (u === v) {
        throw new Error(`第 ${lineNum} 行不能是自环(u = v)`);
      }

      let w = 1;
      if (parts.length >= 3) {
        w = parseInt(parts[2], 10);
        if (!Number.isInteger(w) || w < 0) {
          throw new Error(`第 ${lineNum} 行边权必须是非负整数`);
        }
        if (w > 9999) throw new Error(`第 ${lineNum} 行边权不能超过 9999`);
        weighted = true;
      }

      const key = directed ? `${u}>${v}` : (u < v ? `${u}-${v}` : `${v}-${u}`);
      if (seen.has(key)) {
        throw new Error(`第 ${lineNum} 行与之前的边重复`);
      }
      seen.add(key);

      parsedEdges.push({ u, v, w });
    }

    return { n, m, weighted, edges: parsedEdges };
  }

  function applyCode() {
    try {
      const data = parseCode(codeInput.value);

      /* 重置图 */
      nodes = []; edges = []; nodeSeq = 1; edgeSeq = 1;

      /* 创建 n 个顶点(id 从 1 到 n,与输入编号一致) */
      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';
      codeStatus.textContent =
        `✓ 已加载:${data.n} 个顶点,${data.m} 条边` +
        (data.weighted ? '(带权图,容量已启用)' : '') +
        (directed ? ' · 有向' : ' · 无向');

    } catch (err) {
      codeStatus.className = 'code-status err';
      codeStatus.textContent = '✗ ' + err.message;
    }
  }

  function loadCodeSample() {
    const sampleDirected = `7 10
1 2 5
1 3 4
2 3 2
2 4 3
3 5 4
4 5 2
4 6 3
5 6 5
5 7 2
6 7 4`;
    const sampleUndirected = `6 7
1 2 3
2 3 2
3 4 4
4 5 1
5 6 2
1 6 5
2 5 3`;
    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();
  });

  /* Ctrl+Enter 应用 */
  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;

    const pt = svgPoint(e);
    const nodeEl = e.target.closest ? e.target.closest('[data-node]') : null;
    const edgeEl = e.target.closest ? e.target.closest('[data-edge]') : null;

    if (nodeEl) {
      e.preventDefault();
      const id = Number(nodeEl.dataset.node);

      if (mode === 'drag') {
        const nd = getNode(id);
        if (!nd) return;
        nd.vx = 0; nd.vy = 0;
        drag = { id, ox: pt.x - nd.x, oy: pt.y - nd.y };
        wake();

      } 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();

      } else if (mode === 'erase') {
        removeNode(id);
      }
      return;
    }

    if (edgeEl) {
      e.preventDefault();
      if (mode === 'erase') removeEdge(Number(edgeEl.dataset.edge));
      return;
    }

    e.preventDefault();
    if (pending !== null) { pending = null; refresh(); }
    if (mode === 'drag') blankDown = pt;
  });

  window.addEventListener('pointermove', e => {
    if (drag) {
      const pt = svgPoint(e);
      const nd = getNode(drag.id);
      if (!nd) { drag = null; return; }

      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;
    }

    if (mode === 'edge' && pending !== null) {
      hoverPt = svgPoint(e);
      scheduleRender();
    }
  });

  window.addEventListener('pointerup', e => {
    if (drag) {
      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) {
          nodes.push({
            id: nodeSeq++,
            x: clamp(pt.x, NODE_R + 6, Math.max(NODE_R + 6, W - NODE_R - 6)),
            y: clamp(pt.y, NODE_R + 6, Math.max(NODE_R + 6, H - NODE_R - 6)),
            vx: (Math.random() - 0.5) * 2,
            vy: (Math.random() - 0.5) * 2
          });
          clearAllVisual();
          refresh();
          wake();
        }
      }
      blankDown = null;
    }
  });

  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);
  });

  /* ============================================================
   *  控件绑定
   * ============================================================ */
  document.getElementById('typeSeg').addEventListener('click', e => {
    const btn = e.target.closest('.seg-btn');
    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');
    if (!btn) return;
    document.querySelectorAll('#modeSeg .seg-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    mode = btn.dataset.mode;
    modeHint.textContent = HINTS[mode];
    pending = null;
    refresh();
  });

  chkPhysics.addEventListener('change', () => {
    physicsEnabled = chkPhysics.checked;
    if (physicsEnabled) {
      wake();
    } else {
      nodes.forEach(nd => { nd.vx = 0; nd.vy = 0; });
      updateUI();
    }
    updateUI();
  });

  chkCap.addEventListener('change', () => {
    capEnabled = chkCap.checked;
    if (!capEnabled) closePopup();
    clearAllVisual();
    refresh();
  });

  numNodesEl.addEventListener('change', () => {
    const v = clamp(parseInt(numNodesEl.value, 10) || 0, 0, MAX_NODES);
    numNodesEl.value = v;
    setNodeCount(v);
    wake();
  });

  numEdgesEl.addEventListener('change', () => {
    if (chkTree.checked) { numEdgesEl.value = edges.length; return; }
    setEdgeCount(parseInt(numEdgesEl.value, 10) || 0);
  });

  chkTree.addEventListener('change', () => {
    if (chkTree.checked) {
      chkConn.checked = true;
      chkConn.disabled = true;
      numEdgesEl.value = Math.max(0, nodes.length - 1);
      numEdgesEl.disabled = true;
    } else {
      chkConn.disabled = false;
      numEdgesEl.disabled = false;
      numEdgesEl.value = edges.length;
    }
  });

  document.getElementById('btnRandom').addEventListener('click', randomGenerate);

  document.getElementById('btnLayout').addEventListener('click', () => {
    layoutCircle();
    nodes.forEach(nd => {
      nd.vx = (Math.random() - 0.5) * 4;
      nd.vy = (Math.random() - 0.5) * 4;
    });
    refresh();
    wake();
  });

  document.getElementById('btnTidy').addEventListener('click', tidyLayout);

  document.getElementById('btnClear').addEventListener('click', () => {
    nodes = []; edges = []; nodeSeq = 1; edgeSeq = 1; pending = null; drag = null;
    clearAllVisual();
    algoResult.innerHTML = '选择两个顶点后,可计算它们之间的最短路与最大流。';
    refresh();
  });

  document.getElementById('btnTopo').addEventListener('click', showTopo);
  document.getElementById('btnPath').addEventListener('click', showPath);
  document.getElementById('btnFlow').addEventListener('click', showFlow);

  selSrc.addEventListener('change', () => { clearHighlight(); render(); });
  selDst.addEventListener('change', () => { clearHighlight(); render(); });

  /* ============================================================
   *  尺寸自适应
   * ============================================================ */
  const ro = new ResizeObserver(() => {
    const r = stage.getBoundingClientRect();
    W = Math.max(240, Math.round(r.width));
    H = Math.max(240, Math.round(r.height));
    svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
    nodes.forEach(nd => {
      nd.x = clamp(nd.x, NODE_R + 4, W - NODE_R - 4);
      nd.y = clamp(nd.y, NODE_R + 4, H - NODE_R - 4);
    });
    render();
  });
  ro.observe(stage);

  /* ============================================================
   *  初始化
   * ============================================================ */
  {
    const r = stage.getBoundingClientRect();
    W = Math.max(240, Math.round(r.width));
    H = Math.max(240, Math.round(r.height));
  }
  randomGenerate();
})();
</script>
</body>
</html>