# -*- coding: utf-8 -*-
"""2014年度 女子学院 (JG-E0010) の独立検証。主解法 (逆算・比・線分図・角度の追い方・場合分け) とは別経路
(方程式の厳密解・座標・全探索・シミュレーション・立体の座標モデル・境界の線積分) で答えを再計算する。
浮動小数は答えの計算に使わない (Fraction / sympy)。複数空らんの答えは override の表記と同じ文字列に整形して比較する。
Q03 は 3 つの立体を座標で作り、展開図に描かれた面を除いて残る 1 面の形を求めて ①〜⑦ と照合する (図の寸法は概数との整合のみ確認)。"""
from fractions import Fraction as F
import itertools, math
import sympy as sp

CHECKS = {}
R = sp.Rational


def dec(x):
    """Fraction → 厳密な小数表記 (整数ならそのまま)。"""
    x = F(x)
    if x.denominator == 1:
        return str(x.numerator)
    d = x.denominator
    while d % 2 == 0: d //= 2
    while d % 5 == 0: d //= 5
    assert d == 1, x
    ip = x.numerator // x.denominator
    rem = x - ip
    digits = ""
    while rem:
        rem *= 10
        g = rem.numerator // rem.denominator
        digits += str(g)
        rem -= g
    return f"{ip}.{digits}"


def to_frac(e):
    e = sp.nsimplify(e)
    assert e.is_Rational, e
    return F(int(e.p), int(e.q))


# ---------- 大問1 ----------
def q1s1():
    x = sp.symbols("x")
    left = x * R(8, 5) - (R("1.75") - R(5, 12) / R(3, 8)) * R("3.6")
    sol = sp.solve(sp.Eq(left, R(93, 50)), x)
    assert len(sol) == 1
    return to_frac(sol[0])
CHECKS["JG-E0010-Q01-S01"] = {"method": "□ を未知数 x とおいた方程式を sympy で厳密に解く (小数 1.75・3.6 も有理数で扱う)。主解法の逆算とは別経路",
                              "compute": q1s1,
                              "extra": [(lambda: (lambda v: v * F(8, 5) - (F("1.75") - F(5, 12) / F(3, 8)) * F("3.6") == F(93, 50))(q1s1()), "求めた値を元の式に代入して 93/50 になる")]}


def q1s2():
    x = sp.symbols("x", positive=True)                 # AB の長さ
    A, D, E, Fp = (0, 11), (5, 11), (11, 0), (11, 9)
    B = (0, 11 - x)
    s, t = sp.symbols("s t")
    sol = sp.solve([B[0] + s * (Fp[0] - B[0]) - D[0] - t * (E[0] - D[0]), B[1] + s * (Fp[1] - B[1]) - D[1] - t * (E[1] - D[1])], [s, t], dict=True)[0]
    C = (sp.simplify(B[0] + sol[s] * (Fp[0] - B[0])), sp.simplify(B[1] + sol[s] * (Fp[1] - B[1])))   # 直線 BF と直線 DE の交点

    def area(pts):                                      # 反時計回りなら正の符号つき面積 (靴ひも公式)
        return sp.Rational(1, 2) * sum(p[0] * q[1] - q[0] * p[1] for p, q in zip(pts, pts[1:] + pts[:1]))
    s1, s2 = area([A, B, C, D]), area([C, E, Fp])
    roots = [r for r in sp.solve(sp.Eq(s1, s2), x) if r.is_real and 0 < r < 11]
    assert len(roots) == 1, roots
    r = roots[0]
    assert s1.subs(x, r) > 0 and s2.subs(x, r) > 0
    return to_frac(r)
CHECKS["JG-E0010-Q01-S02"] = {"method": "AB = x として B の座標を置き、直線 BF と DE の交点 C を求め、四角形 ABCD と三角形 CEF の面積 (靴ひも公式) を等しいとおいて sympy で解く (主解法の『共通部分を足す』とは別経路)",
                              "compute": q1s2}


def _dirs():
    """正五角形 ABCDE と正六角形 (1 辺 1) を、辺 CD を共有して座標で作る。"""
    pi = sp.pi
    C, D = sp.Matrix([0, 0]), sp.Matrix([1, 0])
    B = C + sp.Matrix([sp.cos(3 * pi / 5), sp.sin(3 * pi / 5)])      # 正五角形の内角 108° → CB の向きは 108°
    A = B + sp.Matrix([sp.cos(pi / 5), sp.sin(pi / 5)])               # B→A は 36° 傾く (外角 72° ずつ回る)
    E = D + sp.Matrix([sp.cos(2 * pi / 5), sp.sin(2 * pi / 5)])
    h = sp.sqrt(3) / 2
    hexv = {"C": C, "D": D, "right": sp.Matrix([R(3, 2), h]), "topR": sp.Matrix([1, 2 * h]), "topL": sp.Matrix([0, 2 * h]), "left": sp.Matrix([-R(1, 2), h])}
    return A, B, C, D, E, hexv


def _angle_deg(u, v):
    """2 つのベクトルのなす角 (度)。cos を厳密に作り、候補の整数度のうち 1 つだけが厳密に一致することを最小多項式で確認する。"""
    cosv = u.dot(v) / (sp.sqrt(u.dot(u)) * sp.sqrt(v.dot(v)))
    cands = [n for n in range(0, 181) if abs(sp.N(cosv - sp.cos(sp.pi * n / 180), 40)) < sp.Float("1e-30")]
    assert len(cands) == 1, cands
    n = cands[0]
    x = sp.Symbol("x")
    assert sp.minimal_polynomial(cosv - sp.cos(sp.pi * n / 180), x) == x      # 差が厳密に 0
    return n


def q1s3():
    A, B, C, D, E, H = _dirs()
    a = _angle_deg(H["left"] - C, B - C)                  # ア: C で 正六角形の左下の辺と辺 CB
    i = _angle_deg(H["topL"] - H["right"], D - H["right"])   # イ: 右端の頂点で 対角線 (左上の頂点へ) と 右下の辺 (D へ)
    u = _angle_deg(H["topL"] - H["right"], B - A)           # ウ: 対角線と直線 BA の交点で、左上の頂点へ向かう線と B へ向かう線
    e = _angle_deg(H["topL"] - H["topR"], B - A)            # エ: 直線 BA が上の辺と交わる点で、上の辺の左向きと A (B) へ向かう向き
    return f"ア {a}, イ {i}, ウ {u}, エ {e}"


