图-查看器

· · 科技·工程

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>图论可视化</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.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;}

  /* ================= 滑块 ================= */
  .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;}
  .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 .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;
  }
  .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: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;
    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: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);
  }
  .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>
          <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 9
1 1 2
1 2 2.5
1 2 3.7
1 3 3.14
2 3 0.5
2 4 1.2
3 5 4.8
4 5 3
5 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">
      </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>(最短路会切换为 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>
        <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" step="any" 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 MAX_WEIGHT = 1e9;

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

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

  let edgeMeta = 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
  };

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

  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() {
    computeEdgeMeta();
    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>
        <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; }
        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 = 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';

      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;

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

    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 = [];
      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) {
        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">
      <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>`;
    }

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

  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;

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

  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) {
      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];
      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 (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) || []) {
        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, 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) {
      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;
      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) {
          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();
    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 (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;

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

  /* ============================================================
   *  算法结果展示
   * ============================================================ */
  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.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();
      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;
      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();
  }

  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">${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);
        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;
          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));
      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('边数不能为负');

    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 11
1 1 1.5
1 2 5.5
1 2 -2.1
2 3 2.4
3 4 3.3
4 4 0.8
4 5 2.4
5 6 5.1
5 7 -2.8
6 7 4.9
2 4 1.2`;
    const sampleUndirected = `6 9
1 1 2.5
1 2 3.5
1 2 1.8
2 3 2.2
3 4 4.1
3 4 0.7
4 5 1.7
5 6 2.3
2 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;

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

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

    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');
    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));
  }
  syncPhysSliders();
  randomGenerate();
})();
</script>
</body>
</html>