기말시험 대비 문서의 그림 생성 코드다. if __name__ == "__main__": 아래가 자체 테스트다.

# 기말시험 대비 문서의 그림을 모두 만들고, 문서 답에 쓴 숫자를 다시 계산해 확인한다: 99_final-prep_fig1~33.svg
# 실행: ~/.venvs/vault-plots/bin/python -I 99_final-prep_plot.py  (matplotlib 필요)
import os
from fractions import Fraction as F

import matplotlib
matplotlib.use("svg")
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.patches import FancyBboxPatch, Rectangle, FancyArrowPatch, Circle, Polygon

PREFIX = "99_final-prep"
INK = "#888888"
C = ["#3b82c4", "#d9622b", "#3a9a5b", "#9b59b6", "#c49a1b"]
BLUE, ORANGE, GREEN, PURPLE, GOLD = C
_fonts = {f.name for f in font_manager.fontManager.ttflist}
FONT = next((n for n in ["Apple SD Gothic Neo", "NanumGothic", "Noto Sans CJK KR"] if n in _fonts), "DejaVu Sans")
plt.rcParams.update({
    "font.family": FONT, "font.size": 10.5, "axes.unicode_minus": False, "svg.fonttype": "path",
    "svg.hashsalt": PREFIX, "text.color": INK,
    "axes.edgecolor": INK, "axes.labelcolor": INK, "xtick.color": INK, "ytick.color": INK,
    "axes.facecolor": "none", "figure.facecolor": "none", "savefig.transparent": True,
    "axes.spines.top": False, "axes.spines.right": False, "legend.frameon": False,
})

HERE = os.path.dirname(os.path.abspath(__file__))

# ---------------------------------------------------------------- 파트 A
# =====================================================================
# 1부 계산 도구
# =====================================================================

# ---------- 문제 1: 슬라이딩 윈도우 구현(1바이트 번호, SWS = RWS = 4) ----------
A_SWS = 4
A_RWS = 4


def A_u8(x):
    return x % 256


def A_in_window(x, lo, hi):
    """돌려 쓰는 1바이트 번호로 x가 lo부터 hi 사이(양 끝 포함)에 있나: swpInWindow와 같은 계산."""
    return A_u8(x - lo) < A_u8(hi - lo) + 1


def A_swp_trace():
    """문제 1-2의 사건 열 개를 차례로 돌려, 사건마다 상태를 돌려준다.
    약속: 데이터 n까지 빈틈없이 받으면 ACK n+1(= NFE). LAR은 아직 확인 안 된 첫 번호."""
    st = {"LAR": 254, "LFS": 253, "NFE": 254, "sem": A_SWS,
          "sendQ": [None] * A_SWS, "recvQ": [None] * A_RWS,
          "waiting": [], "delivered": [], "ack": None}
    rows = []

    def snap(ev, fn, ack=None, note=""):
        rows.append({"ev": ev, "fn": fn, "LAR": st["LAR"], "LFS": st["LFS"], "NFE": st["NFE"],
                     "sem": st["sem"], "sendQ": list(st["sendQ"]), "recvQ": list(st["recvQ"]),
                     "ack": ack, "note": note, "delivered": list(st["delivered"])})

    def send(data):
        if st["sem"] == 0:
            st["waiting"].append(data)
            return None
        st["sem"] -= 1
        st["LFS"] = A_u8(st["LFS"] + 1)
        seq = st["LFS"]
        st["sendQ"][seq % A_SWS] = seq
        return seq

    def ack_arrives(a):
        freed = 0
        if A_in_window(a, A_u8(st["LAR"] + 1), A_u8(st["LFS"] + 1)):
            while True:
                st["sendQ"][st["LAR"] % A_SWS] = None
                st["sem"] += 1
                freed += 1
                st["LAR"] = A_u8(st["LAR"] + 1)
                if st["LAR"] == a:
                    break
        while st["waiting"] and st["sem"] > 0:
            send(st["waiting"].pop(0))
        return freed

    def data_arrives(seq, data):
        if not A_in_window(seq, st["NFE"], A_u8(st["NFE"] + A_RWS - 1)):
            if A_u8(st["NFE"] - seq) <= 128:
                return st["NFE"]
            return None
        st["recvQ"][seq % A_RWS] = seq
        st["_data_" + str(seq)] = data
        if seq == st["NFE"]:
            while st["recvQ"][st["NFE"] % A_RWS] is not None:
                s = st["recvQ"][st["NFE"] % A_RWS]
                st["delivered"].append(st["_data_" + str(s)])
                st["recvQ"][st["NFE"] % A_RWS] = None
                st["NFE"] = A_u8(st["NFE"] + 1)
            return st["NFE"]
        return None

    snap("처음", "")
    for d in ["D0", "D1", "D2", "D3"]:
        send(d)
    snap("1", "sendSWP ×4")
    send("D4")
    snap("2", "sendSWP(D4)", note="기다림")
    a = data_arrives(254, "D0")
    snap("3", "deliverSWP(F254)", ack=a)
    a = data_arrives(0, "D2")
    snap("4", "deliverSWP(F0)", ack=a)
    a = data_arrives(1, "D3")
    snap("5", "deliverSWP(F1)", ack=a)
    freed6 = ack_arrives(255)
    snap("6", "deliverSWP(ACK 255)", note="D4 → 번호 2")
    snap("7", "swpTimeout(255)", note="255 다시 보냄")
    a = data_arrives(2, "D4")
    snap("8", "deliverSWP(F2)", ack=a)
    a = data_arrives(255, "D1")
    snap("9", "deliverSWP(F255)", ack=a)
    freed10 = ack_arrives(3)
    snap("10", "deliverSWP(ACK 3)")
    return rows, freed6, freed10


def A_slot_clash(sws, lar):
    """확인을 기다리는 번호가 lar부터 sws개일 때, 같은 칸(seq % sws)을 쓰는 두 번호를 찾는다."""
    seen = {}
    for i in range(sws):
        s = A_u8(lar + i)
        k = s % sws
        if k in seen:
            return seen[k], s
        seen[k] = s
    return None


def A_safe_impl_sizes(max_w):
    """칸을 seq % SWS로 고를 때 255 → 0에서 칸이 이어지는(256의 약수인) 창 크기."""
    return [w for w in range(1, max_w + 1) if 256 % w == 0]


# ---------- 문제 2: CSMA/CD (버스 2 km, 10 Mbps, 전파 2×10^8 m/s) ----------
A_L = 2000           # 버스 길이 (m)
A_V = 200            # 전파 속도 (m/μs)
A_XC = 400           # C의 위치 (m)
A_R = 10             # 전송률 (비트/μs = Mbps)
A_SLOT = 51.2        # 슬롯 시간 (μs)


def A_d(x1, x2):
    return abs(x1 - x2) / A_V


def A_collision_times(tb):
    """A가 0에, B가 tb에 보내기 시작할 때 B와 A가 충돌을 아는 시각."""
    return A_d(0, A_L), tb + A_d(0, A_L)


def A_backoff_run():
    """2-3: A는 k = 0, B는 k = 1. 충돌을 안 순간 멈추고 그때부터 백오프를 센다(잼 무시)."""
    tb_know, ta_know = A_collision_times(9)            # B 10, A 19
    b_stop, a_stop = tb_know, ta_know
    # A: k = 0 → 19 μs에 들어 본다. B의 마지막 신호가 A에 닿는 때까지 바쁘다.
    a_ready = a_stop + 0 * A_SLOT
    b_tail_at_a = b_stop + A_d(A_L, 0)                 # 20
    a_send = max(a_ready, b_tail_at_a)
    a_end = a_send + 1000 / A_R                         # 1,000비트 = 100 μs
    # B: k = 1 → 10 + 51.2 = 61.2 μs에 들어 본다. A의 새 프레임이 B에 닿는 때는 30 μs.
    b_ready = b_stop + 1 * A_SLOT
    a_head_at_b = a_send + A_d(0, A_L)
    a_tail_at_b = a_end + A_d(0, A_L)
    b_busy = a_head_at_b <= b_ready < a_tail_at_b
    b_send = a_tail_at_b if b_busy else b_ready
    return {"a_ready": a_ready, "a_send": a_send, "a_end": a_end, "b_ready": b_ready,
            "a_head_at_b": a_head_at_b, "b_busy": b_busy, "b_send": b_send}


# ---------- 문제 3: 무선 LAN (1바이트 = 1 μs, SIFS 10 μs) ----------
A_RTS, A_CTS, A_ACK, A_DATA, A_SIFS = 20, 14, 14, 1500, 10


def A_rts_cts_times():
    rts = (0, A_RTS)
    cts = (rts[1] + A_SIFS, rts[1] + A_SIFS + A_CTS)
    data = (cts[1] + A_SIFS, cts[1] + A_SIFS + A_DATA)
    ack = (data[1] + A_SIFS, data[1] + A_SIFS + A_ACK)
    nav_cts = A_DATA + A_ACK + 2 * A_SIFS
    nav_rts = A_CTS + A_DATA + A_ACK + 3 * A_SIFS
    return rts, cts, data, ack, nav_cts, nav_rts


# ---------- 문제 4: CDMA (0 → +1, 1 → −1, 보내지 않으면 0) ----------
A_CODES = {"A": (1, 1, -1, -1), "B": (1, -1, 1, -1), "C": (1, -1, -1, 1)}


def A_dot(u, v):
    return sum(a * b for a, b in zip(u, v))


A_D = (1, 1, 1, 1)        # 4-2에서 D에게 주는 코드
A_E = (1, 1, 1, -1)       # 4-2에서 E에게 억지로 주는 코드(직교하지 않음)


def A_code(u):
    return {"D": A_D, "E": A_E}.get(u) or A_CODES[u]


def A_spread(sends):
    """sends: {사용자: 받는 쪽에 닿는 값(+1/−1/0, 세기가 다르면 그 배수)}. 같은 자리 칩끼리 더한 받은 신호."""
    z = [0, 0, 0, 0]
    for u, d in sends.items():
        for m in range(4):
            z[m] += d * A_code(u)[m]
    return tuple(z)


def A_decode(z, code):
    return F(A_dot(z, code), len(code))


# =====================================================================
# 그림
# =====================================================================

def fig_A1():
    """문제 1-2의 상태 표: 사건마다 LAR, LFS, NFE, 남은 자리, 두 큐의 칸."""
    rows, _, _ = A_swp_trace()
    cols = [("사건", 0.55), ("불린 함수", 1.75), ("LAR", 0.55), ("LFS", 0.55), ("NFE", 0.55),
            ("자리", 0.55)] + [(str(k), 0.5) for k in range(4)] + [(str(k), 0.5) for k in range(4)] + \
           [("ACK", 0.6), ("메모", 1.25)]
    xs = [0]
    for _, w in cols:
        xs.append(xs[-1] + w)
    W = xs[-1]
    nrow = len(rows)
    rh = 0.42
    H = (nrow + 2) * rh
    fig, ax = plt.subplots(figsize=(W * 0.98, H * 0.98 + 0.2))
    ax.set_xlim(0, W)
    ax.set_ylim(H, 0)
    ax.set_axis_off()
    # 묶음 머리
    s0, s1 = xs[6], xs[10]
    r0, r1 = xs[10], xs[14]
    ax.add_patch(Rectangle((s0, 0), s1 - s0, rh, facecolor=BLUE, alpha=0.18, edgecolor="none"))
    ax.text((s0 + s1) / 2, rh / 2, "sendQ 칸 (보내는 쪽)", ha="center", va="center", fontsize=10)
    ax.add_patch(Rectangle((r0, 0), r1 - r0, rh, facecolor=GREEN, alpha=0.18, edgecolor="none"))
    ax.text((r0 + r1) / 2, rh / 2, "recvQ 칸 (받는 쪽)", ha="center", va="center", fontsize=10)
    for j, (name, _) in enumerate(cols):
        ax.text((xs[j] + xs[j + 1]) / 2, 1.5 * rh, name, ha="center", va="center", fontsize=10, fontweight="bold")
    ax.plot([0, W], [2 * rh, 2 * rh], color=INK, lw=1)
    prev = None
    for i, r in enumerate(rows):
        y = (i + 2) * rh
        yc = y + rh / 2
        vals = [r["ev"], r["fn"], r["LAR"], r["LFS"], r["NFE"], r["sem"]] + \
               [("" if v is None else v) for v in r["sendQ"]] + [("" if v is None else v) for v in r["recvQ"]] + \
               [("" if r["ack"] is None else r["ack"]), r["note"]]
        for j, v in enumerate(vals):
            x0, x1 = xs[j], xs[j + 1]
            if 6 <= j < 10 and v != "":
                ax.add_patch(Rectangle((x0 + 0.03, y + 0.04), x1 - x0 - 0.06, rh - 0.08, facecolor=BLUE, alpha=0.25, edgecolor="none"))
            if 10 <= j < 14 and v != "":
                ax.add_patch(Rectangle((x0 + 0.03, y + 0.04), x1 - x0 - 0.06, rh - 0.08, facecolor=GREEN, alpha=0.25, edgecolor="none"))
            changed = prev is not None and 2 <= j <= 5 and vals[j] != prev[j]
            ax.text((x0 + x1) / 2, yc, str(v), ha="center", va="center", fontsize=10,
                    color=ORANGE if changed else INK, fontweight="bold" if changed else "normal")
        ax.plot([0, W], [y + rh, y + rh], color=INK, lw=0.4, alpha=0.5)
        prev = vals
    for j in (2, 6, 10, 14):
        ax.plot([xs[j], xs[j]], [rh, H], color=INK, lw=0.8)
    return fig


def _A_bus_axes(ax, tmax, xc=None):
    ax.set_xlim(-150, A_L + 150)
    ax.set_ylim(tmax, -2)
    ax.set_xticks([0, A_L] + ([xc] if xc else []))
    ax.set_xticklabels(["A (0 m)", "B (2,000 m)"] + (["C (400 m)"] if xc else []))
    ax.set_ylabel("시간 (μs)")
    for x in [0, A_L] + ([xc] if xc else []):
        ax.plot([x, x], [0, tmax], color=INK, lw=1, ls="-" if x in (0, A_L) else ":")
    ax.spines["bottom"].set_visible(False)
    ax.xaxis.tick_top()


def _A_band(ax, x0, ts, te, color, alpha=0.35):
    """x0에서 [ts, te] 동안 보낸 신호가 버스 위로 퍼지는 띠."""
    pts_r = [(x0, ts), (A_L, ts + A_d(x0, A_L)), (A_L, te + A_d(x0, A_L)), (x0, te)]
    pts_l = [(x0, ts), (0, ts + A_d(x0, 0)), (0, te + A_d(x0, 0)), (x0, te)]
    for pts in (pts_r, pts_l):
        if pts[0][0] != pts[1][0]:
            ax.add_patch(Polygon(pts, closed=True, facecolor=color, alpha=alpha, edgecolor=color, lw=0.8))


def fig_A2():
    fig, ax = plt.subplots(figsize=(7, 4.2))
    _A_bus_axes(ax, 30)
    tb_know, ta_know = A_collision_times(9)
    _A_band(ax, 0, 0, ta_know, BLUE)
    _A_band(ax, A_L, 9, tb_know, ORANGE, alpha=0.6)
    ax.plot([A_L], [tb_know], marker="*", ms=15, color=ORANGE)
    ax.annotate(f"B가 충돌을 앎: {tb_know:g} μs\n(A의 첫 비트 도착)", (A_L, tb_know), (1180, 3.2),
                fontsize=10, arrowprops=dict(arrowstyle="->", color=INK))
    ax.plot([0], [ta_know], marker="*", ms=15, color=ORANGE)
    ax.annotate(f"A가 충돌을 앎: {ta_know:g} μs\n(B의 첫 비트 도착)", (0, ta_know), (180, 25.5),
                fontsize=10, arrowprops=dict(arrowstyle="->", color=INK))
    ax.annotate("B가 들어 봄: 9 μs, 비어 있음", (A_L, 9), (1150, 15.5), fontsize=10,
                arrowprops=dict(arrowstyle="->", color=INK))
    ax.text(700, 6.3, "A의 신호", color=BLUE, fontsize=10.5, rotation=-17)
    ax.annotate("", (-70, 0), (-70, 20), arrowprops=dict(arrowstyle="<->", color=PURPLE))
    ax.text(40, 2.2, "2d = 20 μs (왕복)", color=PURPLE, fontsize=10, va="center")
    ax.text(40, 11.5, "A는 19 μs까지\n보내는 중", fontsize=10, color=BLUE)
    return fig


def fig_A3():
    fig, ax = plt.subplots(figsize=(7.6, 4.2))
    _A_bus_axes(ax, 24, xc=A_XC)
    ax.set_xlim(-820, A_L + 150)
    _A_band(ax, 0, 0, 10, BLUE)
    _A_band(ax, A_L, 9, 10, ORANGE, alpha=0.6)
    ax.add_patch(Rectangle((A_XC - 25, A_d(0, A_XC)), 50, 10, facecolor=GREEN, alpha=0.5, edgecolor=GREEN))
    ax.annotate("C: 2~12 μs에 A의 프레임을\n온전히 다 받음", (A_XC + 25, 7), (560, 2.5), fontsize=10,
                arrowprops=dict(arrowstyle="->", color=INK))
    t_bc = 9 + A_d(A_L, A_XC)
    ax.plot([A_XC], [t_bc], marker="o", ms=7, color=ORANGE)
    ax.annotate(f"B의 신호가 C에: {t_bc:g} μs\n(C는 이미 다 받은 뒤)", (A_XC, t_bc), (620, 21.5), fontsize=10,
                arrowprops=dict(arrowstyle="->", color=INK))
    ax.plot([0], [10], marker="s", ms=7, color=BLUE)
    ax.text(-60, 10, "10 μs: A가 다 보냄\n→ 성공으로 앎", fontsize=10, color=BLUE, ha="right", va="center")
    ax.plot([0], [19], marker="o", ms=7, color=ORANGE)
    ax.text(-60, 19, "19 μs: B의 신호 도착\n(A는 이미 듣지 않음)", fontsize=10, color=ORANGE, ha="right", va="center")
    ax.plot([A_L], [10], marker="*", ms=15, color=ORANGE)
    ax.text(A_L - 40, 7.4, "B: 깨진 프레임", fontsize=10, ha="right")
    return fig