def q1s3_pentagon():
    A, B, C, D, E, H = _dirs()
    side = lambda p, q: sp.simplify((p - q).dot(p - q))
    return all(side(p, q) == 1 for p, q in [(A, B), (B, C), (C, D), (D, E), (E, A)])      # 正五角形の 5 辺はすべて 1 (座標の作り方の確認)


def q1s3_crossing():
    """直線 BA の延長が正六角形の上の辺 (0 < x < 1) と交わり、対角線との交点 X が B と A の間 (A の手前) にあることを確認 (図の読み取りの裏づけ)。
    任意精度の数値 (sympy の N) で連立方程式 B + s(A−B) = TL + r(RT−TL) を解く。真偽の判定だけに使う。"""
    A, B, C, D, E, H = _dirs()
    N = lambda m: sp.Matrix([sp.N(c, 30) for c in m])
    A_, B_, TL, RT = N(A), N(B), N(H["topL"]), N(H["right"])
    t = (TL[1] - B_[1]) / (A_[1] - B_[1])
    px = B_[0] + t * (A_[0] - B_[0])                       # 直線 BA の延長と上の辺 (y = √3) の交点の x 座標
    M = sp.Matrix([[(A_ - B_)[0], -(RT - TL)[0]], [(A_ - B_)[1], -(RT - TL)[1]]])
    s, r = M.LUsolve(TL - B_)
    return bool(0 < px < 1) and bool(0 < s < 1) and bool(0 < r < 1)


CHECKS["JG-E0010-Q01-S03"] = {"method": "正五角形・正六角形 (1 辺 1) を辺 CD を共有して sympy の厳密な座標で作り、4 つの角を『2 本の線の方向ベクトルのなす角』として cos を厳密に求め、整数度と最小多項式で一致を確認 (主解法の角度の追い方とは別経路)",
                              "compute": q1s3, "expect": "ア 12, イ 90, ウ 66, エ 36", "official_value": "ア 12, イ 90, ウ 66, エ 36",
                              "extra": [(q1s3_pentagon, "座標で作った正五角形の 5 辺がすべて長さ 1 (正五角形になっている)"),
                                        (q1s3_crossing, "直線 BA の延長が上の辺の内側で交わり、対角線との交点が B と A の間にある (図の読み取りと矛盾しない)")]}


def q1s4():
    S = [30, 37, 38, 41, 42, 49]
    sset = set(S)
    sols = []
    # 4 数 a<b<c<d を −60〜120 の範囲で全探索。範囲に漏れがない理由: 2 数の和はすべて 30〜49 なので、b ≥ 16 (b ≤ 15 なら a+b ≤ 29)、c ≥ 17、
    # したがって d ≤ 49 − 17 = 32、a ≥ 30 − b ≥ 30 − 31 = −1。実際の取りうる範囲は −1〜32 で、探索範囲はそれより十分広い。途中で 2 数の和が S に入るものだけ進める。
    for a in range(-60, 121):
        for b in range(a + 1, 121):
            if a + b not in sset: continue
            for c in range(b + 1, 121):
                if a + c not in sset or b + c not in sset: continue
                for d in range(c + 1, 121):
                    if sorted([a + b, a + c, a + d, b + c, b + d, c + d]) == S:
                        sols.append((a, b, c, d))
    assert len(sols) == 1, sols
    a, b, c, d = sols[0]
    return f"{a + d}, {a}, {b}, {c}, {d}"
CHECKS["JG-E0010-Q01-S04"] = {"method": "異なる 4 整数 a<b<c<d を全探索し、6 つの 2 数の和が与えられた 6 個と一致する組を探す (解の一意性も確認)。主解法 (大小関係の整理・合計 ÷ 3) とは別経路",
                              "compute": q1s4, "expect": "38, 13, 17, 24, 25", "official_value": "38, 13, 17, 24, 25"}


def q1s5():
    d, v = sp.symbols("d v", positive=True)            # d = 片道の道のり、v = 姉の分速
    sol = sp.solve(sp.Eq(d / 80 + d / 60, 2 * d / v), v)
    assert len(sol) == 1
    return to_frac(sol[0])
CHECKS["JG-E0010-Q01-S05"] = {"method": "片道を文字 d として、妹の往復の時間 = 姉の往復の時間の方程式を sympy で解く (d が約分で消える)。主解法の『片道 240m と仮定』とは別経路",
                              "compute": q1s5,
                              "extra": [(lambda: F(2 * 240) / q1s5() == F(240, 80) + F(240, 60), "片道 240m で姉の往復の時間 = 妹の往復の時間 (3 + 4 = 7 分)")]}


# ---------- 大問2 ----------
def q2():
    sols = []
    # ゲーム機の値段 (円) を 1〜100000 で全探索。最後に残る金額は P の 1 次式で P とともに増えるので (P/40 − 35)、解は高々 1 つ。探索はその確認と値の取得。
    for P in range(1, 100001):
        a1 = F(P, 2) - 500                                       # A が最初に払う額
        r1 = P - a1                                              # 残り
        b = F(3, 4) * r1 + 300                                   # B
        r2 = r1 - b
        if r2 < 0: continue
        c = F(4, 5) * r2                                         # C (残りの 4/5)
        r3 = r2 - c
        if r3 == 300:                                            # 最後に残った 300 円を A が払う
            sols.append((P, a1 + 300, b, c))
    assert len(sols) == 1, sols
    P, a, b, c = sols[0]
    assert a + b + c == P
    return f"値段 {dec(P)}, A {dec(a)}, B {dec(b)}, C {dec(c)}"
CHECKS["JG-E0010-Q02-S01"] = {"method": "ゲーム機の値段 P を 1〜100000 円で全探索し、A (P/2−500)・B (残りの 3/4+300)・C (その残りの 4/5) と払い、最後に 300 円残る P を探す (解の一意性も確認)。主解法の逆算とは別経路",
                              "compute": q2, "expect": "値段 13400, A 6500, B 5700, C 1200", "official_value": "値段 13400, A 6500, B 5700, C 1200"}


# ---------- 大問3: 立体を座標で作り、展開図に描かれていない 1 面の形を求める ----------
s2, s3 = sp.sqrt(2), sp.sqrt(3)


def V(*c):
    return sp.Matrix([sp.nsimplify(x) if not isinstance(x, sp.Basic) else x for x in c])


def dist(p, q):
    return sp.simplify(sp.sqrt(((p - q).T * (p - q))[0]))


class Solid:
    def __init__(self, verts, faces):
        self.verts, self.faces = verts, faces            # 頂点名 → 座標、面名 → 頂点名の並び (周の順)

    def edges_of(self, f):
        vs = self.faces[f]
        return [frozenset((vs[i], vs[(i + 1) % len(vs)])) for i in range(len(vs))]

    def neighbor(self, f, edge):
        for g in self.faces:
            if g != f and edge in self.edges_of(g): return g
        return None

    def is_closed_surface(self):
        cnt = {}
        for f in self.faces:
            for e in self.edges_of(f): cnt[e] = cnt.get(e, 0) + 1
        return all(c == 2 for c in cnt.values()) and len(self.verts) - len(cnt) + len(self.faces) == 2      # どの辺もちょうど 2 面が共有 + オイラーの式

    def elen(self, e):
        a, b = tuple(e)
        return dist(self.verts[a], self.verts[b])

    def sig(self, f):
        return sorted(self.elen(e) for e in self.edges_of(f))            # 辺の長さの並び (形の目印)

    def local_coords(self, f, p, q):
        """面 f を、辺 p→q が (0,0)→(1,0) になるよう長さを |pq| で割って平面に写した座標 (面は y>0 側)。"""
        P, Q = self.verts[p], self.verts[q]
        L = dist(P, Q)
        e1 = (Q - P) / L
        out = []
        for v in self.faces[f]:
            d = self.verts[v] - P
            x = sp.simplify(d.dot(e1) / L)
            perp = d - d.dot(e1) * e1
            out.append((x, sp.simplify(sp.sqrt(perp.dot(perp)) / L)))
        return out

    def unfold(self, root, top_edge, tree):
        """展開図を作る。root の辺 top_edge=(ア, イ) を (0,0)→(1,0) とし root を下 (y<0) に置く。tree = [(子の面, 親の面, 共有辺)] (親が先)。
        子は共有辺をはさんで親の反対側に、実際の長さで置く。戻り値: 面名 → {頂点名: (x, y)}。"""
        p, q = top_edge
        pos = {root: {vn: (x, -y) for vn, (x, y) in zip(self.faces[root], self.local_coords(root, p, q))}}
        for child, parent, edge in tree:
            u, w = tuple(edge)
            U, W = pos[parent][u], pos[parent][w]
            L = sp.sqrt((W[0] - U[0]) ** 2 + (W[1] - U[1]) ** 2)
            e1 = ((W[0] - U[0]) / L, (W[1] - U[1]) / L)
            n = (-e1[1], e1[0])
            cx = sum(pt[0] for pt in pos[parent].values()) / len(pos[parent])
            cy = sum(pt[1] for pt in pos[parent].values()) / len(pos[parent])
            sgn = -1 if (cx - U[0]) * n[0] + (cy - U[1]) * n[1] > 0 else 1        # 親の重心と反対側
            Lm = self.elen(frozenset((u, w)))
            pos[child] = {vn: (sp.simplify(U[0] + x * Lm * e1[0] + sgn * y * Lm * n[0]), sp.simplify(U[1] + x * Lm * e1[1] + sgn * y * Lm * n[1]))
                          for vn, (x, y) in zip(self.faces[child], self.local_coords(child, u, w))}
        return pos


# 図の ①〜⑦ (辺アイ = (0,0)-(1,0) に正規化した理想形) と、図から測った概数 (px; ア・イ・頂点)
CAND = {1: [(0, 0), (1, 0), (1, 1), (0, 1)], 2: [(0, 0), (1, 0), (1, R(1, 2)), (0, R(1, 2))], 3: [(0, 0), (1, 0), (1, s2), (0, s2)],
        4: [(0, 0), (1, 0), (R(1, 2), s3 / 2)], 5: [(0, 0), (1, 0), (R(1, 2), R(1, 2))], 6: [(0, 0), (1, 0), (0, 1)], 7: [(0, 0), (1, 0), (1, 1)]}
CAND_PX = {1: [(86, 366), (276, 366), (276, 180), (86, 180)], 2: [(333, 368), (526, 368), (526, 272), (333, 272)], 3: [(603, 373), (795, 373), (795, 107), (603, 107)],
           4: [(848, 369), (1038, 369), (943, 207)], 5: [(1105, 370), (1295, 370), (1200, 275)], 6: [(1360, 367), (1550, 367), (1360, 182)], 7: [(1612, 365), (1802, 365), (1802, 180)]}


def same_polygon(P, Q):
    if len(P) != len(Q): return False
    has = lambda pt, S: any(sp.simplify(pt[0] - q[0]) == 0 and sp.simplify(pt[1] - q[1]) == 0 for q in S)
    return all(has(p, Q) for p in P) and all(has(q, P) for q in Q)


def which_candidate(poly):
    m = [k for k, c in CAND.items() if same_polygon(poly, c)]
    assert len(m) == 1, m
    return m[0]


def candidates_match_figure():
    """理想形 ①〜⑦ が図の寸法 (概数) と ±0.07 (辺アイを 1 として) で合っている。"""
    for k, pts in CAND_PX.items():
        (x0, y0), (x1, _) = pts[0], pts[1]
        w = x1 - x0
        for (x, y), (cx, cy) in zip(pts, CAND[k]):
            if abs((x - x0) / w - float(sp.N(cx))) > 0.07 or abs((y0 - y) / w - float(sp.N(cy))) > 0.07: return False
    return True