def fig_A4():
    r = A_backoff_run()
    fig, ax = plt.subplots(figsize=(7, 5.6))
    _A_bus_axes(ax, 150)
    _A_band(ax, 0, 0, 19, BLUE)
    _A_band(ax, A_L, 9, 10, ORANGE, alpha=0.6)
    _A_band(ax, 0, r["a_send"], r["a_end"], BLUE)
    _A_band(ax, A_L, r["b_send"], 175, ORANGE, alpha=0.6)
    ax.text(330, 14, "첫 충돌", fontsize=10)
    ax.plot([0], [r["a_ready"]], marker="o", ms=6, color=BLUE)
    ax.annotate(f"A: k = 0, {r['a_ready']:g} μs에 들어 보니 B의 꼬리가\n아직 지나는 중 → {r['a_send']:g} μs에 보냄",
                (0, r["a_send"]), (120, 40), fontsize=10, arrowprops=dict(arrowstyle="->", color=INK))
    ax.annotate("", (A_L + 70, 10), (A_L + 70, r["b_ready"]), arrowprops=dict(arrowstyle="<->", color=PURPLE))
    ax.text(A_L + 95, (10 + r["b_ready"]) / 2, "B의\n백오프\n51.2 μs", fontsize=10, color=PURPLE, va="center")
    ax.plot([A_L], [r["b_ready"]], marker="o", ms=6, color=ORANGE)
    ax.annotate(f"B: k = 1, {r['b_ready']:g} μs에 들어 보니\nA의 프레임이 지나는 중 → 기다림", (A_L, r["b_ready"]),
                (1050, 78), fontsize=10, arrowprops=dict(arrowstyle="->", color=INK))
    ax.annotate(f"A의 프레임 꼬리가 B를 지남:\n{r['b_send']:g} μs에 B가 보냄", (A_L, r["b_send"]), (900, 110),
                fontsize=10, arrowprops=dict(arrowstyle="->", color=INK))
    ax.text(250, 95, f"A의 프레임\n{r['a_send']:g}~{r['a_end']:g} μs", fontsize=10, color=BLUE)
    return fig


def fig_A5():
    fig, ax = plt.subplots(figsize=(7, 3.4))
    ax.set_aspect("equal")
    ax.set_axis_off()
    pos = {"A": (-40, 0), "AP": (0, 0), "C": (40, 0)}
    for name, col in (("A", BLUE), ("C", GREEN)):
        x, y = pos[name]
        ax.add_patch(Circle((x, y), 50, facecolor=col, alpha=0.08, edgecolor=col, ls="--", lw=1.2))
    for name, (x, y) in pos.items():
        if name == "AP":
            ax.add_patch(FancyBboxPatch((x - 7, y - 4), 14, 8, boxstyle="round,pad=0.5", facecolor="none", edgecolor=PURPLE, lw=1.5))
        else:
            ax.add_patch(Rectangle((x - 6, y - 3.5), 12, 7, facecolor="none", edgecolor=BLUE if name == "A" else GREEN, lw=1.5))
        ax.text(x, y, name, ha="center", va="center", fontsize=11, fontweight="bold")
    ax.annotate("", (-6, -9), (-34, -9), arrowprops=dict(arrowstyle="<->", color=INK))
    ax.text(-20, -13, "40 m", ha="center", va="center", fontsize=10)
    ax.annotate("", (34, -9), (6, -9), arrowprops=dict(arrowstyle="<->", color=INK))
    ax.text(20, -13, "40 m", ha="center", va="center", fontsize=10)
    ax.text(-62, 38, "A의 신호가\n닿는 범위 (50 m)", color=BLUE, fontsize=10, ha="center")
    ax.text(62, 38, "C의 신호가\n닿는 범위 (50 m)", color=GREEN, fontsize=10, ha="center")
    ax.text(0, -30, "A와 C 사이는 80 m: 서로의 신호가 들리지 않는다", fontsize=10, ha="center")
    ax.set_xlim(-95, 95)
    ax.set_ylim(-52, 52)
    return fig


def _A_wl_axes(ax, ticks, tmax_y, labels_y):
    ax.set_xlim(-0.6, 2.6)
    ax.set_ylim(tmax_y, -8)
    for x, name in ((0, "A"), (1, "AP"), (2, "C")):
        ax.plot([x, x], [0, tmax_y], color=INK, lw=1)
        ax.text(x, -5, name, ha="center", va="bottom", fontsize=11, fontweight="bold")
    ax.set_xticks([])
    ax.spines["bottom"].set_visible(False)
    ax.set_yticks(labels_y)
    ax.set_yticklabels([str(t) for t in ticks], fontsize=9.5)
    ax.set_ylabel("시간 (μs)")


def fig_A6():
    """RTS/CTS 없이 CSMA만: A는 0에, C는 300에 1,500바이트 데이터를 보낸다(시간은 고른 눈금)."""
    fig, ax = plt.subplots(figsize=(6.4, 5.2))
    s = 0.1                                            # 1 μs = 0.1 눈금
    ta, tc = 0, 300
    ticks = [0, 300, 1500, 1800]
    _A_wl_axes(ax, ticks, 200, [t * s for t in ticks])
    ax.add_patch(Rectangle((0, ta * s), 1, A_DATA * s, facecolor=BLUE, alpha=0.3, edgecolor=BLUE))
    ax.add_patch(Rectangle((1, tc * s), 1, A_DATA * s, facecolor=ORANGE, alpha=0.3, edgecolor=ORANGE))
    ax.text(0.5, 60, "A의 데이터\n1,500 μs", ha="center", fontsize=10, color=BLUE)
    ax.text(1.5, 165, "C의 데이터\n1,500 μs", ha="center", fontsize=10, color=ORANGE)
    ax.add_patch(Rectangle((0.93, tc * s), 0.14, (ta + A_DATA - tc) * s, facecolor=ORANGE, alpha=0.6, hatch="xx", edgecolor=ORANGE))
    ax.annotate("AP에서 두 신호가\n섞임 (300~1,500 μs)", (1.08, 95), (1.58, 95), fontsize=10, ha="center", va="center",
                arrowprops=dict(arrowstyle="->", color=INK))
    ax.plot([2], [30], marker="o", ms=6, color=ORANGE)
    ax.text(2.1, 30, "300 μs: C가 들어 봄.\nA의 신호가 안 들려\n곧 보냄", fontsize=10, va="center")
    ax.set_xlim(-0.6, 3.15)
    ax.text(-0.08, 165, "A: ACK가\n안 옴", ha="right", fontsize=10, color=PURPLE)
    ax.plot([0], [(A_DATA + 40) * s], marker="x", ms=9, color=PURPLE)
    ax.text(2.08, 190, "C: ACK가\n안 옴", ha="left", fontsize=10, color=PURPLE, va="center")
    ax.plot([2], [(tc + A_DATA + 40) * s], marker="x", ms=9, color=PURPLE)
    ax.text(-0.08, 60, "보내는 내내\nC의 신호가\n안 들림", ha="right", fontsize=10)
    return fig


def _A_ty(t):
    """RTS/CTS 그림의 시간 눈금: 데이터 구간만 줄여 그린다."""
    pts = [(0, 0), (54, 108), (1554, 228), (1600, 320)]
    for (t0, y0), (t1, y1) in zip(pts, pts[1:]):
        if t <= t1:
            return y0 + (y1 - y0) * (t - t0) / (t1 - t0)
    return pts[-1][1]


def fig_A7():
    rts, cts, data, ack, nav_cts, _ = A_rts_cts_times()
    fig, ax = plt.subplots(figsize=(6.6, 6.0))
    ticks = [0, 20, 30, 44, 54, 1554, 1564, 1578]
    _A_wl_axes(ax, ticks, 300, [_A_ty(t) for t in ticks])

    def box(x0, x1, t0, t1, col, label, a=0.35):
        y0, y1 = _A_ty(t0), _A_ty(t1)
        ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, facecolor=col, alpha=a, edgecolor=col))
        ax.text((x0 + x1) / 2, (y0 + y1) / 2, label, ha="center", va="center", fontsize=10)

    box(0, 1, *rts, BLUE, "RTS (20)")
    box(0, 2, *cts, GREEN, "CTS(A), NAV = 1,534 μs")
    box(0, 1, *data, BLUE, "A의 데이터\n1,500 μs\n(줄여 그림)")
    box(0, 1, *ack, GREEN, "ACK (14)")
    y_nav0, y_nav1 = _A_ty(cts[1]), _A_ty(cts[1] + nav_cts)
    ax.add_patch(Rectangle((1.95, y_nav0), 0.1, y_nav1 - y_nav0, facecolor=GOLD, alpha=0.7, edgecolor=GOLD))
    ax.text(2.12, (y_nav0 + y_nav1) / 2, "C는 NAV 동안\n조용히 함\n44~1,578 μs", fontsize=10, va="center")
    ax.plot([2], [_A_ty(300)], marker="o", ms=6, color=ORANGE)
    ax.annotate("300 μs: C에 보낼 것이\n생겨도 기다림", (1.95, _A_ty(300)), (1.08, _A_ty(300) - 6), fontsize=10,
                va="center", arrowprops=dict(arrowstyle="->", color=INK))
    ax.text(2.12, _A_ty(rts[1]) - 4, "RTS는 C에\n안 들림", fontsize=10, va="center", color=INK)
    for yb in (150, 156):
        ax.plot([-0.68, -0.52], [yb - 3, yb + 3], color=INK, lw=1, clip_on=False)
    ax.text(2.12, _A_ty(1578) + 12, "1,578 μs 뒤 C가\n들어 보기부터 다시", fontsize=10, va="center")
    return fig


FIGS_A = [("A1", fig_A1), ("A2", fig_A2), ("A3", fig_A3), ("A4", fig_A4), ("A5", fig_A5),
          ("A6", fig_A6), ("A7", fig_A7)]


def checks_A():
    # ---- 문제 1 ----
    rows, freed6, freed10 = A_swp_trace()
    r = {x["ev"]: x for x in rows}
    assert r["1"]["sendQ"] == [0, 1, 254, 255] and r["1"]["LAR"] == 254 and r["1"]["LFS"] == 1 and r["1"]["sem"] == 0
    assert r["2"]["note"] == "기다림" and r["2"]["LFS"] == 1
    assert r["3"]["ack"] == 255 and r["3"]["NFE"] == 255 and r["3"]["delivered"] == ["D0"]
    assert r["4"]["ack"] is None and r["4"]["recvQ"] == [0, None, None, None]
    assert r["5"]["recvQ"] == [0, 1, None, None] and r["5"]["NFE"] == 255
    assert freed6 == 1 and r["6"]["LAR"] == 255 and r["6"]["LFS"] == 2 and r["6"]["sendQ"] == [0, 1, 2, 255] and r["6"]["sem"] == 0
    assert r["8"]["recvQ"] == [0, 1, 2, None] and r["8"]["ack"] is None
    assert r["9"]["ack"] == 3 and r["9"]["NFE"] == 3 and r["9"]["recvQ"] == [None] * 4
    assert r["9"]["delivered"] == ["D0", "D1", "D2", "D3", "D4"]
    assert freed10 == 4 and r["10"]["LAR"] == 3 and r["10"]["sem"] == 4 and r["10"]["sendQ"] == [None] * 4
    assert [254 % 4, 255 % 4, 0 % 4, 1 % 4, 2 % 4] == [2, 3, 0, 1, 2]
    # 1-1: 번호 256개, SWS = RWS면 128까지. 구현은 256의 약수만.
    assert max(w for w in range(1, 257) if 2 * w <= 256) == 128
    assert A_safe_impl_sizes(128) == [1, 2, 4, 8, 16, 32, 64, 128]
    assert 100 + 100 <= 256 and A_slot_clash(100, 250) == (250, 50)
    assert A_slot_clash(128, 250) is None and A_slot_clash(4, 254) is None and A_slot_clash(3, 254) is not None
    # ---- 문제 2 ----
    assert A_d(0, A_L) == 10 and A_collision_times(9) == (10, 19)
    assert 2 * A_d(0, A_L) * A_R == 200                  # 최소 프레임 200비트
    assert 51.2 * A_R == 512 and 512 // 8 == 64
    assert A_d(0, A_XC) == 2 and A_d(0, A_XC) + 100 / A_R == 12 and 9 + A_d(A_L, A_XC) == 17
    b = A_backoff_run()
    assert b["a_ready"] == 19 and b["a_send"] == 20 and b["a_end"] == 120
    assert abs(b["b_ready"] - 61.2) < 1e-9 and b["a_head_at_b"] == 30 and b["b_busy"] and b["b_send"] == 130
    assert F(1, 2) * F(1, 4) == F(1, 8)
    assert F(3, 10) * 10 == 3                            # 10 Mbps의 30% = 3 Mbps
    # ---- 문제 3 ----
    rts, cts, data, ack, nav_cts, nav_rts = A_rts_cts_times()
    assert rts == (0, 20) and cts == (30, 44) and data == (54, 1554) and ack == (1564, 1578)
    assert nav_cts == 1534 and cts[1] + nav_cts == 1578 and nav_rts == 1558 and rts[1] + nav_rts == 1578
    assert A_DATA / A_RTS == 75 and 1500 + 300 == 1800
    assert 2 * A_DATA == 3000 and 2 * A_RTS == 40
    assert A_RTS + A_SIFS + A_CTS + A_SIFS == 54 and F(54, A_DATA) == F(36, 1000)   # RTS/CTS 추가 시간 54 μs, 3.6%
    # ---- 문제 4 ----
    cs = A_CODES
    for u in cs:
        for v in cs:
            assert A_dot(cs[u], cs[v]) == (4 if u == v else 0)
    z1 = A_spread({"A": -1, "B": 1, "C": -1})
    z2 = A_spread({"A": 1, "B": 0, "C": 1})
    assert z1 == (-1, -1, 3, -1) and z2 == (2, 0, -2, 0)
    assert [A_dot(z1, cs[u]) for u in "ABC"] == [-4, 4, -4]
    assert [A_dot(z2, cs[u]) for u in "ABC"] == [4, 0, 4]
    D = A_D
    assert all(A_dot(D, cs[u]) == 0 for u in cs)
    # 네 칩짜리 ±1 코드 16개 중 A, B, C, D 모두와 직교하는 것은 없다(다섯째 사용자 불가)
    allc = [(a, b, c, d) for a in (1, -1) for b in (1, -1) for c in (1, -1) for d in (1, -1)]
    assert [x for x in allc if all(A_dot(x, y) == 0 for y in list(cs.values()) + [D])] == []
    assert [x for x in allc if all(A_dot(x, y) == 0 for y in cs.values())] == [(1, 1, 1, 1), (-1, -1, -1, -1)]
    # 직교하지 않는 E = (+1,+1,+1,−1)
    assert [A_dot(A_E, cs[u]) for u in "ABC"] == [2, 2, -2] and A_dot(A_E, D) == 2
    z = A_spread({"A": 1, "E": -1})
    assert z == (0, 0, -2, 0) and A_decode(z, cs["A"]) == F(1, 2)
    z = A_spread({"A": 1, "E": -3})                    # E가 가까워 세 배 세기로 닿으면
    assert z == (-2, -2, -4, 2) and A_decode(z, cs["A"]) == F(-1, 2)
    z = A_spread({"A": 1, "E": -2})
    assert A_decode(z, cs["A"]) == 0
    # E 자신도 남의 몫이 섞여 나온다: A만 +1을 보낼 때 E의 코드로 읽으면 2/4
    assert A_decode(A_spread({"A": 1}), A_E) == F(1, 2)

# ---------------------------------------------------------------- 파트 B
# ---------------------------------------------------------------------------
# 2부(스위칭과 브리지) 계산 함수
# ---------------------------------------------------------------------------

# 스위치 네 대로 된 망. 스위치마다 {포트 번호: 이웃 이름}
B_NET = {
    "S1": {0: "A", 1: "C", 2: "S2", 3: "S3"},
    "S2": {0: "S1", 1: "S4", 2: "D"},
    "S3": {0: "S1", 1: "S4", 2: "E"},
    "S4": {0: "S2", 1: "S3", 2: "B", 3: "F"},
}
B_HOSTS = ["A", "B", "C", "D", "E", "F"]


def B_adj(net, broken=()):
    """이웃 목록(양방향). broken은 끊긴 링크 (u, v) 모음."""
    cut = {frozenset(e) for e in broken}
    adj = {}
    for s, ports in net.items():
        for p, n in ports.items():
            if frozenset((s, n)) in cut:
                continue
            adj.setdefault(s, set()).add(n)
            adj.setdefault(n, set()).add(s)
    return adj


def B_dist(adj, dst):
    """dst까지 몇 번 건너는지(너비 우선 탐색)."""
    d = {dst: 0}
    q = [dst]
    while q:
        u = q.pop(0)
        for v in sorted(adj.get(u, ())):
            if v not in d:
                d[v] = d[u] + 1
                q.append(v)
    return d


def B_port_of(net, s, n):
    return next(p for p, x in net[s].items() if x == n)