def layout_matches(pos, drawn_faces, measured_px, origin, unit, tol=0.07):
    """展開した頂点の位置が、図から測った頂点の位置 (px。原点 = ア、単位 = 辺アイの長さ) と、どちらの向きにも ±tol で対応する。"""
    pred = [(float(sp.N(x)), float(sp.N(y))) for f in drawn_faces for (x, y) in pos[f].values()]
    meas = [((x - origin[0]) / unit, (origin[1] - y) / unit) for x, y in measured_px]
    near = lambda p, S: any(abs(p[0] - q[0]) <= tol and abs(p[1] - q[1]) <= tol for q in S)
    return all(near(m, pred) for m in meas) and all(near(p, meas) for p in pred)


# ---- Ⓐ: 辺の長さがすべて 1 の正四角すい
SA = Solid({"A0": V(0, 0, 0), "A1": V(1, 0, 0), "A2": V(1, 1, 0), "A3": V(0, 1, 0), "P": V(R(1, 2), R(1, 2), s2 / 2)},
           {"base": ["A0", "A1", "A2", "A3"], "t01": ["P", "A0", "A1"], "t12": ["P", "A1", "A2"], "t23": ["P", "A2", "A3"], "t30": ["P", "A3", "A0"]})
MEAS_A = ((225, 172), 190, [(225, 172), (415, 172), (415, 363), (225, 363), (60, 265), (60, 457), (580, 265)])


def net_A():
    TL, TR, BR, BL = "A3", "A2", "A1", "A0"                                  # 展開図の正方形の左上 (ア)・右上 (イ)・右下・左下 (対称なのでどの割り当てでもよい)
    eL, eR, eT2 = frozenset((BL, TL)), frozenset((TR, BR)), frozenset(("P", BL))
    T1 = SA.neighbor("base", eL)                                             # 正方形の左の辺についた三角形
    Tr = SA.neighbor("base", eR)                                             # 右の辺についた三角形
    T2 = SA.neighbor(T1, eT2)                                                # T1 の下の辺 (頂点 P と左下の角を結ぶ辺) についた三角形
    drawn = {"base", T1, Tr, T2}
    miss = [f for f in SA.faces if f not in drawn]
    assert len(miss) == 1
    M = miss[0]
    assert frozenset((TL, TR)) in SA.edges_of(M)                             # 描かれていない面は辺アイにつく
    pos = SA.unfold("base", (TL, TR), [(T1, "base", eL), (Tr, "base", eR), (T2, T1, eT2)])
    return which_candidate(SA.local_coords(M, TL, TR)), M, drawn, [(pos, drawn)]


# ---- Ⓑ: 底面が直角台形 (平行な辺 1 と 1/2、高さ √3/2、斜めの辺 1) で、柱の高さが 1 の角柱
_P = {"P1": V(0, 0, 0), "P2": V(-1, 0, 0), "P3": V(-R(1, 2), -s3 / 2, 0), "P4": V(0, -s3 / 2, 0)}
_vB = dict(_P)
_vB.update({"Q" + k[1]: v + V(0, 0, 1) for k, v in _P.items()})
SB = Solid(_vB, {"cap0": ["P1", "P2", "P3", "P4"], "cap1": ["Q1", "Q2", "Q3", "Q4"], "l12": ["P1", "P2", "Q2", "Q1"], "l23": ["P2", "P3", "Q3", "Q2"],
                 "l34": ["P3", "P4", "Q4", "Q3"], "l41": ["P4", "P1", "Q1", "Q4"]})
MEAS_B = ((793, 120), 190, [(793, 120), (983, 120), (793, 308), (983, 308), (793, 472), (983, 472), (793, 567), (983, 567), (1143, 210), (1143, 308), (603, 308), (698, 472)])


def net_B():
    lat = [f for f in SB.faces if f.startswith("l")]
    R2 = [f for f in lat if any(sp.simplify(x - s3 / 2) == 0 for x in SB.sig(f))]          # 縦が 約 0.87 の長方形
    R3 = [f for f in lat if any(sp.simplify(x - R(1, 2)) == 0 for x in SB.sig(f))]          # 縦が 半分の長方形
    assert len(R2) == 1 and len(R3) == 1
    R2, R3 = R2[0], R3[0]
    sq = [f for f in lat if f not in (R2, R3)]                                              # 1 × 1 の側面が 2 つ
    R1 = [f for f in sq if any(SB.neighbor(f, e) == R2 for e in SB.edges_of(f))]            # R2 と辺を共有する方が展開図の一番上の正方形
    assert len(R1) == 1
    R1 = R1[0]
    M = [f for f in sq if f != R1][0]
    top = [e for e in SB.edges_of(R1) if SB.neighbor(R1, e) == M]
    assert len(top) == 1
    a, b = tuple(top[0])
    res = {which_candidate(SB.local_coords(M, p, q)) for p, q in ((a, b), (b, a))}         # ア・イの左右は鏡像の違いだけなので両方確かめる
    assert len(res) == 1
    drawn = {R1, R2, R3, "cap0", "cap1"}
    sh12 = [e for e in SB.edges_of(R1) if SB.neighbor(R1, e) == R2][0]
    sh23 = [e for e in SB.edges_of(R2) if SB.neighbor(R2, e) == R3][0]
    layouts = []
    for (aa, bb) in ((a, b), (b, a)):                                                      # ア・イの向きと、右の台形にどちらの底面を使うかの 4 通りを展開する
        for capR, capL in (("cap0", "cap1"), ("cap1", "cap0")):
            eR = [e for e in SB.edges_of(R1) if SB.neighbor(R1, e) == capR][0]
            eL = [e for e in SB.edges_of(R2) if SB.neighbor(R2, e) == capL][0]
            layouts.append((SB.unfold(R1, (aa, bb), [(R2, R1, sh12), (R3, R2, sh23), (capR, R1, eR), (capL, R2, eL)]), drawn))
    return res.pop(), M, drawn, layouts


# ---- Ⓒ: 立方体 (1 辺 1) を、頂点 B, D と上の面の 2 辺の中点を通る平面で切った立体 (頂点 C を含む側)
SC = Solid({"B": V(1, 0, 0), "C": V(1, 1, 0), "D": V(0, 1, 0), "F": V(1, 0, 1), "G": V(1, 1, 1), "H": V(0, 1, 1), "M1": V(R(1, 2), 0, 1), "M2": V(0, R(1, 2), 1)},
           {"bot": ["B", "C", "D"], "sqx": ["B", "C", "G", "F"], "sqy": ["D", "C", "G", "H"], "triy": ["B", "F", "M1"], "trix": ["D", "H", "M2"],
            "top": ["F", "G", "H", "M2", "M1"], "cut": ["B", "D", "M2", "M1"]})
MEAS_C = ((192, 105), 286, [(192, 105), (478, 105), (768, 105), (192, 395), (478, 395), (768, 395), (52, 395), (910, 395), (1110, 368), (1175, 55), (480, 685), (622, 685), (768, 540)])


def net_C():
    sqs = [f for f in SC.faces if len(SC.faces[f]) == 4 and all(sp.simplify(x - 1) == 0 for x in SC.sig(f))]
    assert len(sqs) == 2
    res, last, layouts = set(), None, []
    for Ra, Rb in ((sqs[0], sqs[1]), (sqs[1], sqs[0])):                      # 鏡像 (x と y の入れかえ) の 2 通りを両方確かめる
        shared = [e for e in SC.edges_of(Ra) if SC.neighbor(Ra, e) == Rb][0]  # 2 つの正方形の間の辺 (イから下へのびる辺)
        pent = [f for f in SC.faces if len(SC.faces[f]) == 5][0]              # 五角形の面
        bot_edge = [e for e in SC.edges_of(Rb) if SC.neighbor(Rb, e) == pent][0]    # 右の正方形の下の辺 (五角形がつく)
        bottom_end = list(shared & bot_edge)[0]
        top_end = list(shared - {bottom_end})[0]                              # イ
        top_edge = [e for e in SC.edges_of(Ra) if top_end in e and e != shared][0]  # 左の正方形の上の辺 = 辺アイ
        a_end = list(top_edge - {top_end})[0]                                 # ア
        left_edge = [e for e in SC.edges_of(Ra) if a_end in e and e != top_edge][0]
        left_tri = SC.neighbor(Ra, left_edge)
        assert len(SC.faces[left_tri]) == 3                                   # 左の辺には三角形がついている
        right_edge = [e for e in SC.edges_of(Rb) if SC.neighbor(Rb, e) not in (Ra, pent) and top_end not in e][0]
        right_tri = SC.neighbor(Rb, right_edge)
        assert len(SC.faces[right_tri]) == 3
        hyp = max(SC.edges_of(right_tri), key=lambda e: SC.elen(e) ** 2)      # 三角形の最も長い辺 (斜辺)
        trap = SC.neighbor(right_tri, hyp)
        assert len(SC.faces[trap]) == 4 and trap not in (Ra, Rb)              # 斜辺に台形がついている
        drawn = {Ra, Rb, left_tri, pent, right_tri, trap}
        miss = [f for f in SC.faces if f not in drawn]
        assert len(miss) == 1
        M = miss[0]
        assert SC.neighbor(Ra, top_edge) == M                                 # 描かれていない面は辺アイにつく
        res.add(which_candidate(SC.local_coords(M, a_end, top_end)))
        pos = SC.unfold(Ra, (a_end, top_end), [(left_tri, Ra, left_edge), (Rb, Ra, shared), (pent, Rb, bot_edge), (right_tri, Rb, right_edge), (trap, right_tri, hyp)])
        layouts.append((pos, drawn))
        last = (M, drawn)
    assert len(res) == 1
    return res.pop(), last[0], last[1], layouts


def q3():
    a, b, c = net_A()[0], net_B()[0], net_C()[0]
    return f"Ⓐ {a}, Ⓑ {b}, Ⓒ {c}"


# 図の展開図の各面の寸法 (px の概数。原本 PDF を 4 倍に描画した画像で測った辺の長さ)。第 1 要素は辺アイの長さ。
FIG = {"A": (190, [[190, 190, 191, 191], [189, 192, 191], [192, 190, 192], [189, 192, 191]]),
       "B": (191, [[192, 191, 192, 191], [192, 167, 192, 167], [192, 95, 192, 95], [190, 193, 93, 167], [191, 189, 98, 165]]),
       "C": (191, [[191, 193, 191, 193], [193, 193, 193, 193], [193, 93, 214], [193, 95, 137, 97, 193], [193, 95, 215], [215, 135, 213, 273]])}


def drawn_pieces_match(solid, key, miss_and_drawn):
    """図に描かれた面 (測った辺の長さ) が、立体の面と形 (辺の長さの並び) で ±0.07 (辺アイ = 1) で 1 対 1 に対応し、残る面が M だけになる。"""
    unit, pieces = FIG[key]
    model = {f: [float(sp.N(x)) for x in solid.sig(f)] for f in solid.faces}
    left = set(solid.faces)
    for meas in pieces:
        ms = sorted(m / unit for m in meas)
        hit = [f for f in sorted(left) if len(model[f]) == len(ms) and all(abs(a - b) <= 0.07 for a, b in zip(model[f], ms))]
        if not hit: return False
        left.discard(hit[0])
    return len(left) == 1 and len(solid.faces) == len(pieces) + 1


def unfolded_layout_matches_figure():
    """立体を展開図の通りに (描かれた面だけ) 展開した頂点の位置が、図から測った頂点の位置と一致する (3 つの展開図とも)。
    Ⓑ は 4 通りの展開のうち少なくとも 1 つ、Ⓒ は 2 通り (鏡像) の両方が一致し、Ⓑ では図と合わない向きの展開が存在する (判別力がある)。"""
    okA = any(layout_matches(pos, dr, MEAS_A[2], MEAS_A[0], MEAS_A[1]) for pos, dr in net_A()[3])
    okB = [layout_matches(pos, dr, MEAS_B[2], MEAS_B[0], MEAS_B[1]) for pos, dr in net_B()[3]]
    okC = [layout_matches(pos, dr, MEAS_C[2], MEAS_C[0], MEAS_C[1]) for pos, dr in net_C()[3]]
    return okA and any(okB) and not all(okB) and all(okC)