def B_dg_table(net, s, broken=()):
    """스위치 s의 데이터그램 포워딩 표 {목적지: 나갈 포트}. 길이가 같으면 작은 포트."""
    adj = B_adj(net, broken)
    table = {}
    for h in B_HOSTS:
        d = B_dist(adj, h)
        cands = [(d[n], p) for p, n in net[s].items()
                 if n in d and frozenset((s, n)) not in {frozenset(e) for e in broken}]
        best = min(cands)
        table[h] = best[1]
    return table


def B_dg_path(net, src, dst, broken=()):
    """표를 따라가며 지나는 스위치와 나갈 포트 목록."""
    s = next(sw for sw, ports in net.items() if src in ports.values())
    hops = []
    while True:
        p = B_dg_table(net, s, broken)[dst]
        hops.append((s, p))
        n = net[s][p]
        if n == dst:
            return hops
        s = n


def B_sr_header(ports):
    """지나는 순서의 포트 목록 → 스위치가 맨 오른쪽을 읽도록 적은 헤더."""
    return list(reversed(ports))


def B_sr_rotate(h):
    return [h[-1]] + h[:-1]


def B_sr_strip(h):
    return h[:-1]


def B_sr_trace(header, mode):
    """스위치마다 받은 헤더와 읽은 번호."""
    seen = []
    h = list(header)
    while h:
        seen.append((list(h), h[-1]))
        h = B_sr_rotate(h) if mode == "rotate" else B_sr_strip(h)
        if mode == "rotate" and len(seen) == len(header):
            break
    return seen, h


# 가상 회선: 링크(앞 노드, 뒤 노드)마다 이미 쓰는 VCI
B_VC_USED0 = {("S1", "S2"): {1, 2}, ("S2", "S4"): {1, 3}}
B_VC_PATHS = [["A", "S1", "S2", "S4", "B"], ["C", "S1", "S2", "S4", "B"]]


def B_vc_setup(paths, used0):
    used = {k: set(v) for k, v in used0.items()}
    rows = {}      # 스위치 → [(들어온 포트, VCI, 나갈 포트, VCI)]
    vcis = []      # 연결마다 링크별 VCI
    for path in paths:
        link_vci = []
        for u, v in zip(path, path[1:]):
            s = used.setdefault((u, v), set())
            k = 1
            while k in s:
                k += 1
            s.add(k)
            link_vci.append(k)
        vcis.append(link_vci)
        for i in range(1, len(path) - 1):
            sw = path[i]
            rows.setdefault(sw, []).append((B_port_of(B_NET, sw, path[i - 1]), link_vci[i - 1],
                                            B_port_of(B_NET, sw, path[i + 1]), link_vci[i]))
    return rows, vcis


def B_vc_forward(rows, path, first_vci):
    """데이터 패킷이 지나며 다는 VCI 목록."""
    v = first_vci
    seq = [v]
    for i in range(1, len(path) - 1):
        sw = path[i]
        pin = B_port_of(B_NET, sw, path[i - 1])
        hit = [r for r in rows[sw] if r[0] == pin and r[1] == v]
        assert len(hit) == 1
        v = hit[0][3]
        seq.append(v)
    return seq


# 학습 브리지
B_BR = {"B1": {1: "LAN1", 2: "LAN2"}, "B2": {1: "LAN2", 2: "LAN3", 3: "LAN4"}}
B_BR_LOOP = dict(B_BR, B3={1: "LAN1", 2: "LAN4"})
B_HOST_LAN = {"A": "LAN1", "B": "LAN2", "C": "LAN3", "E": "LAN3", "D": "LAN4"}
B_FRAMES = [("A", "C"), ("C", "A"), ("E", "C"), ("D", "B"), ("B", "D"), ("A", "E")]


def B_bridge_run(bridges, frames, cap=200, tables=None):
    """프레임마다 (브리지별 판단, 실린 LAN 순서, 처리 뒤 표)를 돌려준다."""
    tables = tables if tables is not None else {b: {} for b in bridges}
    out = []
    for src, dst in frames:
        q = [(B_HOST_LAN[src], None)]
        lans, dec, n, history = [], {}, 0, []
        while q and n < cap:
            lan, sender = q.pop(0)
            n += 1
            lans.append(lan)
            for b in sorted(bridges):
                if b == sender:
                    continue
                for p, l in bridges[b].items():
                    if l != lan:
                        continue
                    tables[b][src] = p
                    history.append((b, src, p))
                    if dst == "*" or dst not in tables[b]:
                        outs = [x for x in sorted(bridges[b]) if x != p]
                        kind = "flood"
                    elif tables[b][dst] == p:
                        outs, kind = [], "filter"
                    else:
                        outs, kind = [tables[b][dst]], "forward"
                    dec.setdefault(b, (kind, outs))
                    for x in outs:
                        q.append((bridges[b][x], b))
        out.append({"dec": dec, "lans": lans, "tables": {b: dict(t) for b, t in tables.items()},
                    "left": len(q), "history": history})
    return out


# 스위치 성능
def B_switch_limit(bus_bps, pps, pkt_bytes):
    bus = bus_bps / 2
    cnt = pps * pkt_bytes * 8
    return min(bus, cnt), ("버스" if bus < cnt else "개수"), bus, cnt