CHECKS["JG-E0010-Q03-S01"] = {"method": "Ⓐ (辺がすべて等しい正四角すい)・Ⓑ (底面が直角台形の角柱)・Ⓒ (立方体を 3 点で切った立体) を sympy の座標で作り、展開図に描かれた面と対応させて、"
                              "描かれていない 1 面を辺アイを (0,0)-(1,0) とする平面座標に写し、①〜⑦ の形 (厳密な座標) と照合する。主解法 (辺の長さと頂点に集まる角の対応) とは別経路",
                              "compute": q3, "expect": "Ⓐ 4, Ⓑ 1, Ⓒ 7", "official_value": "Ⓐ 4, Ⓑ 1, Ⓒ 7",
                              "extra": [(lambda: SA.is_closed_surface() and SB.is_closed_surface() and SC.is_closed_surface(), "3 つの立体は、どの辺もちょうど 2 面が共有する閉じた立体 (オイラーの式 V−E+F=2)"),
                                        (candidates_match_figure, "①〜⑦ の理想形が図の寸法 (概数) と ±0.07 で合っている"),
                                        (lambda: drawn_pieces_match(SA, "A", net_A()[1:3]) and drawn_pieces_match(SB, "B", net_B()[1:3]) and drawn_pieces_match(SC, "C", net_C()[1:3]),
                                         "展開図に描かれた各面の寸法 (概数) が立体の面と 1 対 1 に対応し、残る面が 1 つだけになる"),
                                        (unfolded_layout_matches_figure, "立体を図の通りに展開した頂点の位置が、図から測った展開図の頂点の位置と ±0.07 で一致する (Ⓐ・Ⓑ・Ⓒ とも。向きの違う展開は一致しない)")]}


# ---------- 大問4: 水面の高さの差のグラフ → 条件を全探索してシミュレーション ----------
T_STOP, T_RESTART, T_END = 36, 54, 72          # グラフの折れ点の横座標 (分)。縦軸: 差 (mm) の目盛りは (36 分で 90mm)


def _heights(a, b, H, who, t):
    """A は毎分 a mm、B は毎分 b mm。who の容器だけ T_STOP〜T_RESTART の間、注水を止める。高さは満水 H (mm) で止まる。"""
    def one(rate, stopped, t):
        poured = (min(t, T_STOP) + max(0, t - T_RESTART)) if stopped else t
        return min(H, rate * poured)
    return one(a, who == "A", t), one(b, who == "B", t)


def _diff(a, b, H, who, t):
    ha, hb = _heights(a, b, H, who, t)
    return ha - hb


def q4():
    # 探索範囲: 毎分の上昇は 0.5〜20mm (0.5mm きざみ)、容器の高さは 1〜80cm (1cm きざみ)。グラフの折れ点 (36・54・72 分) と差 9cm は整数なので、この刻みで足りる。
    rates = [F(k, 2) for k in range(1, 41)]
    Hs = [F(10 * k) for k in range(1, 81)]                       # 容器の高さ 10〜800mm (1cm きざみ)
    sols = []
    for a in rates:
        for b in rates:
            for who in "AB":
                for H in Hs:
                    d = lambda t: _diff(a, b, H, who, F(t))
                    # グラフの折れ点: d(36) = 9cm = 90mm、d(54) = 0、d(72) = 0
                    if d(T_STOP) != 90 or d(T_RESTART) != 0 or d(T_END) != 0: continue
                    # 0〜36 分は増加、36〜54 分は減少、54〜72 分は山 (正の値) で、72 分以降は 0 のまま
                    if not all(d(t) < d(t + 1) for t in range(0, T_STOP)): continue
                    if not all(d(t) > d(t + 1) for t in range(T_STOP, T_RESTART)): continue
                    seq = [d(t) for t in range(T_RESTART, T_END + 1)]
                    pk = seq.index(max(seq))
                    if not (0 < pk < len(seq) - 1 and all(seq[i] < seq[i + 1] for i in range(pk)) and all(seq[i] > seq[i + 1] for i in range(pk, len(seq) - 1)) and seq[-1] == 0): continue
                    if d(T_END + 20) != 0: continue
                    sols.append((a, b, who, H))
    assert len(sols) == 1, sols
    a, b, who, H = sols[0]
    full = lambda idx: next(F(t, 2) for t in range(0, 400) if _heights(a, b, H, who, F(t, 2))[idx] == H)      # 満水になる最初の時刻 (半分きざみ)
    tA, tB = full(0), full(1)
    assert tA.denominator == 1 and tB.denominator == 1 and 60 <= tA < 120 and 60 <= tB < 120               # 9 時台 (60〜120 分後)
    return f"{dec(a)}, {dec(b)}, {T_STOP}, {who}, {T_RESTART}, {who}, {dec(tA - 60)}, {dec(tB - 60)}, {dec(H / 10)}"
CHECKS["JG-E0010-Q04-S01"] = {"method": "A・B の毎分の上昇 (0.5mm きざみ)、止める容器 (A か B)、容器の高さ (1cm きざみ) の全組み合わせを、グラフの折れ点 (36・54・72 分) と差 (36 分で 90mm) に合うかでふるいにかけ、"
                              "シミュレーションで満水時刻まで求める (解の一意性も確認)。主解法 (傾きの読み取り) とは別経路",
                              "compute": q4, "expect": "7.5, 5, 36, A, 54, A, 6, 12, 36", "official_value": "7.5, 5, 36, A, 54, A, 6, 12, 36"}


# ---------- 大問5: 円の通過部分の面積 → 境界の線積分 (グリーンの定理) ----------
_th, _u = sp.symbols("theta u")


def _line_int(P, Q):
    x, y = P[0] + _u * (Q[0] - P[0]), P[1] + _u * (Q[1] - P[1])
    return sp.integrate(sp.Rational(1, 2) * (x * sp.diff(y, _u) - y * sp.diff(x, _u)), (_u, 0, 1))


def _arc_int(cx, cy, r, a0, a1):
    x, y = cx + r * sp.cos(_th), cy + r * sp.sin(_th)
    return sp.integrate(sp.simplify(sp.Rational(1, 2) * (x * sp.diff(y, _th) - y * sp.diff(x, _th))), (_th, a0, a1))


def _geometry5():
    rad, alpha, r = 12, sp.pi / 6, 1                   # おうぎ形の半径 12、三角定規 (30°-60°-90°) の斜辺 = 12 が壁となす角 = 30°、円の半径 1
    w, hgt = rad * sp.cos(alpha), rad * sp.sin(alpha)  # 垂直な辺の x 座標 (±w) と高さ
    n1, n2 = sp.Matrix([-1, 0]), sp.Matrix([-sp.cos(alpha), sp.sin(alpha)])         # 左の角での外向き法線 (垂直な辺の法線と弧の法線)
    piv = sp.acos(n1.dot(n2))                          # 角で円が回る角 = 2 つの法線のなす角
    return rad, alpha, r, w, hgt, piv


def q5():
    rad, alpha, r, w, hgt, piv = _geometry5()
    pieces = [_line_int((-w, r), (-w, hgt)),                                  # 左の内側 (図形の辺)
              _arc_int(0, 0, rad, sp.pi - alpha, alpha),                       # 内側の弧 (図形の弧、時計回り)
              _line_int((w, hgt), (w, r)),                                     # 右の内側
              _arc_int(w + r, r, r, sp.pi, 2 * sp.pi),                         # 終わりの円の下半分
              _line_int((w + 2 * r, r), (w + 2 * r, hgt)),                     # 右の外側
              _arc_int(w, hgt, 2 * r, 0, piv),                                 # 右の角でまわる弧 (半径 2)
              _arc_int(0, 0, rad + 2 * r, alpha, sp.pi - alpha),               # 外側の大きな弧 (半径 14)
              _arc_int(-w, hgt, 2 * r, sp.pi - piv, sp.pi),                    # 左の角でまわる弧
              _line_int((-w - 2 * r, hgt), (-w - 2 * r, r)),                   # 左の外側
              _arc_int(-w - r, r, r, sp.pi, 2 * sp.pi)]                        # はじめの円の下半分
    area = sp.expand(sp.simplify(sum(pieces)))                                  # 20 + 19π の形
    return to_frac(area.subs(sp.pi, R("3.14")))


def q5_tube():
    """中心の道すじの長さ L を求め、通過面積 = 2rL + πr² (道すじのまわりの幅 2r の帯 + 両端の半円) で確認。"""
    rad, alpha, r, w, hgt, piv = _geometry5()
    L = 2 * (hgt - r) + 2 * piv * r + (sp.pi - 2 * alpha) * (rad + r)
    return to_frac(sp.expand(2 * r * L + sp.pi * r * r).subs(sp.pi, R("3.14"))) == q5()


def q5_grid():
    """通過部分の格子点計数 (近似)。中心の道すじ上に円を並べて塗り、塗られた面積が 20 + 19π にほぼ等しい。浮動小数の目安チェック (答えそのものは境界の積分で厳密に出す)。"""
    import numpy as np
    pi = math.pi
    w, hg = 6 * math.sqrt(3), 6.0
    pts = []
    def line(p, q, step=0.005):
        n = max(2, int(math.dist(p, q) / step)); pts.extend((p[0] + (q[0] - p[0]) * i / n, p[1] + (q[1] - p[1]) * i / n) for i in range(n + 1))
    def arc(c, r, a0, a1, step=0.005):
        n = max(2, int(abs(a1 - a0) * r / step)); pts.extend((c[0] + r * math.cos(a0 + (a1 - a0) * i / n), c[1] + r * math.sin(a0 + (a1 - a0) * i / n)) for i in range(n + 1))
    line((-w - 1, 1), (-w - 1, hg)); arc((-w, hg), 1, pi, pi - pi / 6); arc((0, 0), 13, 5 * pi / 6, pi / 6); arc((w, hg), 1, pi / 6, 0); line((w + 1, hg), (w + 1, 1))
    h = 0.02
    xmin, ymin = -w - 3, -1.0
    nx, ny = int((2 * w + 6) / h), int(16 / h)
    xs, ys = xmin + (np.arange(nx) + 0.5) * h, ymin + (np.arange(ny) + 0.5) * h
    mask = np.zeros((nx, ny), dtype=bool)
    rr = int(1 / h) + 2
    for px, py in pts[::2]:
        ix, iy = int((px - xmin) / h), int((py - ymin) / h)
        x0, x1, y0, y1 = max(0, ix - rr), min(nx, ix + rr + 1), max(0, iy - rr), min(ny, iy + rr + 1)
        dx, dy = xs[x0:x1, None] - px, ys[None, y0:y1] - py
        mask[x0:x1, y0:y1] |= (dx * dx + dy * dy <= 1.0)
    return abs(mask.sum() * h * h - (20 + 19 * pi)) < 0.15


CHECKS["JG-E0010-Q05-S01"] = {"method": "図形の輪郭 (おうぎ形の弧と 30°-60°-90° の三角定規) から、角で円がまわる角を外向き法線のなす角として求め、通過部分の境界 (内側の輪郭・外側の平行線と弧・両端の半円) を 1 周する線積分 "
                              "(グリーンの定理) で面積を厳密に計算する。主解法 (長方形・扇形・半円に分ける) とは別経路",
                              "compute": q5,
                              "extra": [(q5_tube, "中心の道すじの長さ L から 2rL + πr² (幅 2r の帯 + 両端の半円) で求めた面積と一致"),
                                        (q5_grid, "格子点計数 (近似) で通過面積が 20 + 19π (≒ 79.69) にほぼ一致 (±0.15)")]}


# ---------- 大問6: 休憩つきの作業 → 1 個ずつの完成時刻をシミュレーション ----------
def _worked(t, work, rest):
    """時刻 t (分) までに働いた時間。work 分働いて rest 分休むをくり返す (rest = 0 なら休まない)。"""
    if rest == 0: return F(t)
    full, rem = divmod(F(t), work + rest)
    return full * work + min(rem, work)


def _items(t, x=0, discrete=True):
    """A は 0 分から (2 時間働いて 30 分休憩、1 個 2 分)、B と C は x 分から (B は 1 時間 30 分働いて 30 分休憩、1 個 2.5 分、C は休まず 1 個 3 分)。時刻 t までの完成個数。"""
    a = _worked(t, 120, 30) / 2
    tb = F(t) - x
    if tb < 0: return F(math.floor(a)) if discrete else a
    b = _worked(tb, 90, 30) / F(5, 2)
    c = tb / 3
    return F(math.floor(a) + math.floor(b) + math.floor(c)) if discrete else a + b + c