# ATM
def B_atm(n_bytes, hdr=5, pay=48):
    cells = -(-n_bytes // pay)
    wire = cells * (hdr + pay)
    pad = cells * pay - n_bytes
    return cells, wire, pad


# ---------------------------------------------------------------------------
# 그림 도우미
# ---------------------------------------------------------------------------
B_POS = {"S1": (2.4, 2.0), "S2": (5.0, 3.1), "S3": (5.0, 0.9), "S4": (7.6, 2.0),
         "A": (0.4, 3.1), "C": (0.4, 0.9), "D": (5.0, 4.6), "E": (5.0, -0.6),
         "B": (9.6, 3.1), "F": (9.6, 0.9)}


def B_node(ax, name, color=INK, alpha=1.0):
    x, y = B_POS[name]
    if name.startswith("S"):
        ax.add_patch(FancyBboxPatch((x - 0.42, y - 0.3), 0.84, 0.6, boxstyle="round,pad=0.02",
                                    fc="none", ec=color, lw=1.6, alpha=alpha))
        ax.text(x, y, name, ha="center", va="center", fontsize=11, color=color, alpha=alpha)
    else:
        ax.add_patch(Rectangle((x - 0.3, y - 0.25), 0.6, 0.5, fc="none", ec=color, lw=1.2, alpha=alpha))
        ax.text(x, y, name, ha="center", va="center", fontsize=11, color=color, alpha=alpha)


def B_edges(net):
    seen = []
    for s, ports in net.items():
        for p, n in ports.items():
            if frozenset((s, n)) not in [frozenset(e) for e in seen]:
                seen.append((s, n))
    return seen


def B_half(name):
    return (0.44, 0.32) if name.startswith("S") else (0.32, 0.27)


def B_clip(u, v):
    """u, v 상자의 테두리에서 끊은 선분의 두 끝."""
    (x1, y1), (x2, y2) = B_POS[u], B_POS[v]
    dx, dy = x2 - x1, y2 - y1
    def t(name):
        hw, hh = B_half(name)
        return min(hw / abs(dx) if dx else 9e9, hh / abs(dy) if dy else 9e9)
    a, b = t(u), 1 - t(v)
    return (x1 + dx * a, y1 + dy * a), (x1 + dx * b, y1 + dy * b)


def B_draw_net(ax, alpha=1.0, ports=True, broken=()):
    cut = {frozenset(e) for e in broken}
    for u, v in B_edges(B_NET):
        (x1, y1), (x2, y2) = B_clip(u, v)
        ls = ":" if frozenset((u, v)) in cut else "-"
        ax.plot([x1, x2], [y1, y2], color=INK, lw=1.2, alpha=alpha, ls=ls, zorder=0)
    for n in B_POS:
        B_node(ax, n, alpha=alpha)
    if ports:
        for s, pp in B_NET.items():
            sx, sy = B_POS[s]
            for p, n in pp.items():
                nx, ny = B_POS[n]
                dx, dy = nx - sx, ny - sy
                L = (dx * dx + dy * dy) ** 0.5
                t = 0.7 / L
                px, py = -dy / L * 0.2, dx / L * 0.2
                if py < 0 or (py == 0 and px < 0):
                    px, py = -px, -py
                ax.text(sx + dx * t + px, sy + dy * t + py, str(p), fontsize=10, color=PURPLE,
                        ha="center", va="center", alpha=alpha)


def B_frame_axes(ax, xlim, ylim):
    ax.set_xlim(*xlim)
    ax.set_ylim(*ylim)
    ax.set_aspect("equal")
    ax.axis("off")


def B_table(ax, x0, y0, widths, rh, rows, title=None, hl=None, fs=10):
    """왼쪽 위 (x0, y0)에서 시작하는 표. rows[0]이 머리 줄. hl: {(r, c): 색}."""
    hl = hl or {}
    W = sum(widths)
    if title:
        ax.text(x0 + W / 2, y0 + 0.12, title, ha="center", va="bottom", fontsize=10.5, color=INK)
    for r, row in enumerate(rows):
        y = y0 - (r + 1) * rh
        x = x0
        for c, cell in enumerate(row):
            col = hl.get((r, c), INK)
            ax.add_patch(Rectangle((x, y), widths[c], rh, fc="none", ec=INK, lw=0.8))
            ax.text(x + widths[c] / 2, y + rh / 2, cell, ha="center", va="center", fontsize=fs,
                    color=col, fontweight=("bold" if r == 0 else "normal"))
            x += widths[c]


# ---------------------------------------------------------------------------
# 그림
# ---------------------------------------------------------------------------
def fig_B_net():
    """문제 그림: 스위치 네 대, 호스트 여섯 대, 포트 번호."""
    fig, ax = plt.subplots(figsize=(7.2, 4.4))
    B_draw_net(ax)
    B_frame_axes(ax, (-0.3, 10.3), (-1.1, 5.1))
    ax.text(10.25, -1.0, "보라 숫자 = 스위치의 포트 번호", ha="right", va="bottom", fontsize=9.5, color=PURPLE)
    return fig


def fig_B_vc_tables():
    """답 그림: 두 가상 회선이 만든 S1, S2, S4의 VC 표 줄."""
    rows, vcis = B_vc_setup(B_VC_PATHS, B_VC_USED0)
    fig, ax2 = plt.subplots(figsize=(9.6, 2.6))
    ax2.set_xlim(0, 10.5)
    ax2.set_ylim(0.3, 3.25)
    ax2.axis("off")
    head = ["들어온\n포트", "들어온\nVCI", "나갈\n포트", "나갈\nVCI"]
    w = [0.75] * 4
    for i, sw in enumerate(["S1", "S2", "S4"]):
        body = [[str(x) for x in r] for r in rows[sw]]
        hl = {(1, c): BLUE for c in range(4)}
        hl.update({(2, c): ORANGE for c in range(4)})
        B_table(ax2, 0.35 + i * 3.5, 2.8, w, 0.62, [head] + body, title=f"{sw}의 VC 표(새 줄)", hl=hl)
    ax2.text(10.4, 0.35, "파랑: A→B 회선의 줄, 주황: C→B 회선의 줄", ha="right", va="bottom", fontsize=9.5, color=INK)
    return fig


def fig_B_vc_path():
    """답 그림: 두 가상 회선의 링크별 VCI."""
    rows, vcis = B_vc_setup(B_VC_PATHS, B_VC_USED0)
    fig, ax = plt.subplots(figsize=(8.4, 4.4))
    B_draw_net(ax, alpha=0.35)
    for k, (path, col) in enumerate(zip(B_VC_PATHS, [BLUE, ORANGE])):
        off = 0.09 if k == 0 else -0.09
        for (u, v), vci in zip(zip(path, path[1:]), vcis[k]):
            (x1, y1), (x2, y2) = B_clip(u, v)
            ax.annotate("", xy=(x2, y2 + off), xytext=(x1, y1 + off),
                        arrowprops=dict(arrowstyle="-|>", color=col, lw=2.0, shrinkA=0, shrinkB=0))
            mx, my = (x1 + x2) / 2, (y1 + y2) / 2
            ax.text(mx, my + (0.38 if k == 0 else -0.38), f"VCI {vci}", color=col, fontsize=10.5,
                    ha="center", va="center", fontweight="bold")
    ax.text(0.0, 4.75, "파랑: A→B 회선", color=BLUE, fontsize=10.5)
    ax.text(0.0, 4.3, "주황: C→B 회선", color=ORANGE, fontsize=10.5)
    B_frame_axes(ax, (-0.3, 10.3), (-1.1, 5.1))
    return fig


def fig_B_dg_tables():
    """답 그림: S1과 S4의 데이터그램 포워딩 표."""
    t1 = B_dg_table(B_NET, "S1")
    t4 = B_dg_table(B_NET, "S4")
    fig, ax = plt.subplots(figsize=(6.4, 3.6))
    ax.set_xlim(0, 6.4)
    ax.set_ylim(0, 3.6)
    ax.axis("off")
    head = ["목적지", "나갈 포트"]
    rows1 = [head] + [[h, str(t1[h])] for h in B_HOSTS]
    rows4 = [head] + [[h, str(t4[h])] for h in B_HOSTS]
    hl1 = {(B_HOSTS.index("B") + 1, 1): ORANGE, (B_HOSTS.index("F") + 1, 1): ORANGE}
    hl4 = {(B_HOSTS.index("A") + 1, 1): ORANGE, (B_HOSTS.index("C") + 1, 1): ORANGE}
    B_table(ax, 0.3, 3.2, [1.1, 1.3], 0.42, rows1, title="S1의 포워딩 표", hl=hl1)
    B_table(ax, 3.6, 3.2, [1.1, 1.3], 0.42, rows4, title="S4의 포워딩 표", hl=hl4)
    return fig


def fig_B_sr_headers():
    """답 그림: A→F 소스 라우팅 헤더(회전·제거)."""
    hops = B_dg_path(B_NET, "A", "F")
    header = B_sr_header([p for _, p in hops])
    fig, ax = plt.subplots(figsize=(8.4, 3.4))
    ax.set_xlim(0, 8.4)
    ax.set_ylim(0, 3.4)
    ax.axis("off")
    names = [s for s, _ in hops]
    cw, ch = 0.42, 0.42
    for r, (mode, label) in enumerate([("rotate", "회전"), ("strip", "제거")]):
        y = 2.2 - r * 1.35
        ax.text(0.15, y + ch / 2, label, fontsize=11, va="center", color=INK)
        seen, _ = B_sr_trace(header, mode)
        for i, (h, read) in enumerate(seen):
            x0 = 1.2 + i * 2.35
            if r == 0:
                ax.text(x0 + 0.65, 3.15, f"{names[i]}이 받은 헤더", ha="center", fontsize=10, color=INK)
            for j, v in enumerate(h):
                last = j == len(h) - 1
                ax.add_patch(Rectangle((x0 + j * cw, y), cw, ch, fc="none",
                                       ec=ORANGE if last else INK, lw=2.0 if last else 1.0))
                ax.text(x0 + j * cw + cw / 2, y + ch / 2, str(v), ha="center", va="center",
                        fontsize=11, color=ORANGE if last else INK)
            josa = "으로" if read in (0, 3, 6) else "로"
            ax.text(x0 + 0.65, y - 0.28, f"포트 {read}{josa}", ha="center", fontsize=9.5, color=ORANGE)
            if i < len(seen) - 1:
                ax.annotate("", xy=(x0 + 2.2, y + ch / 2), xytext=(x0 + 1.45, y + ch / 2),
                            arrowprops=dict(arrowstyle="-|>", color=INK, lw=1.0))
    ax.text(8.35, 0.05, "주황 칸 = 그 스위치가 읽는 번호(맨 오른쪽)", ha="right", fontsize=9.5, color=ORANGE)
    return fig


def fig_B_failure():
    """답 그림: S2–S4가 끊긴 뒤 데이터그램이 돌아가는 길."""
    broken = [("S2", "S4")]
    fig, ax = plt.subplots(figsize=(7.2, 4.4))
    B_draw_net(ax, alpha=0.45, broken=broken)
    hops = B_dg_path(B_NET, "A", "F", broken)
    path = ["A"] + [s for s, _ in hops] + ["F"]
    for u, v in zip(path, path[1:]):
        (x1, y1), (x2, y2) = B_clip(u, v)
        ax.annotate("", xy=(x2, y2), xytext=(x1, y1),
                    arrowprops=dict(arrowstyle="-|>", color=GREEN, lw=2.2, shrinkA=0, shrinkB=0))
    (x1, y1), (x2, y2) = B_POS["S2"], B_POS["S4"]
    ax.text((x1 + x2) / 2, (y1 + y2) / 2, "×", color=ORANGE, fontsize=22, ha="center", va="center")
    ax.text((x1 + x2) / 2 + 0.25, (y1 + y2) / 2 + 0.45, "끊김", color=ORANGE, fontsize=10.5)
    ax.text(0.0, 4.75, "초록: 표가 새로 계산된 뒤 A→F 패킷의 길", color=GREEN, fontsize=10.5)
    hd = " ".join(str(p) for p in B_sr_header([p for _, p in hops]))
    ax.text(10.25, -1.0, f"새 소스 라우팅 헤더: [{hd}]", color=GREEN, fontsize=10.5, ha="right", va="bottom")
    B_frame_axes(ax, (-0.3, 10.3), (-1.1, 5.1))
    return fig


B_BPOS = {"LAN1": (0.2, 1.8, 2.4), "LAN2": (3.9, 1.8, 6.4), "LAN3": (8.4, 3.2, 10.6), "LAN4": (8.4, 0.4, 10.6)}
B_BRPOS = {"B1": (3.15, 1.8), "B2": (7.3, 1.8)}
B_HOSTX = {"A": ("LAN1", 1.3), "B": ("LAN2", 5.15), "C": ("LAN3", 9.0), "E": ("LAN3", 10.0), "D": ("LAN4", 9.5)}


def B_draw_lans(ax, loop=False, alpha=1.0):
    for name, (x1, y, x2) in B_BPOS.items():
        ax.plot([x1, x2], [y, y], color=INK, lw=3, alpha=alpha, solid_capstyle="butt")
        ax.text(x1, y - 0.35, name, fontsize=10, color=INK, alpha=alpha)
    for h, (lan, x) in B_HOSTX.items():
        y = B_BPOS[lan][1]
        ax.plot([x, x], [y, y + 0.35], color=INK, lw=1, alpha=alpha)
        ax.add_patch(Rectangle((x - 0.25, y + 0.35), 0.5, 0.42, fc="none", ec=INK, lw=1.1, alpha=alpha))
        ax.text(x, y + 0.56, h, ha="center", va="center", fontsize=11, color=INK, alpha=alpha)
    # 브리지: 선은 상자 테두리에서 시작한다. (포트, 상자 쪽 끝, LAN 쪽 끝, 포트 글자 자리)
    links = {"B1": [(1, (2.77, 1.8), (2.4, 1.8), (2.58, 1.95)), (2, (3.53, 1.8), (3.9, 1.8), (3.76, 1.95))],
             "B2": [(1, (6.92, 1.8), (6.4, 1.8), (6.66, 1.95)),
                    (2, (7.68, 1.98), (8.4, 3.2), (7.85, 2.5)),
                    (3, (7.68, 1.62), (8.4, 0.4), (7.85, 0.98))]}
    for b, (x, y) in B_BRPOS.items():
        ax.add_patch(FancyBboxPatch((x - 0.38, y - 0.3), 0.76, 0.6, boxstyle="round,pad=0.02",
                                    fc="none", ec=BLUE, lw=1.6, alpha=alpha))
        ax.text(x, y, b, ha="center", va="center", fontsize=11, color=BLUE, alpha=alpha)
        for p, (bx_, by_), (lx, ly), (tx, ty) in links[b]:
            ax.plot([bx_, lx], [by_, ly], color=BLUE, lw=1.2, alpha=alpha, zorder=0)
            ax.text(tx, ty, str(p), fontsize=10, color=PURPLE, ha="center", va="bottom", alpha=alpha)
    if loop:
        bx, by = 5.2, -0.8
        ax.add_patch(FancyBboxPatch((bx - 0.38, by - 0.3), 0.76, 0.6, boxstyle="round,pad=0.02",
                                    fc="none", ec=ORANGE, lw=1.8))
        ax.text(bx, by, "B3", ha="center", va="center", fontsize=11, color=ORANGE)
        ax.plot([0.6, 0.6, bx - 0.4], [1.8, by, by], color=ORANGE, lw=1.4, zorder=0)
        ax.plot([bx + 0.4, 9.0, 9.0], [by, by, 0.4], color=ORANGE, lw=1.4, zorder=0)
        ax.text(bx - 0.6, by + 0.05, "1", fontsize=10, color=PURPLE, va="bottom")
        ax.text(bx + 0.52, by + 0.05, "2", fontsize=10, color=PURPLE, va="bottom")


def fig_B_bridge_net():
    fig, ax = plt.subplots(figsize=(8.0, 3.2))
    B_draw_lans(ax)
    ax.set_xlim(0, 10.8)
    ax.set_ylim(-0.2, 4.1)
    ax.set_aspect("equal")
    ax.axis("off")
    return fig


def B_dec_text(d, b, bridges):
    if b not in d:
        return "받지 않음"
    kind, outs = d[b]
    if kind == "filter":
        return "filter"
    lans = ",".join(bridges[b][p][3:] for p in outs)
    return f"{kind} → LAN{lans}"


def B_learn_text(before, after):
    new = [f"{k}:{v}" for k, v in after.items() if before.get(k) != v]
    return " ".join(new) if new else "—"


def fig_B_bridge_trace():
    res = B_bridge_run(B_BR, B_FRAMES)
    rows = [["#", "프레임", "B1의 판단", "B2의 판단", "실린 LAN", "B1에 새 줄", "B2에 새 줄"]]
    prev = {"B1": {}, "B2": {}}
    for i, ((s, d), r) in enumerate(zip(B_FRAMES, res)):
        lans = ",".join(l[3:] for l in r["lans"])
        rows.append([str(i + 1), f"{s}→{d}", B_dec_text(r["dec"], "B1", B_BR), B_dec_text(r["dec"], "B2", B_BR),
                     lans, B_learn_text(prev["B1"], r["tables"]["B1"]), B_learn_text(prev["B2"], r["tables"]["B2"])])
        prev = r["tables"]
    fig, ax = plt.subplots(figsize=(10.0, 3.9))
    W = [0.45, 0.9, 2.0, 2.2, 1.15, 1.15, 1.15]
    ax.set_xlim(0, sum(W) + 0.1)
    ax.set_ylim(0, 3.95)
    ax.axis("off")
    hl = {}
    for r in range(1, len(rows)):
        for c in (2, 3):
            if rows[r][c].startswith("flood"):
                hl[(r, c)] = ORANGE
            elif rows[r][c].startswith("filter"):
                hl[(r, c)] = GREEN
            elif rows[r][c].startswith("forward"):
                hl[(r, c)] = BLUE
    B_table(ax, 0.05, 3.9, W, 0.52, rows, hl=hl, fs=10)
    return fig


def fig_B_bridge_loop():
    """답 그림: B3을 더해 고리가 생긴 확장 LAN과 방송이 도는 두 방향."""
    fig, ax = plt.subplots(figsize=(8.0, 4.8))
    B_draw_lans(ax, loop=True)
    g = dict(arrowstyle="-|>", color=GREEN, lw=2.0)
    ax.annotate("", xy=(5.0, 2.75), xytext=(1.3, 2.75), arrowprops=dict(g, connectionstyle="arc3,rad=-0.15"))
    ax.annotate("", xy=(9.9, 0.05), xytext=(5.9, 1.45), arrowprops=dict(g, connectionstyle="arc3,rad=0.25"))
    ax.plot([10.3, 10.3, 0.25, 0.25], [0.2, -1.25, -1.25, 1.2], color=GREEN, lw=2.0)
    ax.annotate("", xy=(0.25, 1.6), xytext=(0.25, 1.15), arrowprops=g)
    ax.text(3.15, 3.25, "① LAN1 → B1 → LAN2", color=GREEN, fontsize=10, ha="center")
    ax.text(6.0, 0.35, "② B2 → LAN4", color=GREEN, fontsize=10, ha="center")
    ax.text(5.2, -1.6, "③ LAN4 → B3 → LAN1, 다시 ①로", color=GREEN, fontsize=10, ha="center")
    ax.text(0.0, 4.0, "초록: A의 방송 한 부가 도는 길(반대 방향으로 도는 한 부가 더 있다)",
            color=GREEN, fontsize=10)
    ax.set_xlim(-0.2, 10.8)
    ax.set_ylim(-1.9, 4.4)
    ax.set_aspect("equal")
    ax.axis("off")
    return fig


B_SW_BUS = 1.2e9
B_SW_PPS = 120_000


def fig_B_switch():
    fig, ax = plt.subplots(figsize=(6.8, 3.8))
    L = [64 + i for i in range(0, 1500 - 64 + 1, 4)] + [1500]
    cnt = [B_SW_PPS * l * 8 / 1e6 for l in L]
    bus = B_SW_BUS / 2 / 1e6
    lim = [min(c, bus) for c in cnt]
    ax.plot(L, cnt, color=BLUE, lw=1.2, ls="--")
    ax.axhline(bus, color=ORANGE, lw=1.2, ls="--")
    ax.plot(L, lim, color=GREEN, lw=2.6)
    ax.text(1480, bus + 30, "버스 한계 600 Mbps", color=ORANGE, ha="right", fontsize=10)
    ax.text(1100, B_SW_PPS * 1100 * 8 / 1e6 + 40, "개수 한계\n120,000 × 패킷 비트", color=BLUE,
            ha="right", fontsize=10)
    for l, txt, dx, dy in [(64, "64바이트: 61.44 Mbps", 40, -50), (625, "625바이트에서\n두 한계가 만난다", 25, -170),
                           (1500, "1,500바이트\n600 Mbps", -20, -150)]:
        y = min(B_SW_PPS * l * 8 / 1e6, bus)
        ax.plot([l], [y], "o", color=GREEN, ms=6)
        ax.text(l + dx, y + dy, txt, fontsize=9.5, color=INK, ha="left" if dx > 0 else "right")
    ax.set_xlim(0, 1550)
    ax.set_ylim(0, 1500)
    ax.set_xlabel("패킷 길이(바이트)")
    ax.set_ylabel("처리량(Mbps)")
    ax.text(30, 1380, "초록 실선 = 실제로 낼 수 있는 최대", color=GREEN, fontsize=10)
    return fig


def fig_B_atm():
    cells, wire, pad = B_atm(1500)
    fig, ax = plt.subplots(figsize=(9.0, 2.6))
    scale = 8.6 / wire
    # 위: 원래 패킷
    ax.add_patch(Rectangle((0.2, 1.55), 1500 * scale, 0.45, fc=BLUE, ec="none", alpha=0.35))
    ax.text(0.2 + 1500 * scale / 2, 1.775, "IP 패킷 1,500바이트", ha="center", va="center", fontsize=10.5, color=INK)
    # 아래: 셀
    x = 0.2
    for k in range(cells):
        ax.add_patch(Rectangle((x, 0.6), 5 * scale, 0.45, fc=ORANGE, ec="none"))
        data = 48 if k < cells - 1 else 1500 - 48 * (cells - 1)
        ax.add_patch(Rectangle((x + 5 * scale, 0.6), data * scale, 0.45, fc=BLUE, ec="none", alpha=0.35))
        if data < 48:
            ax.add_patch(Rectangle((x + (5 + data) * scale, 0.6), (48 - data) * scale, 0.45, fc=GOLD, ec="none"))
        ax.add_patch(Rectangle((x, 0.6), 53 * scale, 0.45, fc="none", ec=INK, lw=0.4))
        x += 53 * scale
    ax.text(0.2, 0.32, f"셀 {cells}개 = {wire:,}바이트", fontsize=10.5, color=INK, va="center")
    ax.text(0.2 + wire * scale, 0.32, f"마지막 셀: 데이터 {1500 - 48 * (cells - 1)} + 채움 {pad}",
            fontsize=10, color=GOLD, ha="right", va="center")
    ax.text(0.2 + wire * scale, 2.25, "주황 = 셀 머리말 5바이트, 파랑 = 데이터, 금색 = 채움", fontsize=9.5,
            color=INK, ha="right")
    ax.set_xlim(0, 9.0)
    ax.set_ylim(0.1, 2.5)
    ax.axis("off")
    return fig


FIGS_B = [("B1", fig_B_net), ("B2", fig_B_vc_tables), ("B3", fig_B_vc_path), ("B4", fig_B_dg_tables),
          ("B5", fig_B_sr_headers), ("B6", fig_B_failure), ("B7", fig_B_bridge_net), ("B8", fig_B_bridge_trace),
          ("B9", fig_B_bridge_loop), ("B10", fig_B_switch), ("B11", fig_B_atm)]


def checks_B():
    # 2-1, 2-2 가상 회선
    rows, vcis = B_vc_setup(B_VC_PATHS, B_VC_USED0)
    assert vcis == [[1, 3, 2, 1], [1, 4, 4, 2]], vcis
    assert rows["S1"] == [(0, 1, 2, 3), (1, 1, 2, 4)]
    assert rows["S2"] == [(0, 3, 1, 2), (0, 4, 1, 4)]
    assert rows["S4"] == [(0, 2, 2, 1), (0, 4, 2, 2)]
    assert B_vc_forward(rows, B_VC_PATHS[0], 1) == [1, 3, 2, 1]
    assert B_vc_forward(rows, B_VC_PATHS[1], 1) == [1, 4, 4, 2]
    # 열쇠가 VCI 하나면 S1에서 두 줄이 겹친다
    assert len({r[1] for r in rows["S1"]}) == 1 and len({(r[0], r[1]) for r in rows["S1"]}) == 2
    # 2-3 데이터그램 표
    t1 = B_dg_table(B_NET, "S1")
    t4 = B_dg_table(B_NET, "S4")
    assert t1 == {"A": 0, "B": 2, "C": 1, "D": 2, "E": 3, "F": 2}, t1
    assert t4 == {"A": 0, "B": 2, "C": 0, "D": 0, "E": 1, "F": 3}, t4
    # 소스 라우팅 A→F
    hops = B_dg_path(B_NET, "A", "F")
    assert hops == [("S1", 2), ("S2", 1), ("S4", 3)]
    h = B_sr_header([p for _, p in hops])
    assert h == [3, 1, 2]
    rot, end = B_sr_trace(h, "rotate")
    assert [x[0] for x in rot] == [[3, 1, 2], [2, 3, 1], [1, 2, 3]] and end == [3, 1, 2]
    st, end = B_sr_trace(h, "strip")
    assert [x[0] for x in st] == [[3, 1, 2], [3, 1], [3]] and end == []
    assert [x[1] for x in rot] == [x[1] for x in st] == [2, 1, 3]
    # 흔한 실수: 헤더를 [2 1 3]으로 적으면 S1→S3→S4를 지나 B에 간다
    hh, sw, path = [2, 1, 3], "S1", []
    while True:
        p = hh[-1]
        hh = B_sr_rotate(hh)
        path.append((sw, p))
        nxt = B_NET[sw][p]
        if nxt not in B_NET:
            break
        sw = nxt
    assert path == [("S1", 3), ("S3", 1), ("S4", 2)] and B_NET["S4"][2] == "B"
    # 2-4 S2–S4 고장
    br = [("S2", "S4")]
    assert B_dg_table(B_NET, "S1", br)["F"] == 3 and B_dg_table(B_NET, "S1", br)["B"] == 3
    hb = B_dg_path(B_NET, "A", "F", br)
    assert hb == [("S1", 3), ("S3", 1), ("S4", 3)]
    assert B_sr_header([p for _, p in hb]) == [3, 1, 3]
    assert B_dg_table(B_NET, "S2", br)["B"] == 0      # S2에 남은 패킷은 S1 쪽으로 되돌아간다
    assert B_dg_table(B_NET, "S2", br)["F"] == 0
    assert B_dg_table(B_NET, "S4", br)["A"] == 1
    # 2-5 학습 브리지
    res = B_bridge_run(B_BR, B_FRAMES)
    lans = [[l[3:] for l in r["lans"]] for r in res]
    assert lans == [["1", "2", "3", "4"], ["3", "2", "1"], ["3"], ["4", "2", "3", "1"], ["2", "4"], ["1", "2", "3"]], lans
    kinds = [(r["dec"].get("B1", ("—",))[0], r["dec"].get("B2", ("—",))[0]) for r in res]
    assert kinds == [("flood", "flood"), ("forward", "forward"), ("—", "filter"), ("flood", "flood"),
                     ("filter", "forward"), ("flood", "forward")], kinds
    assert res[-1]["tables"]["B1"] == {"A": 1, "C": 2, "D": 2, "B": 2}
    assert res[-1]["tables"]["B2"] == {"A": 1, "C": 2, "E": 2, "D": 3, "B": 1}
    assert all(r["left"] == 0 for r in res)
    # 받는 사람에게 가는 길이 아닌 LAN(헛걸음): 1번은 LAN4, 4번은 LAN1·LAN3, 나머지는 없음
    tree = {"LAN1": {"LAN2"}, "LAN2": {"LAN1", "LAN3", "LAN4"}, "LAN3": {"LAN2"}, "LAN4": {"LAN2"}}
    def on_path(a, b):
        prev, q = {a: None}, [a]
        while q:
            u = q.pop(0)
            for v in sorted(tree[u]):
                if v not in prev:
                    prev[v] = u
                    q.append(v)
        p, x = set(), b
        while x is not None:
            p.add(x[3:])
            x = prev[x]
        return p
    wasted = [set(l) - on_path(B_HOST_LAN[s], B_HOST_LAN[d]) for (s, d), l in zip(B_FRAMES, lans)]
    assert wasted == [{"4"}, set(), set(), {"1", "3"}, set(), set()], wasted
    # 2-4번 프레임(D→B)이 헛걸음한 LAN: B는 LAN2에 있는데 LAN1, LAN3에도 실림
    assert set(lans[3]) - {"4", "2"} == {"1", "3"}
    # 2-6 고리: 방송이 끝나지 않고, 표의 A 줄이 뒤집힌다
    loop = B_bridge_run(B_BR_LOOP, [("A", "*")], cap=60)[0]
    assert loop["left"] > 0
    a_at_b2 = [p for b, s, p in loop["history"] if b == "B2" and s == "A"]
    assert 1 in a_at_b2 and 3 in a_at_b2
    flips = sum(1 for x, y in zip(a_at_b2, a_at_b2[1:]) if x != y)
    assert flips >= 5
    lan_seq = [l[3:] for l in loop["lans"]]
    assert lan_seq.count("3") >= 10 and lan_seq[1:].count("1") >= 5   # C·E가 여러 번 받고, A도 되받는다
    # 고리가 없으면 방송은 LAN마다 한 번
    nb = B_bridge_run(B_BR, [("A", "*")])[0]
    assert sorted(nb["lans"]) == ["LAN1", "LAN2", "LAN3", "LAN4"] and nb["left"] == 0
    # 2-7 스위치 성능
    x, why, bus, cnt = B_switch_limit(B_SW_BUS, B_SW_PPS, 1500)
    assert (x, why, bus, cnt) == (600e6, "버스", 600e6, 1.44e9)
    assert x / 100e6 == 6
    x, why, bus, cnt = B_switch_limit(B_SW_BUS, B_SW_PPS, 64)
    assert why == "개수" and abs(x - 61.44e6) < 1
    assert B_SW_BUS / (2 * B_SW_PPS) == 5000 and 5000 / 8 == 625
    assert 8 * 100e6 * 2 == 1.6e9                       # 8포트를 다 채우려면 버스 1.6 Gbps
    assert 800e6 / 512 == 1_562_500                     # 64바이트로 채우려면 초당 1,562,500개
    assert round(800e6 / 12_000) == 66_667
    # 2-8 ATM
    assert B_atm(1500) == (32, 1696, 36)
    assert 1500 - 48 * 31 == 12 and 32 * 5 == 160 and 160 + 36 == 196
    assert round(1500 / 1696 * 100, 1) == 88.4 and round(196 / 1696 * 100, 1) == 11.6
    assert round(5 / 53 * 100, 1) == 9.4
    assert B_atm(40) == (1, 53, 8) and round(40 / 53 * 100, 1) == 75.5
    assert 48 * 8 / 64_000 == 0.006 and 1500 * 8 / 64_000 == 0.1875
    assert round(18 / 1518 * 100, 1) == 1.2
    assert round(13 / 53 * 100, 1) == 24.5 and -(-1500 // 53) == 29 and round(1500 / 53, 2) == 28.30
    assert 120_000 * 64 == 7_680_000                    # 비트로 안 바꾸면 나오는 틀린 값
    # 2-9 번역기 수와 표준 모듈 수(10종류)
    assert 10 * 9 // 2 == 45

# ---------------------------------------------------------------- 파트 C
# ---------------------------------------------------------------------
# 3부(IP와 주소) 계산 도구. 이름은 모두 C_로 시작한다.
# ---------------------------------------------------------------------

C_MAC_PREFIX = "AA-00-00-00-"


def C_frag(data, off, mf, mtu, h=20):
    """데이터 data바이트, Offset 칸 off(8바이트 단위), MF mf인 데이터그램을 MTU mtu 링크에 맞게 자른다.
    돌려주는 값: [(데이터 바이트, Offset 칸, MF, Total Length), ...]"""
    if h + data <= mtu:
        return [(data, off, mf, h + data)]
    r = (mtu - h) // 8 * 8
    out, done = [], 0
    while done < data:
        d = min(r, data - done)
        last = done + d == data
        out.append((d, off + done // 8, mf if last else 1, h + d))
        done += d
    return out


def C_path_frag(data, mtus):
    """출발지가 보낸 데이터그램(Offset 0, MF 0)이 MTU 목록을 차례로 지날 때 구간마다의 조각 목록"""
    cur = [(data, 0, 0, 20 + data)]
    seg = []
    for m in mtus:
        nxt = []
        for d, o, f, _ in cur:
            nxt += C_frag(d, o, f, m)
        cur = nxt
        seg.append(cur)
    return seg


def C_reassemble(frags):
    """도착 순서대로 조각을 버퍼에 넣는다. 조각마다 (채운 구간들, 알게 된 끝, 끝났는지)를 돌려준다."""
    filled, end, states = [], None, []
    for d, o, f, _ in frags:
        filled.append((o * 8, o * 8 + d))
        if f == 0:
            end = o * 8 + d
        filled.sort()
        pos = 0
        for a, b in filled:
            if a > pos:
                break
            pos = max(pos, b)
        states.append((list(filled), end, end is not None and pos >= end))
    return states


def C_ip(s):
    a = [int(x) for x in s.split(".")]
    return (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]


def C_str(n):
    return ".".join(str((n >> s) & 255) for s in (24, 16, 8, 0))


def C_mask(k):
    return 0 if k == 0 else (0xFFFFFFFF << (32 - k)) & 0xFFFFFFFF


def C_lpm(table, dst):
    """table: [("a.b.c.d/k", 다음 홉), ...]. 맞는 줄 가운데 접두사가 가장 긴 줄의 (다음 홉, 줄)을 돌려준다."""
    best = None
    for pfx, hop in table:
        net, k = pfx.split("/")
        k = int(k)
        if C_ip(dst) & C_mask(k) == C_ip(net):
            if best is None or k > best[0]:
                best = (k, hop, pfx)
    return (best[1], best[2]) if best else (None, None)


def C_checksum(hdr):
    """인터넷 체크섬: 16비트씩 1의 보수 덧셈 후 뒤집기"""
    s = 0
    for i in range(0, len(hdr), 2):
        s += (hdr[i] << 8) | hdr[i + 1]
        s = (s & 0xFFFF) + (s >> 16)
    return (~s) & 0xFFFF


def C_header(ttl, src="201.10.1.10", dst="201.10.4.20", tl=84, ident=0x1C46, proto=1):
    h = bytearray([0x45, 0, tl >> 8, tl & 255, ident >> 8, ident & 255, 0, 0, ttl, proto, 0, 0])
    h += C_ip(src).to_bytes(4, "big") + C_ip(dst).to_bytes(4, "big")
    cs = C_checksum(h)
    h[10], h[11] = cs >> 8, cs & 255
    return bytes(h)


# 문제 2의 인터넷: 네트워크 1~4, 라우터 R1~R3. 라우터 k가 네트워크 n에 붙은 인터페이스의 MAC은 AA-00-00-00-0k-0n
C_NODES = {
    "A": [("201.10.1.10", "00-0A", 1)],
    "R1": [("201.10.1.1", "01-01", 1), ("201.10.2.1", "01-02", 2)],
    "R2": [("201.10.2.2", "02-02", 2), ("201.10.3.2", "02-03", 3)],
    "R3": [("201.10.3.3", "03-03", 3), ("201.10.4.3", "03-04", 4)],
    "B": [("201.10.4.20", "00-0B", 4)],
}
C_TABLES = {
    "A": [("201.10.1.0/24", "if"), ("0.0.0.0/0", "201.10.1.1")],
    "R1": [("201.10.1.0/24", "if"), ("201.10.2.0/24", "if"), ("201.10.3.0/24", "201.10.2.2"), ("201.10.4.0/24", "201.10.2.2")],
    "R2": [("201.10.1.0/24", "201.10.2.1"), ("201.10.2.0/24", "if"), ("201.10.3.0/24", "if"), ("201.10.4.0/24", "201.10.3.3")],
    "R3": [("201.10.3.0/24", "if"), ("201.10.4.0/24", "if"), ("0.0.0.0/0", "201.10.3.2")],
    "B": [("201.10.4.0/24", "if"), ("0.0.0.0/0", "201.10.4.3")],
}


def C_owner(ip):
    for n, ifs in C_NODES.items():
        for a, m, net in ifs:
            if a == ip:
                return n, m, net
    return None


def C_out_if(node, nexthop):
    """다음 홉과 같은 /24 네트워크에 붙은 내 인터페이스"""
    for a, m, net in C_NODES[node]:
        if C_ip(a) & C_mask(24) == C_ip(nexthop) & C_mask(24):
            return a, m, net


def C_deliver(src_node, dst_ip, ttl0=64, arp=None):
    """홉마다 (보내는 노드, 찾은 줄, 다음 홉 IP, 네트워크, 출발 MAC, 목적 MAC, TTL, 체크섬, ARP 요청 여부)
    arp: 노드별 ARP 표(dict). 요청을 받은 대상은 요청자를 적는다."""
    if arp is None:
        arp = {n: {} for n in C_NODES}
    hops, node, ttl = [], src_node, ttl0
    src_ip = C_NODES[src_node][0][0]
    while True:
        if any(a == dst_ip for a, _, _ in C_NODES[node]):
            return hops, arp
        if node != src_node:
            ttl -= 1
            if ttl == 0:
                return hops + [("drop", node)], arp
        hop, line = C_lpm(C_TABLES[node], dst_ip)
        nh = dst_ip if hop == "if" else hop
        my_ip, my_mac, net = C_out_if(node, nh)
        asked = nh not in arp[node]
        nxt, nh_mac, _ = C_owner(nh)
        if asked:
            arp[node][nh] = nh_mac
            arp[nxt][my_ip] = my_mac
        hops.append((node, line, nh, net, my_mac, nh_mac, ttl, C_header(ttl, src_ip, dst_ip)[10:12].hex(), asked))
        node = nxt


# 문제 3: 회사 K의 /22를 부서별로 나눈다
C_DEPTS = [("개발", 400), ("영업", 200), ("연구", 100), ("관리", 50)]


def C_alloc(base, k_block, depts):
    """큰 블록부터 경계에 맞춰 놓는다. (이름, 호스트 수, 접두사 길이, 시작, 끝, 쓸 수 있는 수)"""
    pos, out = C_ip(base), []
    for name, n in sorted(depts, key=lambda x: -x[1]):
        hb = 0
        while (1 << hb) - 2 < n:
            hb += 1
        size = 1 << hb
        assert pos % size == 0
        out.append((name, n, 32 - hb, pos, pos + size - 1, size - 2))
        pos += size
    assert pos <= C_ip(base) + (1 << (32 - k_block))
    return out


C_KTABLE = [("200.30.40.0/23", "if0"), ("200.30.42.0/24", "if1"), ("200.30.43.0/25", "if2"),
            ("200.30.43.128/26", "if3"), ("0.0.0.0/0", "X")]
C_XTABLE = [("200.30.40.0/22", "K"), ("200.30.44.0/22", "J"), ("0.0.0.0/0", "Z")]


def C_loop_hops(dst, ttl=64):
    """회사 라우터(K-R)와 ISP 라우터 X 사이에서 dst가 몇 번 오가는지 센다. (방문 순서, 버린 곳)"""
    where, seq = "K", []
    while True:
        seq.append(where)
        ttl -= 1
        if ttl == 0:
            return seq, where
        if where == "K":
            hop, _ = C_lpm(C_KTABLE, dst)
            if hop != "X":
                return seq, hop
            where = "X"
        else:
            hop, _ = C_lpm(C_XTABLE, dst)
            if hop != "K":
                return seq, hop
            where = "K"


def C_aggregate(p1, p2):
    """두 블록이 한 블록으로 합쳐지면 그 접두사를, 아니면 None"""
    n1, k1 = p1.split("/")
    n2, k2 = p2.split("/")
    k1, k2 = int(k1), int(k2)
    if k1 != k2:
        return None
    k = k1 - 1
    if C_ip(n1) & C_mask(k) == C_ip(n2) & C_mask(k) and C_ip(n1) != C_ip(n2):
        return f"{C_str(C_ip(n1) & C_mask(k))}/{k}"
    return None


# 문제 4: NAT
def C_nat(packets, G="138.76.29.7", first=5001):
    table, nxt, out = {}, first, []
    for direction, s, d in packets:
        if direction == "out":
            if s not in table.values():
                table[nxt] = s
                nxt += 1
            g = [k for k, v in table.items() if v == s][0]
            out.append(((G, g), d))
        else:
            g = d[1]
            out.append((s, table[g]) if g in table else None)
    return table, out


# ---------------------------------------------------------------------
# 그림 도구
# ---------------------------------------------------------------------

def C_blank(w, h, xl, yl):
    fig, ax = plt.subplots(figsize=(w, h))
    ax.set_xlim(*xl)
    ax.set_ylim(*yl)
    ax.set_axis_off()
    return fig, ax


def C_box(ax, x, y, w, h, fc, ec=None, lw=1.2, alpha=1.0, r=0.06):
    ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle=f"round,pad=0,rounding_size={r}",
                                fc=fc, ec=ec or fc, lw=lw, alpha=alpha))


def C_node(ax, x, y, name, color, w=0.9, h=0.55):
    C_box(ax, x - w / 2, y - h / 2, w, h, "none", color, lw=1.8)
    ax.text(x, y, name, ha="center", va="center", fontsize=11.5, color=color, fontweight="bold")


def C_arrow(ax, x0, y0, x1, y1, color, ls="-", lw=1.6):
    ax.add_patch(FancyArrowPatch((x0, y0), (x1, y1), arrowstyle="-|>", mutation_scale=13,
                                 color=color, lw=lw, linestyle=ls, shrinkA=0, shrinkB=0))


# ---------------------------------------------------------------------
# 문제 1 · 단편화
# ---------------------------------------------------------------------
C_P1_DATA = 1480
C_P1_MTU = [1500, 1006, 576]


def fig_C1():
    fig, ax = C_blank(9.0, 2.3, (0, 10), (0, 2.6))
    xs = [0.8, 3.8, 6.8, 9.2]
    names = ["H1", "R1", "R2", "H2"]
    cols = [BLUE, GREEN, GREEN, BLUE]
    for i, (nm, mtu, lab) in enumerate(zip(range(3), C_P1_MTU, ["네트워크 A (이더넷)", "네트워크 B", "네트워크 C"])):
        ax.plot([xs[i] + 0.45, xs[i + 1] - 0.45], [1.0, 1.0], color=INK, lw=2)
        ax.text((xs[i] + xs[i + 1]) / 2, 1.22, lab, ha="center", va="bottom", fontsize=10.5)
        ax.text((xs[i] + xs[i + 1]) / 2, 0.78, f"MTU {mtu:,}", ha="center", va="top", fontsize=11, color=ORANGE)
    for x, nm, c in zip(xs, names, cols):
        C_node(ax, x, 1.0, nm, c)
    ax.text(0.35, 2.3, "H1이 보내는 데이터그램:  Total Length 1,500 · Ident 7001 · DF 0 · MF 0 · Offset 0",
            ha="left", va="center", fontsize=10.5, color=PURPLE)
    return fig


def fig_C2():
    seg = C_path_frag(C_P1_DATA, C_P1_MTU)
    fig, ax = C_blank(9.6, 4.4, (-2.3, 16.2), (-0.6, 6.5))
    scale = 13.5 / 1500
    labs = ["네트워크 A\nMTU 1,500", "네트워크 B\nMTU 1,006", "네트워크 C\nMTU 576"]
    for row, (frags, lab) in enumerate(zip(seg, labs)):
        y = 5.0 - row * 2.2
        ax.text(-0.3, y + 0.35, lab, ha="right", va="center", fontsize=10.5)
        x = 0.0
        for d, o, f, tl in frags:
            w_h = 20 * scale
            w_d = d * scale
            C_box(ax, x, y, w_h, 0.7, PURPLE, alpha=0.85, r=0.03)
            col = ORANGE if (row == 2 and o == 69) else BLUE
            C_box(ax, x + w_h, y, w_d, 0.7, col, alpha=0.30, ec=col, r=0.03)
            ax.text(x + w_h + w_d / 2, y + 0.35, f"{d:,}", ha="center", va="center", fontsize=10.5)
            ax.text(x + (w_h + w_d) / 2, y - 0.12, f"Off {o} · MF {f}\nTL {tl:,}", ha="center", va="top",
                    fontsize=9.8, color=col if col == ORANGE else INK)
            x += w_h + w_d + 0.35
    ax.text(0.0, 6.15, "보라 칸 = IP 헤더 20바이트, 칸 안의 숫자 = 데이터 바이트 수", ha="left", va="center", fontsize=9.8, color=PURPLE)
    return fig


def fig_C3():
    seg = C_path_frag(C_P1_DATA, C_P1_MTU)[-1]
    order = [seg[2], seg[0], seg[1]]
    states = C_reassemble(order)
    fig, ax = C_blank(9.4, 3.4, (-3.2, 15.4), (-0.4, 5.8))
    scale = 14.0 / C_P1_DATA
    for i, ((d, o, f, tl), (filled, end, done)) in enumerate(zip(order, states)):
        y = 4.4 - i * 1.9
        ax.text(-0.3, y + 0.3, f"{i + 1}번째 도착\nOff {o} · MF {f}", ha="right", va="center", fontsize=10)
        ax.add_patch(Rectangle((0, y), C_P1_DATA * scale, 0.6, fc="none", ec=INK, lw=1.0))
        for a, b in filled:
            col = ORANGE if a == o * 8 else BLUE
            ax.add_patch(Rectangle((a * scale, y), (b - a) * scale, 0.6, fc=col, alpha=0.45, ec=col))
            ax.text((a + b) / 2 * scale, y + 0.3, f"{a:,}~{b - 1:,}", ha="center", va="center", fontsize=9.8)
        note = f"끝 = {end:,}바이트" if end else "끝을 아직 모름"
        note += " · 빈 곳 없음 → 위층으로" if done else " · 빈 곳 있음 → 기다림"
        ax.text(0, y + 0.72, note, ha="left", va="bottom", fontsize=10, color=GREEN if done else INK)
    ax.text(C_P1_DATA * scale, -0.25, "재조립 버퍼 (바이트 0 ~ 1,479)", ha="right", va="center", fontsize=9.8)
    return fig


# ---------------------------------------------------------------------
# 문제 2 · 라우터 셋을 지나는 전달
# ---------------------------------------------------------------------

def fig_C4():
    fig, ax = C_blank(10.4, 2.5, (0, 21), (0.3, 4.7))
    xs = {"A": 1.2, "R1": 6.0, "R2": 10.5, "R3": 15.0, "B": 19.8}
    cols = {"A": BLUE, "R1": GREEN, "R2": GREEN, "R3": GREEN, "B": BLUE}
    nets = [("네트워크 1", "201.10.1.0/24", "A", "R1"), ("네트워크 2", "201.10.2.0/24", "R1", "R2"),
            ("네트워크 3", "201.10.3.0/24", "R2", "R3"), ("네트워크 4", "201.10.4.0/24", "R3", "B")]
    y = 3.0
    for nm, pfx, a, b in nets:
        ax.plot([xs[a] + 0.5, xs[b] - 0.5], [y, y], color=INK, lw=2.2)
        ax.text((xs[a] + xs[b]) / 2, 1.0, f"{nm} (이더넷)\n{pfx}", ha="center", va="center", fontsize=10)
    for n, x in xs.items():
        C_node(ax, x, y, n, cols[n], w=1.0, h=0.7)
        ifs = C_NODES[n]
        if n in ("A", "B"):
            ip, mac, _ = ifs[0]
            ax.text(x, y + 0.6, f"{ip}\n…{mac}", ha="center", va="bottom", fontsize=9.8, color=cols[n])
        else:
            for (ip, mac, net), dx, ha in zip(ifs, (-0.55, 0.55), ("right", "left")):
                ax.text(x + dx, y + 0.6, f"{ip}\n…{mac}", ha=ha, va="bottom", fontsize=9.8, color=cols[n])
    return fig



def fig_C5():
    hops, _ = C_deliver("A", "201.10.4.20")
    order = ["A", "R1", "R2", "R3", "B"]
    xs = {n: i * 3.2 for i, n in enumerate(order)}
    fig, ax = C_blank(9.6, 9.4, (-1.0, 13.8), (-17.4, 1.0))
    for n, x in xs.items():
        ax.plot([x, x], [0, -17.2], color=INK, lw=1.0)
        ax.text(x, 0.3, n, ha="center", va="bottom", fontsize=11.5, fontweight="bold",
                color=BLUE if n in ("A", "B") else GREEN)
    ax.text(-0.7, -0.4, "시간\n↓", ha="center", va="top", fontsize=10)
    t = -0.9
    for i, (node, line, nh, net, smac, dmac, ttl, cs, asked) in enumerate(hops):
        x0, x1 = xs[node], xs[order[i + 1]]
        mx = (x0 + x1) / 2
        C_arrow(ax, x0, t, x1, t - 0.5, ORANGE, ls="--")
        ax.text(mx, t - 0.05, f"ARP 요청 (방송)\n{nh}?", ha="center", va="bottom", fontsize=9.6, color=ORANGE)
        t -= 1.0
        C_arrow(ax, x1, t, x0, t - 0.5, PURPLE, ls="--")
        ax.text(mx, t - 0.55, f"ARP 응답 …{dmac}", ha="center", va="top", fontsize=9.6, color=PURPLE)
        t -= 1.75
        C_arrow(ax, x0, t, x1, t - 0.5, BLUE, lw=2.2)
        ax.text(mx, t - 0.05, f"…{smac} → …{dmac}", ha="center", va="bottom", fontsize=9.6, color=BLUE)
        ax.text(mx, t - 0.55, f"TTL {ttl} · 0x{cs}", ha="center", va="top", fontsize=9.6, color=BLUE)
        t -= 1.3
    return fig


# ---------------------------------------------------------------------
# 문제 3 · 서브넷팅과 CIDR
# ---------------------------------------------------------------------


def fig_C6():
    al = C_alloc("200.30.40.0", 22, C_DEPTS)
    base = C_ip("200.30.40.0")
    fig, ax = C_blank(9.6, 2.7, (-0.3, 10.6), (-1.6, 2.2))
    sc = 10.0 / 1024
    cols = [BLUE, GREEN, ORANGE, PURPLE]
    for (name, n, k, a, b, use), col in zip(al, cols):
        x0 = (a - base) * sc
        w = (b - a + 1) * sc
        ax.add_patch(Rectangle((x0, 0), w, 0.8, fc=col, alpha=0.35, ec=col, lw=1.2))
        ax.text(x0 + w / 2, 0.4, f"{name}\n/{k}" if k >= 25 else f"{name} /{k}", ha="center", va="center", fontsize=10)
        ax.text(x0 + 0.03, -0.12, f".{(a >> 8) & 255}.{a & 255}", ha="left", va="top", fontsize=9.6)
    endu = al[-1][4] + 1
    ax.add_patch(Rectangle(((endu - base) * sc, 0), (base + 1024 - endu) * sc, 0.8, fc="none", ec=INK, lw=1.0, ls="--"))
    ax.text(((endu - base) + (base + 1024 - endu) / 2) * sc, 0.4, "남김", ha="center", va="center", fontsize=10)
    ax.text((endu - base) * sc + 0.03, -0.55, f".{(endu >> 8) & 255}.{endu & 255}", ha="left", va="top", fontsize=9.6)
    ax.text(10.0, 0.92, ".43.255", ha="right", va="bottom", fontsize=9.6)
    ax.text(0, 1.25, "200.30.40.0/22  (주소 1,024개)", ha="left", va="bottom", fontsize=10.5)
    ax.text(0, -1.05, "아래 숫자는 블록이 시작하는 주소의 셋째·넷째 바이트 (200.30. 생략)", ha="left", va="top", fontsize=9.6)
    return fig



def fig_C7():
    fig, ax = C_blank(7.6, 3.6, (0, 12), (-1.1, 5.4))
    pos = {"Z": (6.0, 4.5), "X": (3.5, 2.6), "W": (9.0, 2.6), "K": (1.8, 0.6), "J": (5.2, 0.6)}
    hw, hh = 0.5, 0.33

    def edge(a, b, col, ls):
        (x0, y0), (x1, y1) = a, b
        dx, dy = x1 - x0, y1 - y0
        f = min(hw / abs(dx) if dx else 9, hh / abs(dy) if dy else 9)
        ax.plot([x0 + dx * f, x1 - dx * f], [y0 + dy * f, y1 - dy * f], color=col, lw=1.6, ls=ls)

    for a, b in [("Z", "X"), ("Z", "W"), ("X", "K"), ("X", "J")]:
        edge(pos[a], pos[b], INK, "-")
    edge(pos["W"], pos["J"], ORANGE, "--")
    for n, (x, y) in pos.items():
        C_node(ax, x, y, n, GREEN if n in ("Z", "X", "W") else BLUE, w=2 * hw, h=2 * hh)
    ax.text(pos["K"][0], 0.1, "회사 K\n200.30.40.0/22", ha="center", va="top", fontsize=10)
    ax.text(pos["J"][0], 0.1, "회사 J\n200.30.44.0/22", ha="center", va="top", fontsize=10)
    ax.text(pos["Z"][0] + 0.65, pos["Z"][1], "ISP 위쪽 라우터", ha="left", va="center", fontsize=10)
    ax.text(pos["X"][0] - 0.65, pos["X"][1], "접속 라우터", ha="right", va="center", fontsize=10)
    ax.text(pos["W"][0] + 0.65, pos["W"][1], "(나) J가 옮겨 가는\n접속 라우터", ha="left", va="center", fontsize=10, color=ORANGE)
    return fig


# ---------------------------------------------------------------------
# 문제 4 · 집에서 서버로
# ---------------------------------------------------------------------


def fig_C8():
    fig, ax = C_blank(11.4, 3.2, (0, 23.4), (-0.4, 6.0))
    y = 3.0
    ax.add_patch(FancyBboxPatch((0.2, 0.6), 5.0, 4.8, boxstyle="round,pad=0,rounding_size=0.3",
                                fc=BLUE, alpha=0.07, ec=BLUE, lw=1.0))
    ax.text(2.7, 5.15, "집 LAN 192.168.0.0/24", ha="center", va="center", fontsize=10, color=BLUE)
    C_node(ax, 1.6, 4.0, "노트북 L", BLUE, w=1.9, h=0.6)
    C_node(ax, 1.6, 1.9, "휴대폰 P", BLUE, w=1.9, h=0.6)
    ax.text(1.6, 3.55, "…00-11", ha="center", va="top", fontsize=9.8, color=BLUE)
    ax.text(1.6, 1.45, "…00-22", ha="center", va="top", fontsize=9.8, color=BLUE)
    gx = 6.6
    C_node(ax, gx, y, "G", PURPLE, w=1.0, h=0.8)
    ax.text(gx, y + 0.6, "공유기", ha="center", va="bottom", fontsize=10, color=PURPLE)
    ax.text(gx - 0.6, y - 0.55, "192.168.0.1", ha="right", va="top", fontsize=9.8, color=PURPLE)
    ax.text(gx + 0.6, y - 0.55, "138.76.29.7", ha="left", va="top", fontsize=9.8, color=PURPLE)
    for yy in (4.0, 1.9):
        ax.plot([2.55, gx - 0.5], [yy, y], color=INK, lw=1.4)
    xs = [gx, 12.4, 16.6, 20.1]
    for i in range(3):
        ax.plot([xs[i] + 0.5, xs[i + 1] - 0.5], [y, y], color=INK, lw=2.0)
    for i, (m, col) in enumerate([("MTU 1,492", ORANGE), ("MTU 1,500", INK), ("MTU 1,500", INK)]):
        ax.text((xs[i] + xs[i + 1]) / 2, y + 0.25, m, ha="center", va="bottom", fontsize=10, color=col)
    C_node(ax, xs[1], y, "I1", GREEN)
    C_node(ax, xs[2], y, "I2", GREEN)
    C_node(ax, xs[3], y, "S", BLUE)
    ax.text(xs[1] - 0.55, y - 0.55, "138.76.29.254", ha="right", va="top", fontsize=9.8, color=GREEN)
    ax.text(xs[1] + 0.55, y - 0.55, "61.40.1.1", ha="left", va="top", fontsize=9.8, color=GREEN)
    ax.text(xs[2] - 0.55, y - 0.55, "61.40.1.2", ha="right", va="top", fontsize=9.8, color=GREEN)
    ax.text(xs[2] + 0.55, y - 1.15, "128.119.40.1", ha="left", va="top", fontsize=9.8, color=GREEN)
    ax.text(xs[3] + 0.6, y, "128.119.40.186\n웹 서버, 포트 80", ha="left", va="center", fontsize=9.8, color=BLUE)
    ax.text(13.4, 0.4, "I1, I2: 인터넷 서비스 업체(ISP)와 인터넷의 라우터", ha="center", va="center", fontsize=9.8)
    return fig



def fig_C9():
    table, outs = C_nat([("out", ("192.168.0.23", 50000), ("128.119.40.186", 80)),
                         ("out", ("192.168.0.57", 50000), ("128.119.40.186", 80))])
    fig, ax = C_blank(11.0, 5.0, (0, 22.4), (-0.4, 10.0))
    C_node(ax, 0.8, 8.0, "L", BLUE, w=1.0, h=0.7)
    C_node(ax, 0.8, 3.0, "P", BLUE, w=1.0, h=0.7)
    ax.text(0.3, 7.45, "192.168.0.23", ha="left", va="top", fontsize=9.8, color=BLUE)
    ax.text(0.3, 2.45, "192.168.0.57", ha="left", va="top", fontsize=9.8, color=BLUE)
    bx0, bx1 = 7.8, 13.2
    C_box(ax, bx0, 1.2, bx1 - bx0, 7.8, "none", PURPLE, lw=1.8, r=0.2)
    ax.text((bx0 + bx1) / 2, 9.25, "공유기 G (NAT)", ha="center", va="bottom", fontsize=10.5, color=PURPLE)
    ax.text(bx0, 0.9, "안 192.168.0.1", ha="left", va="top", fontsize=9.8, color=PURPLE)
    ax.text(bx1, 0.9, "밖 138.76.29.7", ha="right", va="top", fontsize=9.8, color=PURPLE)
    C_node(ax, 20.2, 5.5, "S", BLUE, w=1.0, h=0.7)
    ax.text(19.75, 4.95, "128.119.40.186", ha="left", va="top", fontsize=9.8, color=BLUE)
    ax.text((bx0 + bx1) / 2, 6.3, "NAT 변환 표", ha="center", va="bottom", fontsize=10, color=GOLD)
    rows = [("밖 쪽 포트", "안 쪽 주소:포트")] + [(f"{g}", f"{a[0]}:{a[1]}") for g, a in table.items()]
    for i, (w, l) in enumerate(rows):
        yy = 5.8 - i * 0.8
        ax.text(bx0 + 0.25, yy, w, ha="left", va="center", fontsize=9.8, color=GOLD if i == 0 else INK)
        ax.text(bx1 - 0.25, yy, l, ha="right", va="center", fontsize=9.8, color=GOLD if i == 0 else INK)
    ax.plot([bx0 + 0.2, bx1 - 0.2], [5.4, 5.4], color=GOLD, lw=0.8)

    def pkt(x0, y0, x1, y1, col, num, s, d, above=True):
        C_arrow(ax, x0, y0, x1, y1, col, lw=1.8)
        mx, my = (x0 + x1) / 2, (y0 + y1) / 2
        ax.text(mx, my + (0.25 if above else -0.5), f"({num}) S {s}\nD {d}", ha="center",
                va="bottom" if above else "top", fontsize=9.6, color=col)
    pkt(1.4, 8.0, bx0 - 0.1, 7.6, BLUE, 1, "192.168.0.23:50000", "128.119.40.186:80")
    pkt(bx1 + 0.1, 7.6, 19.6, 5.9, BLUE, 2, "138.76.29.7:5001", "128.119.40.186:80")
    pkt(1.4, 3.0, bx0 - 0.1, 3.4, GREEN, 3, "192.168.0.57:50000", "128.119.40.186:80", above=False)
    pkt(bx1 + 0.1, 3.4, 19.6, 5.1, GREEN, 4, "138.76.29.7:5002", "128.119.40.186:80", above=False)
    return fig


FIGS_C = [("C1", fig_C1), ("C2", fig_C2), ("C3", fig_C3), ("C4", fig_C4), ("C5", fig_C5),
          ("C6", fig_C6), ("C7", fig_C7), ("C8", fig_C8), ("C9", fig_C9)]


def checks_C():
    # 문제 1: 단편화
    segA, segB, segC = C_path_frag(C_P1_DATA, C_P1_MTU)
    assert segA == [(1480, 0, 0, 1500)]
    assert (1006 - 20) // 8 * 8 == 984 and (576 - 20) // 8 * 8 == 552
    assert segB == [(984, 0, 1, 1004), (496, 123, 0, 516)]
    assert segC == [(552, 0, 1, 572), (432, 69, 1, 452), (496, 123, 0, 516)]
    assert 69 * 8 == 552 and 123 * 8 == 984
    assert sum(t for *_, t in segC) == 1540 and 1540 - 1500 == 40
    assert sum(t for *_, t in segB) == 1520
    st = C_reassemble([segC[2], segC[0], segC[1]])
    assert [s[1] for s in st] == [1480, 1480, 1480] and [s[2] for s in st] == [False, False, True]
    assert C_reassemble([segC[2], segC[0]])[-1][2] is False          # 가운데 조각이 사라지면 끝나지 않음
    # 문제 2: 전달과 ARP
    hops, arp = C_deliver("A", "201.10.4.20")
    assert [(h[0], h[2], h[3], h[4], h[5], h[6]) for h in hops] == [
        ("A", "201.10.1.1", 1, "00-0A", "01-01", 64), ("R1", "201.10.2.2", 2, "01-02", "02-02", 63),
        ("R2", "201.10.3.3", 3, "02-03", "03-03", 62), ("R3", "201.10.4.20", 4, "03-04", "00-0B", 61)]
    assert [h[1] for h in hops] == ["0.0.0.0/0", "201.10.4.0/24", "201.10.4.0/24", "201.10.4.0/24"]
    assert all(h[8] for h in hops)                                     # 네 랜에서 한 번씩 ARP
    assert [h[7] for h in hops] == ["c730", "c830", "c930", "ca30"]
    for ttl in (64, 63, 62, 61):
        assert C_checksum(C_header(ttl)) == 0                           # 체크섬 칸을 넣고 더하면 검사 통과
    h64, h61 = C_header(64), C_header(61)
    assert [i for i in range(20) if h64[i] != h61[i]] == [8, 10]   # TTL 바이트와 체크섬 앞 바이트만 다르다
    assert arp["R1"] == {"201.10.1.10": "00-0A", "201.10.2.2": "02-02"}
    assert arp["B"] == {"201.10.4.3": "03-04"}
    back, arp2 = C_deliver("B", "201.10.1.10", arp=arp)
    assert not any(h[8] for h in back)                                  # 답장 때는 ARP가 없다
    assert [h[6] for h in back] == [64, 63, 62, 61]
    assert [h[2] for h in back] == ["201.10.4.3", "201.10.3.2", "201.10.2.1", "201.10.1.10"]
    tr, _ = C_deliver("A", "201.10.4.20", ttl0=2)
    assert tr[-1] == ("drop", "R2")
    # 문제 3: 서브넷팅
    al = C_alloc("200.30.40.0", 22, C_DEPTS)
    assert [(a[0], a[2], C_str(a[3]), C_str(a[4]), a[5]) for a in al] == [
        ("개발", 23, "200.30.40.0", "200.30.41.255", 510), ("영업", 24, "200.30.42.0", "200.30.42.255", 254),
        ("연구", 25, "200.30.43.0", "200.30.43.127", 126), ("관리", 26, "200.30.43.128", "200.30.43.191", 62)]
    assert [C_str(C_mask(k)) for k in (23, 24, 25, 26, 22, 21)] == [
        "255.255.254.0", "255.255.255.0", "255.255.255.128", "255.255.255.192", "255.255.252.0", "255.255.248.0"]
    assert C_lpm(C_KTABLE, "200.30.41.7")[0] == "if0"
    assert C_lpm(C_KTABLE, "200.30.43.150")[0] == "if3"
    assert C_lpm(C_KTABLE, "200.30.43.100")[0] == "if2"
    assert C_lpm(C_KTABLE, "200.30.43.200") == ("X", "0.0.0.0/0")
    assert 150 & 192 == 128 and 100 & 128 == 0 and 100 & 192 == 64 and 41 & 254 == 40 and 200 & 192 == 192
    seq, dropped_at = C_loop_hops("200.30.43.200")
    assert len(seq) == 64 and seq[:4] == ["K", "X", "K", "X"]           # TTL 64면 라우터 64곳에서 1씩 줄어 64번째에서 버려짐
    fixed = C_KTABLE[:4] + [("200.30.40.0/22", "drop")] + C_KTABLE[4:]
    assert C_lpm(fixed, "200.30.43.200")[0] == "drop" and C_lpm(fixed, "200.30.43.150")[0] == "if3"
    assert C_lpm(fixed, "8.8.8.8")[0] == "X"
    assert 400 + 200 + 100 + 50 == 750 and round(750 / 1024 * 100) == 73 and round(750 / 65536 * 100, 1) == 1.1
    assert 512 + 256 + 128 + 64 == 960
    assert C_aggregate("200.30.40.0/22", "200.30.44.0/22") == "200.30.40.0/21"
    assert C_aggregate("200.30.44.0/22", "200.30.48.0/22") is None
    assert 40 & 240 == 32 and 40 & 248 == 40 and 44 & 248 == 40 and 45 & 252 == 44
    Z1 = [("200.30.40.0/21", "X"), ("0.0.0.0/0", "up")]
    Z2 = [("200.30.40.0/21", "X"), ("200.30.44.0/22", "W"), ("0.0.0.0/0", "up")]
    assert C_lpm(Z1, "200.30.45.9")[0] == "X" and C_lpm(Z2, "200.30.45.9")[0] == "W"
    assert C_lpm(Z2, "200.30.41.9")[0] == "X" and C_lpm(Z2, "200.30.48.1")[0] == "up"
    assert C_lpm(C_XTABLE, "200.30.43.200")[0] == "K"
    # 문제 4: 단편화 필요와 NAT
    assert C_frag(1480, 0, 0, 1492) == [(1472, 0, 1, 1492), (8, 184, 0, 28)]
    assert 1472 // 8 == 184 and 1492 - 20 == 1472
    table, outs = C_nat([("out", ("192.168.0.23", 50000), ("128.119.40.186", 80)),
                         ("out", ("192.168.0.57", 50000), ("128.119.40.186", 80)),
                         ("in", ("128.119.40.186", 80), ("138.76.29.7", 5002)),
                         ("in", ("128.119.40.186", 80), ("138.76.29.7", 5001)),
                         ("in", ("203.0.113.9", 4444), ("138.76.29.7", 5003))])
    assert table == {5001: ("192.168.0.23", 50000), 5002: ("192.168.0.57", 50000)}
    assert outs[0] == (("138.76.29.7", 5001), ("128.119.40.186", 80))
    assert outs[1] == (("138.76.29.7", 5002), ("128.119.40.186", 80))
    assert outs[2] == (("128.119.40.186", 80), ("192.168.0.57", 50000))
    assert outs[3] == (("128.119.40.186", 80), ("192.168.0.23", 50000))
    assert outs[4] is None                                              # 표에 없는 포트로 먼저 들어오면 버림
    # traceroute: L - G - I1 - I2 - S, 라우터 셋
    path = ["G", "I1", "I2"]
    for ttl in range(1, 5):
        left, who = ttl, None
        for r in path:
            left -= 1
            if left == 0:
                who = r
                break
        assert who == (path[ttl - 1] if ttl <= 3 else None)
    assert 8 * 60 // 2 == 240                                            # 8시간 임대의 절반 = 4시간

# ---------------------------------------------------------------- 파트 D
import math

# ---------------------------------------------------------------------
# 4부(종합 시나리오)·5부(헷갈리는 짝)·공식표 계산 도구. 이름은 모두 D_로 시작한다.
# ---------------------------------------------------------------------


def D_ip(s):
    a = [int(x) for x in s.split(".")]
    return (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]


def D_str(n):
    return ".".join(str((n >> s) & 255) for s in (24, 16, 8, 0))


def D_mask(k):
    return 0 if k == 0 else (0xFFFFFFFF << (32 - k)) & 0xFFFFFFFF


def D_frag(data, mtu, h=20):
    """데이터 data바이트(Offset 0, MF 0)를 MTU mtu에 맞게 자른다. [(데이터, Offset 칸, MF, Total Length)]"""
    if h + data <= mtu:
        return [(data, 0, 0, h + data)]
    r = (mtu - h) // 8 * 8
    out, done = [], 0
    while done < data:
        d = min(r, data - done)
        out.append((d, done // 8, 0 if done + d == data else 1, h + d))
        done += d
    return out


def D_lookup(table, dst):
    """table: [(번호, 마스크 길이, 다음 홉)]. 최장 접두사 일치로 다음 홉을 고른다."""
    best = None
    for net, k, hop in table:
        if D_ip(dst) & D_mask(k) == D_ip(net):
            if best is None or k > best[0]:
                best = (k, hop)
    return best[1] if best else None


# 문제 2의 라우터 R 표
D_R_TABLE = [("203.0.113.0", 26, "인터페이스 1 (1층)"),
             ("203.0.113.64", 26, "인터페이스 2 (2층)"),
             ("203.0.113.128", 26, "인터페이스 3 (3층)"),
             ("0.0.0.0", 0, "ISP 라우터")]

# 5부 숨은·노출 노드 문제의 위치(m)와 전파가 닿는 거리
D_POS = {"A": 0, "P": 20, "C": 40, "D": 60, "Q": 85}
D_RANGE = 30


def D_hears(a, b):
    return abs(D_POS[a] - D_POS[b]) <= D_RANGE


def D_nat_run():
    """공유기 G의 NAT. 안에서 나갈 때 줄을 만들고, 밖에서 올 때 줄을 찾는다."""
    G = "203.0.113.7"
    table, nxt, log = {}, [5001], []

    def out(src, dst):
        key = None
        for g, v in table.items():
            if v == src:
                key = g
        if key is None:
            key = nxt[0]
            nxt[0] += 1
            table[key] = src
        return (G, key), dst

    def inn(src, dst):
        if dst[0] != G or dst[1] not in table:
            return None
        return src, table[dst[1]]

    log.append(out(("192.168.0.23", 50000), ("198.51.100.80", 80)))
    log.append(inn(("198.51.100.80", 80), (G, 5001)))
    log.append(out(("192.168.0.31", 50000), ("198.51.100.80", 80)))
    log.append(inn(("198.51.100.80", 80), (G, 5002)))
    log.append(inn(("192.0.2.9", 40000), (G, 8080)))
    return table, log


# ---------------------------------------------------------------------
# 그림 도구
# ---------------------------------------------------------------------

def D_box(ax, x, y, w, h, text, color, fs=10, fill=0.12, lw=1.4, tc=None):
    ax.add_patch(FancyBboxPatch((x - w / 2, y - h / 2), w, h, boxstyle="round,pad=0.02,rounding_size=0.08",
                                fc=matplotlib.colors.to_rgba(color, fill), ec=color, lw=lw, zorder=3))
    ax.text(x, y, text, ha="center", va="center", fontsize=fs, color=tc or INK, zorder=4)


def D_wavy(ax, x0, y0, x1, y1, color, n=7, amp=0.07):
    L = math.hypot(x1 - x0, y1 - y0)
    ux, uy = (x1 - x0) / L, (y1 - y0) / L
    px, py = -uy, ux
    xs, ys = [], []
    for i in range(201):
        t = i / 200
        s = amp * math.sin(2 * math.pi * n * t)
        xs.append(x0 + ux * L * t + px * s)
        ys.append(y0 + uy * L * t + py * s)
    ax.plot(xs, ys, color=color, lw=1.6, zorder=2)


def D_stack(ax, x, y, used, w=0.42, h=0.2):
    """노드가 처리하는 층. used: 아래에서부터 물리, 링크, IP, 포트 가운데 쓰는 층 수"""
    names = ["물리", "링크", "IP", "포트"]
    for i, nm in enumerate(names):
        on = i < used
        ax.add_patch(Rectangle((x - w / 2, y + i * h), w, h, fc=matplotlib.colors.to_rgba(PURPLE, 0.55 if on else 0.0),
                               ec=INK, lw=0.7, zorder=3))
        ax.text(x + w / 2 + 0.05, y + i * h + h / 2, nm, ha="left", va="center", fontsize=9.5, color=INK)


def fig_D1():
    fig, ax = plt.subplots(figsize=(8.8, 3.9))
    ax.set_xlim(0, 11.4)
    ax.set_ylim(-0.3, 3.65)
    ax.axis("off")
    # 무선 다중 접근 범위
    ax.add_patch(FancyBboxPatch((0.12, 1.0), 2.5, 2.3, boxstyle="round,pad=0.02,rounding_size=0.3",
                                fc="none", ec=BLUE, ls="--", lw=1.1, zorder=1))
    ax.text(1.75, 3.5, "무선 다중 접근 링크 (한 채널을 함께 씀)", ha="center", va="center", fontsize=9.5, color=BLUE)
    # 노드
    D_box(ax, 0.75, 2.45, 0.95, 0.42, "노트북 L", GREEN)
    D_box(ax, 0.75, 1.45, 0.95, 0.42, "휴대폰 P", GREEN)
    ax.text(0.75, 2.78, "192.168.0.23", ha="center", va="bottom", fontsize=9.5, color=INK)
    ax.add_patch(FancyBboxPatch((2.45, 1.2), 1.55, 1.8, boxstyle="round,pad=0.02,rounding_size=0.1",
                                fc=matplotlib.colors.to_rgba(ORANGE, 0.10), ec=ORANGE, lw=1.4, zorder=3))
    ax.text(3.22, 2.8, "공유기 G", ha="center", va="center", fontsize=10.5, color=INK, zorder=4)
    for i, t in enumerate(["AP·스위치", "라우터 (IP)", "NAT (포트)", "DHCP 서버"]):
        ax.text(3.22, 2.48 - i * 0.3, t, ha="center", va="center", fontsize=9.5, color=INK, zorder=4)
    ax.text(3.22, 1.05, "안 192.168.0.1", ha="center", va="top", fontsize=9.5, color=INK)
    ax.text(3.22, 0.78, "밖 203.0.113.7", ha="center", va="top", fontsize=9.5, color=INK)
    D_wavy(ax, 1.25, 2.4, 2.43, 2.2, BLUE)
    D_wavy(ax, 1.25, 1.5, 2.43, 1.75, BLUE)
    D_box(ax, 5.8, 2.1, 1.0, 0.55, "ISP 라우터\nR1", PURPLE, fs=9.5)
    D_box(ax, 8.0, 2.1, 1.0, 0.55, "라우터\nR2", PURPLE, fs=9.5)
    D_box(ax, 10.5, 2.1, 1.05, 0.5, "웹 서버 S", GREEN)
    ax.text(10.5, 2.42, "198.51.100.80", ha="center", va="bottom", fontsize=9.5, color=INK)
    # 유선 링크
    for x0, x1, col, top, bot in [(4.02, 5.28, INK, "점대점", "MTU 1,492"), (6.32, 7.48, INK, "점대점", "MTU 1,500"),
                                  (8.52, 9.95, GOLD, "이더넷 LAN", "MTU 1,500")]:
        ax.plot([x0, x1], [2.1, 2.1], color=col, lw=2.2, zorder=2)
        ax.text((x0 + x1) / 2, 2.2, top, ha="center", va="bottom", fontsize=9.5, color=col)
        ax.text((x0 + x1) / 2, 2.0, bot, ha="center", va="top", fontsize=9.5, color=INK)
    # 층 그림
    for x, used in [(0.62, 4), (3.1, 4), (5.67, 3), (7.87, 3), (10.37, 4)]:
        D_stack(ax, x, -0.25, used)
    ax.text(4.55, 0.1, "칠한 층까지\n열어 본다", ha="center", va="center", fontsize=9.5, color=PURPLE)
    return fig


def fig_D2():
    fig, ax = plt.subplots(figsize=(8.4, 5.0))
    ax.set_xlim(0, 10.35)
    ax.set_ylim(-0.3, 8.4)
    ax.axis("off")
    xL, xG = 0.9, 4.2
    ax.plot([xL, xL], [0, 7.7], color=INK, lw=1.2)
    ax.plot([xG, xG], [0, 7.7], color=INK, lw=1.2)
    ax.text(xL, 8.0, "노트북 L", ha="center", fontsize=10.5, color=INK)
    ax.text(xG, 8.0, "공유기 G", ha="center", fontsize=10.5, color=INK)
    ax.annotate("", xy=(0.25, 0.1), xytext=(0.25, 7.6), arrowprops=dict(arrowstyle="-|>", color=INK, lw=1))
    ax.text(0.12, 3.9, "시간", rotation=90, ha="center", va="center", fontsize=9.5, color=INK)
    msgs = [
        ("① DISCOVER", True, True, "0.0.0.0 → 255.255.255.255 \"설정 주세요\""),
        ("② OFFER", False, False, "\"192.168.0.23을 2시간 빌려줄게요\""),
        ("③ REQUEST", True, True, "\"그 제안을 받겠습니다\""),
        ("④ ACK", False, False, ".23/24, 기본 라우터 .1, DNS, 임대 2시간"),
        ("⑤ ARP 요청", True, True, "\"192.168.0.1의 MAC 주소는?\""),
        ("⑥ ARP 응답", False, False, "G가 자기 MAC을 한 명(L)에게"),
        ("⑦ 웹 요청", True, False, "IP 목적지 = S, 프레임 목적지 = G의 MAC"),
    ]
    y = 7.4
    for name, l2g, bcast, note in msgs:
        col = ORANGE if bcast else BLUE
        y0, y1 = y, y - 0.55
        if l2g:
            ax.annotate("", xy=(xG, y1), xytext=(xL, y0), arrowprops=dict(arrowstyle="-|>", color=col, lw=1.6))
        else:
            ax.annotate("", xy=(xL, y1), xytext=(xG, y0), arrowprops=dict(arrowstyle="-|>", color=col, lw=1.6))
        ax.text((xL + xG) / 2, (y0 + y1) / 2 + 0.17, name, ha="center", va="bottom", fontsize=9.5, color=col,
                rotation=-9 if l2g else 9)
        ax.text(xG + 0.25, (y0 + y1) / 2, note, ha="left", va="center", fontsize=9.5, color=INK)
        y -= 1.05
    # 묶음 괄호
    for (ya, yb, lab) in [(7.45, 3.7, "DHCP: 주소와 설정 받기"), (3.25, 1.55, "ARP: 다음 홉 MAC")]:
        ax.plot([9.85, 9.95, 9.95, 9.85], [ya, ya, yb, yb], color=PURPLE, lw=1.1)
        ax.text(10.12, (ya + yb) / 2, lab, rotation=90, ha="center", va="center", fontsize=9.5, color=PURPLE)
    ax.text(xG + 0.25, -0.05, "주황 = 방송, 파랑 = 한 명에게", ha="left", va="center", fontsize=9.5, color=INK)
    return fig


def D_building(ax, router):
    ax.set_xlim(0, 10.4)
    ax.set_ylim(-0.05, 5.05)
    ax.axis("off")
    floors = [(4.05, "3층"), (2.65, "2층"), (1.25, "1층")]
    subnets = ["203.0.113.128/26", "203.0.113.64/26", "203.0.113.0/26"]
    rif = [".129", ".65", ".1"]
    if not router:
        ax.add_patch(FancyBboxPatch((0.25, 0.3), 8.25, 4.3, boxstyle="round,pad=0.02,rounding_size=0.15",
                                    fc=matplotlib.colors.to_rgba(ORANGE, 0.08), ec=ORANGE, lw=1.1, zorder=0))
        ax.text(0.3, 4.8, "주황 칸 = 방송이 닿는 범위: 하나 (PC 60대 + R0). 주소는 모두 203.0.113.0/24",
                ha="left", va="center", fontsize=9.5, color=ORANGE)
    for i, (y, name) in enumerate(floors):
        if router:
            ax.add_patch(FancyBboxPatch((0.28, y - 0.46), 6.55, 1.15, boxstyle="round,pad=0.02,rounding_size=0.12",
                                        fc=matplotlib.colors.to_rgba(ORANGE, 0.08), ec=ORANGE, lw=1.1, zorder=0))
            ax.text(1.3, y + 0.53, "서브넷 " + subnets[i], ha="left", va="center", fontsize=9.5, color=ORANGE)
        ax.add_patch(FancyBboxPatch((0.4, y - 0.36), 6.3, 0.72, boxstyle="round,pad=0.02,rounding_size=0.1",
                                    fc="none", ec=BLUE, ls="--", lw=1.0, zorder=1))
        ax.text(0.55, y + 0.1, name, ha="left", va="center", fontsize=10, color=INK)
        ax.plot([0.55, 6.7], [y - 0.15, y - 0.15], color=INK, lw=2.0, zorder=2)
        for k in range(4):
            xx = 1.55 + k * 0.8
            ax.plot([xx, xx], [y - 0.15, y + 0.02], color=INK, lw=1)
            ax.add_patch(Rectangle((xx - 0.17, y + 0.02), 0.34, 0.2, fc=matplotlib.colors.to_rgba(GREEN, 0.35),
                                   ec=GREEN, lw=1, zorder=3))
        ax.text(4.75, y + 0.1, "… PC 20대", ha="center", va="center", fontsize=9.5, color=INK)
        ax.plot([6.7, 7.4], [y - 0.15, 2.65], color=INK, lw=1.6, zorder=2)
        ax.text(7.2, y - 0.15 + [0.1, 0.28, -0.3][i],
                ("포트 " + str(3 - i)) if not router else rif[i], ha="center", fontsize=9.5, color=INK)
    if router:
        D_box(ax, 7.85, 2.65, 0.95, 0.65, "라우터\nR", PURPLE, fs=10)
        ax.plot([8.33, 9.3], [2.65, 2.65], color=INK, lw=1.8)
        D_box(ax, 9.75, 2.65, 0.85, 0.5, "ISP", INK, fs=10)
        ax.text(0.3, 4.85, "주황 칸 = 방송이 닿는 범위 (층마다 하나)   파랑 점선 = 충돌 도메인 (층마다 하나)",
                ha="left", va="center", fontsize=9.5, color=INK)
        ax.text(0.3, 0.3, "층마다 허브 하나에 PC 20대 (공유 10 Mbps)", ha="left", va="center", fontsize=9.5, color=INK)
    else:
        D_box(ax, 7.85, 2.65, 0.95, 0.65, "브리지", BLUE, fs=10)
        # R0는 1층 버스에 붙는다
        ax.plot([6.2, 6.2], [1.1, 0.78], color=INK, lw=1.4)
        D_box(ax, 6.2, 0.62, 0.7, 0.34, "R0", PURPLE, fs=9.5)
        ax.text(5.78, 0.62, ".254", ha="right", va="center", fontsize=9.5, color=INK)
        ax.plot([6.56, 9.3], [0.62, 0.62], color=INK, lw=1.6)
        D_box(ax, 9.75, 0.62, 0.85, 0.42, "ISP", INK, fs=10)
        ax.text(9.5, 4.2, "파랑 점선 =\n충돌 도메인\n(층마다 하나)", ha="center", va="top", fontsize=9.5, color=BLUE)
        ax.text(0.45, 0.48, "층마다 허브 하나에 PC 20대 (공유 10 Mbps)", ha="left", va="center", fontsize=9.5, color=INK)


def D_table(ax, header, rows, widths, hl, row_h=0.5, fs=9.5):
    """header: 열 이름, rows: 줄 목록, widths: 열 너비, hl: 칠할 (줄, 열) 모음"""
    W = sum(widths)
    H = row_h * (len(rows) + 1)
    ax.set_xlim(-0.05, W + 0.05)
    ax.set_ylim(-0.05, H + 0.05)
    ax.axis("off")
    xs = [0]
    for w in widths:
        xs.append(xs[-1] + w)
    for j, t in enumerate(header):
        ax.add_patch(Rectangle((xs[j], H - row_h), widths[j], row_h, fc=matplotlib.colors.to_rgba(BLUE, 0.18),
                               ec=INK, lw=0.7))
        ax.text(xs[j] + widths[j] / 2, H - row_h / 2, t, ha="center", va="center", fontsize=fs, color=INK)
    for i, row in enumerate(rows):
        y = H - row_h * (i + 2)
        for j, t in enumerate(row):
            fc = matplotlib.colors.to_rgba(ORANGE, 0.22) if (i, j) in hl else "none"
            ax.add_patch(Rectangle((xs[j], y), widths[j], row_h, fc=fc, ec=INK, lw=0.7))
            ax.text(xs[j] + widths[j] / 2, y + row_h / 2, t, ha="center", va="center", fontsize=fs, color=INK)


def fig_D3():
    fig, ax = plt.subplots(figsize=(9.6, 4.1))
    header = ["칸", "L → G (무선)", "G → R1 (점대점)", "R1 → R2 (점대점)", "R2 → S (이더넷)", "언제 바뀌나"]
    rows = [
        ["프레임 받는 쪽·보내는 쪽", "G · L", "주소 없음", "주소 없음", "S · R2", "링크마다 새로"],
        ["IP 출발지 주소", "192.168.0.23", "203.0.113.7", "203.0.113.7", "203.0.113.7", "G에서 한 번 (NAT)"],
        ["출발지 포트 (첫 조각에만)", "50000", "5001", "5001", "5001", "G에서 한 번 (NAT)"],
        ["IP 목적지 주소 : 포트", "198.51.100.80:80", "198.51.100.80:80", "198.51.100.80:80",
         "198.51.100.80:80", "끝까지 그대로"],
        ["TTL", "64", "63", "62", "61", "라우터마다 1 줄어듦"],
        ["헤더 체크섬", "처음 계산", "다시 계산", "다시 계산", "다시 계산", "TTL이 바뀌니 매번"],
        ["Total Length", "1,500", "1,492 / 28", "1,492 / 28", "1,492 / 28", "자를 때만"],
        ["Offset · MF", "0 · 0", "0 · 1 / 184 · 0", "0 · 1 / 184 · 0", "0 · 1 / 184 · 0", "자를 때만"],
        ["Ident · Protocol · Version", "같은 값", "같은 값", "같은 값", "같은 값", "끝까지 그대로"],
    ]
    hl = {(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (2, 2), (4, 2), (4, 3), (4, 4), (5, 2), (5, 3), (5, 4),
          (6, 2), (7, 2)}
    D_table(ax, header, rows, [2.7, 1.95, 1.95, 1.95, 1.95, 2.15], hl)
    return fig


def fig_D4():
    fig, ax = plt.subplots(figsize=(8.2, 4.2))
    D_building(ax, router=False)
    return fig


def fig_D5():
    fig, ax = plt.subplots(figsize=(8.2, 4.2))
    D_building(ax, router=True)
    return fig


def fig_D6():
    fig, ax = plt.subplots(figsize=(8.2, 3.4))
    ax.set_xlim(-36, 122)
    ax.set_ylim(-42, 38)
    ax.set_aspect("equal")
    ax.axis("off")
    for name, col in [("A", BLUE), ("C", ORANGE), ("D", GREEN)]:
        ax.add_patch(Circle((D_POS[name], 0), D_RANGE, fc="none", ec=col, ls="--", lw=1.2))
    ax.text(-27, 27, "A가 닿는 곳", color=BLUE, fontsize=9.5, ha="center", va="center")
    ax.text(D_POS["C"], 32, "C가 닿는 곳", color=ORANGE, fontsize=9.5, ha="center", va="bottom")
    ax.text(106, 20, "D가 닿는 곳", color=GREEN, fontsize=9.5, ha="center", va="center")
    for name, x in D_POS.items():
        ap = name in "PQ"
        ax.add_patch(Circle((x, 0), 3.2, fc=matplotlib.colors.to_rgba(PURPLE if ap else GREEN, 0.5),
                            ec=PURPLE if ap else GREEN, lw=1.2, zorder=3))
        ax.text(x, 5.0, name, ha="center", va="bottom", fontsize=10.5, color=INK, zorder=4)
    ax.plot([0, 100], [-34, -34], color=INK, lw=1)
    for m in (0, 20, 40, 60, 85):
        ax.plot([m, m], [-35.5, -32.5], color=INK, lw=1)
        ax.text(m, -38, f"{m} m", ha="center", va="top", fontsize=9.5, color=INK)
    ax.text(121, -38, "보라 P, Q = 공유기", ha="right", va="top", fontsize=9.5, color=PURPLE)
    return fig


FIGS_D = [("D1", fig_D1), ("D2", fig_D2), ("D3", fig_D3), ("D4", fig_D4), ("D5", fig_D5), ("D6", fig_D6)]


def checks_D():
    # ---- 4부 문제 1 ----
    # DHCP 임대 2시간: T1 = 50%, T2 = 87.5%
    assert F(1, 2) * 120 == 60 and F(7, 8) * 120 == 105
    # L의 주소와 서버는 다른 네트워크다 (마스크 /24)
    assert D_ip("192.168.0.23") & D_mask(24) == D_ip("192.168.0.0")
    assert D_ip("198.51.100.80") & D_mask(24) != D_ip("192.168.0.0")
    # 1,500바이트 IP 패킷(데이터 1,480)이 MTU 1,492 구간을 만나면
    fr = D_frag(1480, 1492)
    assert fr == [(1472, 0, 1, 1492), (8, 184, 0, 28)], fr
    assert (1492 - 20) // 8 * 8 == 1472 and 1472 // 8 == 184
    # 그 뒤 MTU 1,500 구간은 그대로 지난다
    assert all(tl <= 1500 for _, _, _, tl in fr)
    # 보내는 쪽이 1,492에 맞췄다면 자르지 않는다
    assert D_frag(1472, 1492) == [(1472, 0, 0, 1492)]
    # TTL: G, R1, R2 세 라우터를 지나 서버에서 61
    ttl = [64]
    for _ in ("G", "R1", "R2"):
        ttl.append(ttl[-1] - 1)
    assert ttl == [64, 63, 62, 61]
    # NAT
    table, log = D_nat_run()
    assert log[0] == (("203.0.113.7", 5001), ("198.51.100.80", 80))
    assert log[1] == (("198.51.100.80", 80), ("192.168.0.23", 50000))
    assert log[2] == (("203.0.113.7", 5002), ("198.51.100.80", 80))
    assert log[3] == (("198.51.100.80", 80), ("192.168.0.31", 50000))
    assert log[4] is None                                    # 바깥에서 먼저 온 패킷은 버림
    assert table == {5001: ("192.168.0.23", 50000), 5002: ("192.168.0.31", 50000)}

    # ---- 4부 문제 2 ----
    # /26 블록: 주소 64개, 호스트 62대
    assert 2 ** (32 - 26) == 64 and 2 ** (32 - 26) - 2 == 62 >= 21
    assert D_str(D_mask(26)) == "255.255.255.192"
    for i, net in enumerate(["203.0.113.0", "203.0.113.64", "203.0.113.128", "203.0.113.192"]):
        assert D_ip(net) == D_ip("203.0.113.0") + 64 * i
        assert D_ip(net) & D_mask(26) == D_ip(net)
    # 라우터 인터페이스 주소는 각 서브넷 안
    for ifa, net in [("203.0.113.1", "203.0.113.0"), ("203.0.113.65", "203.0.113.64"),
                     ("203.0.113.129", "203.0.113.128")]:
        assert D_ip(ifa) & D_mask(26) == D_ip(net)
    # 1층 A(.37) → 3층 B(.150)
    assert 37 & 192 == 0 and 150 & 192 == 128
    assert format(37, "08b") == "00100101" and format(150, "08b") == "10010110"
    assert D_ip("203.0.113.150") & D_mask(26) != D_ip("203.0.113.37") & D_mask(26)
    assert D_lookup(D_R_TABLE, "203.0.113.150") == "인터페이스 3 (3층)"
    assert D_lookup(D_R_TABLE, "203.0.113.37") == "인터페이스 1 (1층)"
    assert D_lookup(D_R_TABLE, "198.51.100.80") == "ISP 라우터"
    # 줄마다 AND 결과
    assert [D_str(D_ip("203.0.113.150") & D_mask(k)) for _, k, _ in D_R_TABLE[:3]] == ["203.0.113.128"] * 3
    # 마스크를 /24로 잘못 둔 3층 PC: .37을 같은 네트워크로 본다
    assert D_ip("203.0.113.37") & D_mask(24) == D_ip("203.0.113.150") & D_mask(24)
    # 층마다 PC 20대 → 브리지 시절 방송 하나가 닿는 기기: 59대 PC + R0
    assert 3 * 20 - 1 + 1 == 60 and 20 - 1 + 1 == 20

    # ---- 5부 ----
    # 5-4: /16 → /24 256개, 500대 → /23, 네 /22 → /20
    assert 2 ** (24 - 16) == 256
    assert 2 ** (32 - 23) - 2 == 510 >= 500 and 2 ** (32 - 24) - 2 == 254 < 500
    blocks = [D_ip(f"198.51.{b}.0") for b in (96, 100, 104, 108)]
    assert all(b & D_mask(20) == D_ip("198.51.96.0") for b in blocks)
    assert sum(2 ** (32 - 22) for _ in blocks) == 2 ** (32 - 20)
    assert 96 % 16 == 0 and D_str(D_mask(20)) == "255.255.240.0"
    assert D_ip("198.51.112.0") & D_mask(20) != D_ip("198.51.96.0")
    # 5-6: 위치와 닿는 거리
    assert D_hears("A", "P") and D_hears("C", "P") and not D_hears("A", "C")        # 숨은 노드
    assert D_hears("C", "D") and D_hears("D", "Q")
    assert not D_hears("C", "Q") and not D_hears("D", "P")                          # 노출 노드
    assert D_hears("C", "P")                                                       # P의 CTS를 C가 듣는다
    # 5-7: 1,500바이트 패킷이 MTU 576을 만나면
    assert D_frag(1480, 576) == [(552, 0, 1, 572), (552, 69, 1, 572), (376, 138, 0, 396)]
    # RTS 20바이트 대 데이터 1,500바이트
    assert 1500 // 20 == 75

    # ---- 공식과 표 ----
    assert F(512, 10 ** 7) == F(512, 10 ** 7) and F(512 * 10 ** 6, 10 ** 7) == F(256, 5)        # 51.2 μs
    assert 14 + 46 + 4 == 64 and 64 * 8 == 512 and 14 + 1500 + 4 == 1518
    assert F(512 * 10 ** 6, 10 ** 8) == F(512, 100)                                            # 5.12 μs
    assert F(32 * 10 ** 6, 10 ** 7) == F(16, 5) and F(96 * 10 ** 6, 10 ** 7) == F(48, 5)        # 3.2, 9.6 μs
    assert [2 ** min(n, 10) for n in (1, 2, 3, 10, 12)] == [2, 4, 8, 1024, 1024]
    assert 7 * F(256, 5) == F(1792, 5)                                                         # 358.4 μs
    assert sum(2 ** min(n, 10) - 1 for n in range(1, 16)) == 7151                             # 백오프 최대 합
    assert 5 * 500 == 2500
    assert 2 + 2 + 3 * 6 + 2 == 24                                                              # 802.11 헤더 24
    assert round(5 / 53 * 100, 1) == 9.4 and F(48 * 8, 64000) == F(6, 1000) and 5 + 48 == 53
    assert 15 * 4 == 60 and 2 ** 16 - 1 == 65535 and (2 ** 13 - 1) * 8 == 65528
    assert [(lo, hi) for lo, hi in [(0b00000000, 0b01111111), (0b10000000, 0b10111111), (0b11000000, 0b11011111)]] \
        == [(0, 127), (128, 191), (192, 223)]
    assert [2 ** 7, 2 ** 14, 2 ** 21] == [128, 16384, 2097152]
    assert [D_str(D_mask(k)) for k in (20, 21, 22, 23, 24, 25, 26, 27, 28)] == [
        "255.255.240.0", "255.255.248.0", "255.255.252.0", "255.255.254.0", "255.255.255.0",
        "255.255.255.128", "255.255.255.192", "255.255.255.224", "255.255.255.240"]
    assert [2 ** (32 - k) for k in (20, 21, 22, 23, 24, 25, 26, 27, 28)] == [4096, 2048, 1024, 512, 256, 128, 64, 32, 16]
    assert D_ip("172.16.0.0") & D_mask(12) == D_ip("172.31.255.255") & D_mask(12)
    # 최장 접두사 일치 예
    t = [("210.10.0.0", 20, "X"), ("210.10.12.0", 22, "Z"), ("0.0.0.0", 0, "ISP")]
    assert D_lookup(t, "210.10.15.3") == "Z" and D_lookup(t, "210.10.5.1") == "X" and D_lookup(t, "210.10.20.1") == "ISP"
    # 순서 번호: 3비트
    N = 8
    assert N - 1 == 7 and N // 2 == 4 and 4 + 4 <= N and not (5 + 5 <= N)
    assert all(256 % s == 0 for s in (1, 2, 4, 8, 16, 32, 64, 128)) and 256 % 3 != 0
    # 스위치 성능: 버스 800 Mbps, 초당 10만 개, 64바이트
    assert min(800e6 / 2, 100_000 * 512) == 51.2e6
    # DHCP 메시지 수, ARP 28바이트 → 64바이트 프레임
    assert 28 + 18 == 46 and 14 + 46 + 4 == 64

    # ---- 문서에 새로 나온 숫자 ----
    assert 1472 + 8 == 1480 and 20 + 1472 == 1492 and 20 + 8 == 28 and 1500 <= 2312        # 4-3
    assert 2 ** 16 - 2 == 65534 and 2 ** 8 - 2 == 254                                     # 5-4 (나)
    assert [abs(D_POS[a] - D_POS[b]) for a, b in [("A", "C"), ("A", "P"), ("C", "P"), ("C", "D"),
                                                   ("C", "Q"), ("D", "P"), ("D", "Q")]] == [40, 20, 20, 20, 45, 40, 25]
    assert 1500 > 1400                                                                    # 5-7 (다): DF라 버림
    assert D_frag(1480, 576)[1][1] * 8 == 552 and D_frag(1480, 576)[2][1] * 8 == 1104      # Offset 69, 138
    assert 0x0600 == 1536 and 2347 > 2312 and 24 + 4 == 28                                 # 공식표
    assert 2 ** 4 - 1 == 15 and 2 ** 13 - 1 == 8191                                       # IHL, Offset 칸
    assert 10 * 10 + F(1, 10) == F(1001, 10)                                               # 토큰 100.1 ms 예
    assert 2 ** 26 // 2 ** 24 == 4 and 256 // 64 == 4                                     # /24 → /26 네 개
    assert 20 * 3 == 60


ORDER = ["A1", "A2", "A3", "A4", "A5", "A6", "A7", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "B10", "B11", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "D1", "D2", "D3", "D4", "D5", "D6"]


def save(fig, k):
    fig.savefig(os.path.join(HERE, f"{PREFIX}_fig{k}.svg"), bbox_inches="tight", metadata={"Date": None})
    if os.environ.get("PREVIEW_DIR"):
        fig.savefig(os.path.join(os.environ["PREVIEW_DIR"], f"{PREFIX}_fig{k}.png"), bbox_inches="tight", dpi=110,
                    facecolor="white")
    plt.close(fig)


if __name__ == "__main__":
    funcs = dict(FIGS_A + FIGS_B + FIGS_C + FIGS_D)
    assert set(funcs) >= set(ORDER), set(ORDER) - set(funcs)
    for k, name in enumerate(ORDER, 1):
        save(funcs[name](), k)
    checks_A()
    checks_B()
    checks_C()
    checks_D()
    print("ALL CHECKS PASSED")