def q6s1():
    t = F(0)
    while _items(t) < 200:                         # 完成時刻はすべて 0.5 分の倍数 (2 分・2.5 分・3 分きざみ) なので 0.5 分きざみで十分
        t += F(1, 2)
    h, m = divmod(t, 60)
    assert m.denominator == 1
    return f"{h}時間 {dec(m)}分"
CHECKS["JG-E0010-Q06-S01"] = {"method": "A (2 分に 1 個)・B (2.5 分に 1 個)・C (3 分に 1 個) の休憩を入れた作業を 0.5 分きざみでシミュレーションし、完成個数が初めて 200 になる時刻を求める。主解法 (3 時間で 195 個 → 残りを完成順に数える) と同じ結果を別の手順 (全時刻の走査) で確認",
                              "compute": q6s1, "expect": "3時間 5分", "official_value": "3時間 5分",
                              "extra": [(lambda: _items(F(369, 2)) == 199 and _items(185) == 200 and _items(180) == 195, "184.5 分で 199 個、180 分 (3 時間) で 195 個、185 分で 200 個")]}


def q6s2():
    T = 212                                        # 3 時間 32 分 = A が作業を始めてから 212 分
    # B・C が作業を始める時刻 x (分後) を 0〜211 で全探索。3 人の個数を『働いた時間 ÷ 1 個の時間』の仕事算 (連続) で数え、合計がちょうど 200 になる x を探す。
    xs = [x for x in range(0, T) if _items(T, x, discrete=False) == 200]
    assert len(xs) == 1, xs                         # C の寄与が x について単調に減るので、連続の仕事算では 1 つに決まる
    return xs[0]


def q6s2_discrete():
    """個数を 1 個ずつ数える離散の読み方では、212 分ちょうどに 200 個目が完成する x は 45・46・47 の 3 つになる (A の 91 個目が 212 分ちょうど)。47 はその 1 つで、3 人の完成が 212 分にそろう。"""
    ok = []
    for x in range(0, T_CHECK):
        t = F(0)
        while t <= 300 and _items(t, x) < 200: t += F(1, 2)
        if t == T_CHECK: ok.append(x)
    return ok == [45, 46, 47] and _items(T_CHECK, 47) == 200 and _items(T_CHECK - F(1, 2), 47) == 197


T_CHECK = 212
CHECKS["JG-E0010-Q06-S02"] = {"method": "B・C が作業を始める時刻 x を 0〜211 分で全探索し、212 分 (3 時間 32 分) の時点での A (休憩を引いた働いた時間 ÷ 2 分)・B (÷ 2.5 分)・C (÷ 3 分) の個数の合計がちょうど 200 になる x を探す。主解法 (A の個数 → 残りを B・C の周期でまとめる) とは別経路",
                              "compute": q6s2,
                              "extra": [(q6s2_discrete, "離散 (1 個ずつ) の読み方でも x = 47 は条件を満たす (3 人とも 212 分ちょうどに 1 個完成して 197 → 200 個)。ただし離散では 45・46 も満たす")]}


# ---------- 大問7: カード → 全順列を探索 ----------
def _q7_solutions():
    """カード k (漢数字 k) の裏の数字 b[k] を 1〜9 の順列として全探索 (9! = 362880 通り)。
    条件: 六 (k=6) の裏は 8、和 k + b[k] は 9 枚ともすべて異なり最小 3・最大 15。
    図: 漢数字が見えているのは 六・七・五・二・四 (その裏は図に出ていない数字)、算用数字が見えているのは 7, 2, 9, 1 の 4 枚 (その裏の漢数字は図に出ていない 一・三・八・九)。"""
    out = []
    for perm in itertools.permutations(range(1, 10)):
        b = dict(zip(range(1, 10), perm))
        if b[6] != 8: continue
        sums = [k + b[k] for k in range(1, 10)]
        if len(set(sums)) != 9 or min(sums) != 3 or max(sums) != 15: continue
        if {b[1], b[3], b[8], b[9]} != {7, 2, 9, 1}: continue       # 一・三・八・九 の裏に、図で見えている 7, 2, 9, 1 が 1 枚ずつ
        out.append(b)
    assert len(out) == 1, out
    return out[0]


def q7s1(): return _q7_solutions()[1]
def q7s2(): return _q7_solutions()[3]
def q7s3(): return _q7_solutions()[5]


def q7_figure_needed():
    """図の情報 (見えている面) を使わないと、条件を満たす並びは複数あって答えが決まらない。"""
    cnt = set()
    for perm in itertools.permutations(range(1, 10)):
        b = dict(zip(range(1, 10), perm))
        if b[6] != 8: continue
        sums = [k + b[k] for k in range(1, 10)]
        if len(set(sums)) == 9 and min(sums) == 3 and max(sums) == 15: cnt.add((b[1], b[3], b[5]))
    return len(cnt) > 1


def q7_sums_ok():
    b = _q7_solutions()
    sums = sorted(k + b[k] for k in b)
    return sums == [3, 6, 8, 9, 10, 12, 13, 14, 15] and sorted(b.values()) == list(range(1, 10))
CHECKS["JG-E0010-Q07-S01"] = {"method": "9 枚の裏の数字を 1〜9 の順列 (362880 通り) で全探索し、六の裏 = 8、和がすべて異なり最小 3・最大 15、図の見えている面 (算用数字 7, 2, 9, 1 は 一・三・八・九 の裏) をすべて満たすものを探す (解の一意性も確認)。主解法 (最小の和・最大の和から絞る) とは別経路",
                              "compute": q7s1, "extra": [(q7_figure_needed, "図の情報を使わないと答えが決まらない (条件を満たす並びが複数ある)"), (q7_sums_ok, "解の 9 つの和は 3, 6, 8, 9, 10, 12, 13, 14, 15 で、裏の数字は 1〜9 を 1 回ずつ使う")]}
CHECKS["JG-E0010-Q07-S02"] = {"method": "同上 (全順列の探索で一意に決まる解の、三の裏)", "compute": q7s2}
CHECKS["JG-E0010-Q07-S03"] = {"method": "同上 (全順列の探索で一意に決まる解の、五の裏)", "compute": q7s3}
