# -*- coding: utf-8 -*-
"""2024年度 第2回 (TOYO-E0017) の独立検証。主解法 (content/TOYO-E0017.py) とは別経路
(全探索・sympy の厳密計算・座標・条件の再代入・幾何的な排除領域の計算) で答えを再計算する。浮動小数は使わない。"""
from fractions import Fraction as F
import itertools, math
import sympy as sp

CHECKS = {}
PI = F(157, 50)   # 3.14 (公式解答は 3.14 で計算)

# ---------------- 大問1 ----------------
def q1s1():
    # 有理数で式をそのまま評価 (左から順のわり算をそのまま適用)
    return F(12) - F(8) / 6 / 4 + F(3) * 2 - 1
CHECKS["TOYO-E0017-Q01-S01"] = {"method": "有理数で式を直接評価 (÷ を左から順に適用)", "compute": q1s1}

def q1s2():
    # 1〜2024 を全探索 (約数は 2024 以下なので漏れなし)
    return sum(1 for d in range(1, 2025) if 2024 % d == 0 and d % 11 == 0)
CHECKS["TOYO-E0017-Q01-S02"] = {"method": "1〜2024 を全探索し、2024 の約数かつ 11 の倍数を数える", "compute": q1s2,
                                "extra": [(lambda: sum(1 for d in range(1, 2025) if 2024 % d == 0) == 16, "2024 の約数は全部で 16 個 (2³×11×23)")]}

def q1s3():
    # はじめの食塩水 x g: 0.05x = 0.07(x − 30) を sympy で解き、蒸発後の重さを返す
    x = sp.Symbol("x", positive=True)
    sol = sp.solve(sp.Eq(sp.Rational(5, 100) * x, sp.Rational(7, 100) * (x - 30)), x)
    assert len(sol) == 1
    return F(str(sol[0])) - 30
CHECKS["TOYO-E0017-Q01-S03"] = {"method": "食塩量の保存を方程式にして sympy で解き、蒸発後の重さを求める", "compute": q1s3,
                                "extra": [(lambda: F(105) * F(5, 100) / F(75) == F(7, 100), "7% の再代入 (105g の食塩 5.25g ÷ 75g)")]}

def q1s4():
    # 硬貨の使用枚数を全探索 (10円 0〜3, 50円 0〜3, 100円 0〜2 = 48 通りで全部) し、金額の集合を作る
    amounts = {10 * a + 50 * b + 100 * c for a in range(4) for b in range(4) for c in range(3)}
    amounts.discard(0)
    return len(amounts)
CHECKS["TOYO-E0017-Q01-S04"] = {"method": "硬貨の枚数の組 48 通りを全探索して金額の集合の大きさを数える (0 円を除く)", "compute": q1s4}

# ---------------- 大問2 ----------------
def q2s1():
    # B, C, D の手 3^3 = 27 通りを全探索。あいこ ⇔ 4 人の出した手の種類が 1 または 3
    n = 0
    for hands in itertools.product("GCP", repeat=3):
        kinds = set(hands) | {"P"}
        if len(kinds) in (1, 3): n += 1
    return n
CHECKS["TOYO-E0017-Q02-S01"] = {"method": "B,C,D の手 27 通りを全探索し『手の種類が 1 または 3』を数える", "compute": q2s1}

def q2s2():
    # 7人がけ x 脚 (1〜20) を全探索。人数 = 7(x−1)+4 = 4(21−x)+1 を満たす x
    sols = [x for x in range(1, 21) if 7 * (x - 1) + 4 == 4 * (21 - x) + 1]
    assert len(sols) == 1, sols
    return sols[0]
CHECKS["TOYO-E0017-Q02-S02"] = {"method": "7人がけの脚数 1〜20 を全探索し、人数の 2 つの表現が一致するものを探す (一意性も確認)", "compute": q2s2}

def q2s3():
    # 半径 r の半円 (中心原点)。D は中心角 60°、E は 30° の位置。色の部分 = x が r/2 から r√3/2 の範囲で弧の下の面積 (厳密積分)
    r, x = sp.symbols("r x", positive=True)
    area = sp.integrate(sp.sqrt(r**2 - x**2), (x, r / 2, r * sp.sqrt(3) / 2))
    area = sp.simplify(area)                       # = pi r² / 12
    area314 = area.subs(sp.pi, sp.Rational(157, 50))
    sol = [s for s in sp.solve(sp.Eq(area314, sp.Rational(942, 100)), r) if s.is_positive]
    assert len(sol) == 1
    return F(str(sol[0]))
CHECKS["TOYO-E0017-Q02-S03"] = {"method": "色の部分を積分で厳密に求め (π r²/12)、π=3.14 で 9.42 となる r を sympy で解く", "compute": q2s3}

def shoelace(pts):
    s = 0
    for (x1, y1), (x2, y2) in zip(pts, pts[1:] + pts[:1]): s += x1 * y2 - x2 * y1
    return s / 2
def q2s4():
    # 一般の平行四辺形 (ななめ a, 高さ h は記号のまま) で座標計算。BF=2, FC=3。E=(a+e,h), G=E+t(F−E), H は AB 上で G と同じ高さ
    a, h, e, t = sp.symbols("a h e t", positive=True)
    A, B, C, D = (a, h), (0, 0), (5, 0), (a + 5, h)
    Ep, Fp = (a + e, h), (2, 0)
    G = (Ep[0] + t * (Fp[0] - Ep[0]), Ep[1] + t * (Fp[1] - Ep[1]))
    H = (a * (1 - t), h * (1 - t))
    s_ABFE = shoelace([A, B, Fp, Ep]); s_EGD = shoelace([Ep, G, D]); s_GFCD = shoelace([G, Fp, C, D])
    sol = sp.solve([sp.Eq(s_ABFE, s_EGD), sp.Eq(s_EGD, s_GFCD)], [e, t], dict=True)
    sol = [s for s in sol if 0 < s[e] < 5 and 0 < s[t] < 1]
    assert len(sol) == 1, sol
    hg = sp.simplify((G[0] - H[0]).subs(sol[0]))
    ratio = sp.nsimplify(hg / 2)                   # HG : BF
    assert ratio.is_Rational
    p, q = sp.fraction(ratio)
    return (int(p), int(q))
CHECKS["TOYO-E0017-Q02-S04"] = {"method": "ななめの平行四辺形を記号座標で置き、面積条件 2 式を sympy で解いて HG:BF を求める (向きによらないことも確認)", "compute": q2s4}

# ---------------- 大問3 ----------------
H_CUP = {"S": 15, "M": 20, "L": 25}
def juice_per_cup(size):
    # 果汁 j, 水 w: j + w = 底面積×(高さ−1), 3j = 7w を sympy で解く
    j, w = sp.symbols("j w", positive=True)
    sol = sp.solve([sp.Eq(j + w, 10 * (H_CUP[size] - 1)), sp.Eq(3 * j, 7 * w)], [j, w])
    return F(str(sol[j]))
CHECKS["TOYO-E0017-Q03-S01"] = {"method": "果汁と水の連立方程式 (和がジュース量、比 7:3) を sympy で解く", "compute": lambda: juice_per_cup("M")}

def q3s2():
    # L の杯数 1〜2000 を全探索 (M=1.5L, S=2.25L が整数で、果汁合計 23520mL)
    js, jm, jl = juice_per_cup("S"), juice_per_cup("M"), juice_per_cup("L")
    sols = []
    for L in range(1, 2001):
        M, S = F(3, 2) * L, F(9, 4) * L
        if M.denominator != 1 or S.denominator != 1: continue
        if js * S + jm * M + jl * L == 23520: sols.append(int(M))
    assert len(sols) == 1, sols
    return sols[0]
CHECKS["TOYO-E0017-Q03-S02"] = {"method": "L の杯数を全探索し、果汁合計が 23.52L になる (一意の) 組から M を求める", "compute": q3s2}

# ---------------- 大問4 ----------------
def dist(t):
    """豊子さんが出発後 t 分 (Fraction) で進んだ道のり。10 分ごとに分速 10, 20, 30, …"""
    t = F(t); d = F(0); k = 1
    while t > 0:
        seg = min(t, F(10)); d += 10 * k * seg; t -= seg; k += 1
    return d
def speed_at(t):
    """時刻 t (出発後 t 分, t>0) に進んでいる速さ (区間 (10(k−1), 10k] は分速 10k)"""
    return 10 * math.ceil(F(t) / 10)
def q4s1():
    # 680m に達する時刻を 1/10 分刻みの全探索 → 道のりは単調増加なので最初に 680 以上になる点で一致を確認
    for n in range(1, 10000):
        t = F(n, 10)
        if dist(t) >= 680:
            assert dist(t) == 680, "680m は刻みの上にあるはず"
            return F(680) / t
CHECKS["TOYO-E0017-Q04-S01"] = {"method": "道のり関数を区間積分で実装し、680m に達する時刻を刻み探索して 680÷時間", "compute": q4s1}

def q4s2():
    # 9/1 の出会い T 分後、9/2 は T+1 分後。和が一定 ⇔ d(T+1) − d(T) = 36×(6−1)。T を 0〜400 分で 1/10 刻みに全探索し、
    # 解となる T すべてで出会い時刻 T+1 の速さが同じ 1 値になることを確認して返す (解は区間 [169,179] に連続して存在する)
    speeds = set(); found = 0
    for n in range(0, 4001):
        T = F(n, 10)
        if dist(T + 1) - dist(T) == 36 * 5:
            found += 1; speeds.add(speed_at(T + 1))
    assert found > 0 and len(speeds) == 1, (found, speeds)
    return speeds.pop()
CHECKS["TOYO-E0017-Q04-S02"] = {"method": "出会い時刻 T を全探索し、道のりの和の不変式 d(T+1)−d(T)=36×5 を満たす T での豊子さんの速さが一意であることを確認", "compute": q4s2}

def q4s3():
    # d(T+1) − d(T) = 36 を厳密に解く。1 分が 1 区間内なら 10k = 36 で不可能。区間境界 b = 10, 20, … をまたぐ場合を全部調べる
    sols = []
    for b in range(10, 400, 10):
        s1, s2 = b, b + 10                       # 境界 b の前後の速さ (分速 b と b+10)
        T = F(36 - s2 + (s2 - s1) * b, s2 - s1)  # s1(b−T) + s2(T+1−b) = 36
        if b - 1 <= T <= b: sols.append(T)
    assert len(sols) == 1, sols
    T = sols[0]
    # 刻み探索でも同じ解だけが見つかることを確認
    grid = [F(n, 10) for n in range(0, 4001) if dist(F(n, 10) + 1) - dist(F(n, 10)) == 36]
    assert grid == [T], grid
    meet = T + 1                                 # 9/4 の出会い (10 時からの分)
    minutes = int(meet); seconds = (meet - minutes) * 60
    assert seconds.denominator == 1
    return f"午前10時{minutes}分{int(seconds)}秒"
CHECKS["TOYO-E0017-Q04-S03"] = {"method": "不変式 d(T+1)−d(T)=36 を区間境界ごとに厳密に解き (一意)、刻み探索とも照合して時刻文字列を作る",
                                "compute": q4s3, "expect": "午前10時30分36秒", "official_value": "午前10時30分36秒"}

# ---------------- 大問5 ----------------
# 黒い円の中心を三角格子 (i, k) → 位置 (6i+3k, 3√3 k) で表す。中心間の距離² = (6Δi+3Δk)² + 27Δk² (整数)。
# 白い円の中心 O は接している黒い円の中心から距離 6 にあり、他の黒い円の中心から距離 6 以上でなければならない。
# 距離 6 の隣 (方向 φ) は φ±60° の開区間を、距離 6√3 の隣 (方向 φ) は φ±30° の開区間を禁止する。距離 12 以上は禁止なし。
ADJ = {(1, 0): 0, (0, 1): 60, (-1, 1): 120, (-1, 0): 180, (0, -1): 240, (1, -1): 300}            # 距離² = 36
SECOND = {(1, 1): 30, (-1, 2): 90, (-2, 1): 150, (-1, -1): 210, (1, -2): 270, (2, -1): 330}      # 距離² = 108
def _check_lattice():
    for (di, dk), _ in ADJ.items(): assert (6 * di + 3 * dk) ** 2 + 27 * dk ** 2 == 36
    for (di, dk), _ in SECOND.items(): assert (6 * di + 3 * dk) ** 2 + 27 * dk ** 2 == 108
_check_lattice()
def path_angle(centers):
    """O が動ける角度の合計 (度, 整数)。各中心について 1° ごとのセルが禁止区間に含まれないものを数える (端点が整数なので厳密)。"""
    cs = set(centers); total = 0
    for (i, k) in cs:
        banned = [False] * 360
        for (di, dk), phi in list(ADJ.items()) + list(SECOND.items()):
            if (i + di, k + dk) not in cs: continue
            w = 60 if (di, dk) in ADJ else 30
            for a in range(360):
                # セル [a, a+1) が開区間 (phi−w, phi+w) (mod 360) に入るか
                lo = (a - (phi - w)) % 360
                if lo + 1 <= 2 * w: banned[a] = True
        total += sum(1 for a in range(360) if not banned[a])
    return total
def path_length(centers):
    return 2 * PI * 6 * F(path_angle(centers), 360)
ROW = [(i, 0) for i in range(100)]
PARA = [(i, k) for k in range(5) for i in range(100)]
CHECKS["TOYO-E0017-Q05-S01"] = {"method": "一列 100 個の中心を格子座標で置き、各中心のまわりで『他の円に食い込まない方向』の角度を幾何的に数えて合計 → 半径 6 の弧の長さ", "compute": lambda: path_length(ROW),
                                "extra": [(lambda: path_angle(ROW) == 360 + 60 * 198, "弧の角度の総和 = 360° + 60°×(乗り移り 198 回)")]}
CHECKS["TOYO-E0017-Q05-S02"] = {"method": "5 段の平行四辺形配置 (500 個) を格子座標で置き、同じ幾何計算で角度を合計 (内部の円は 0°) → 弧の長さ", "compute": lambda: path_length(PARA),
                                "extra": [(lambda: path_angle(PARA) == 360 + 60 * 206, "弧の角度の総和 = 360° + 60°×(周上の円 206 個)")]}

# ---------------- 大問6 ----------------
# 座標: F 原点、x: F→G、y: F→E、z: 上。小立方体 (i,j,k) は [i,i+1]×[j,j+1]×[k,k+1]。
BLACK = {(1, 2, 2), (1, 1, 2), (1, 1, 1), (0, 0, 1), (2, 1, 0)}   # ＜図2＞から読み取り
ALL = [(i, j, k) for i in range(3) for j in range(3) for k in range(3)]
def plane_through(P, Q, R):
    """3 点を通る平面 (n, d): n·p = d (有理数)"""
    P, Q, R = (tuple(map(F, p)) for p in (P, Q, R))
    u = tuple(Q[a] - P[a] for a in range(3)); v = tuple(R[a] - P[a] for a in range(3))
    n = (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0])
    d = sum(n[a] * P[a] for a in range(3))
    return n, d
def section_points(n, d, cube):
    """平面と小立方体の 12 辺の交点 (有理数) の集合"""
    i, j, k = cube; pts = set()
    corners = [(i + a, j + b, k + c) for a in (0, 1) for b in (0, 1) for c in (0, 1)]
    for p0 in corners:
        for ax in range(3):
            if p0[ax] != (i, j, k)[ax]: continue
            p1 = list(p0); p1[ax] += 1
            dirv = [0, 0, 0]; dirv[ax] = 1
            nd = n[ax]; val0 = sum(n[a] * p0[a] for a in range(3))
            if nd == 0:
                if val0 == d: pts.add(tuple(map(F, p0))); pts.add(tuple(map(F, p1)))
            else:
                t = F(d - val0) / nd
                if 0 <= t <= 1:
                    p = list(map(F, p0)); p[ax] += t; pts.add(tuple(p))
    return pts
def hull_area_2d(pts):
    pts = sorted(set(pts))
    if len(pts) < 3: return F(0)
    def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
    lower = []
    for p in pts:
        while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0: lower.pop()
        lower.append(p)
    upper = []
    for p in reversed(pts):
        while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0: upper.pop()
        upper.append(p)
    hull = lower[:-1] + upper[:-1]
    return abs(shoelace(hull)) if len(hull) >= 3 else F(0)
def projected_section_area(n, d, cube):
    """切り口の面積を、法線成分が最大の軸に垂直な面へ射影した面積で測る (同じ平面上なら実面積と比例するので比は同じ)"""
    drop = max(range(3), key=lambda a: abs(n[a]))
    pts = [tuple(p[a] for a in range(3) if a != drop) for p in section_points(n, d, cube)]
    return hull_area_2d(pts)
def area_ratio(plane_pts):
    n, d = plane_through(*plane_pts)
    tot = sum(projected_section_area(n, d, c) for c in ALL)
    blk = sum(projected_section_area(n, d, c) for c in BLACK)
    r = tot / blk
    return (r.numerator, r.denominator)
def count_ratio(plane_pts):
    n, d = plane_through(*plane_pts)
    cut = [c for c in ALL if projected_section_area(n, d, c) > 0]
    w = sum(1 for c in cut if c not in BLACK); b = sum(1 for c in cut if c in BLACK)
    g = math.gcd(w, b)
    return (w // g, b // g)
Bp, Fp, Hp, Ap = (0, 0, 3), (0, 0, 0), (3, 3, 0), (0, 3, 3)
Ip, Jp = (F(3, 2), 0, 0), (3, F(3, 2), 0)
Kp, Lp, Mp = (0, 2, 3), (1, 0, 0), (3, 2, 0)
CHECKS["TOYO-E0017-Q06-S01"] = {"method": "平面 BFH と 27 個の小立方体の切り口を座標計算 (辺との交点→凸包面積) し、全体と黒の面積比を厳密に求める", "compute": lambda: area_ratio((Bp, Fp, Hp)),
                                "extra": [(lambda: count_ratio((Bp, Fp, Hp)) == (2, 1), "切られる個数は白 6・黒 3 (= 9 個、2:1)")]}
CHECKS["TOYO-E0017-Q06-S02"] = {"method": "平面 AIJ と各小立方体の切り口面積を座標計算し、面積が正の立方体を白・黒で数える", "compute": lambda: count_ratio((Ap, Ip, Jp)),
                                "extra": [(lambda: sum(1 for c in ALL if projected_section_area(*plane_through(Ap, Ip, Jp), c) > 0) == 15, "切られる立方体は 15 個 (6+6+3)")]}
CHECKS["TOYO-E0017-Q06-S03"] = {"method": "平面 KLM (K: AK=1, L: FL=1, M: GM=2) と各小立方体の切り口面積を座標計算し、全体と黒の面積比を厳密に求める", "compute": lambda: area_ratio((Kp, Lp, Mp)),
                                "extra": [(lambda: count_ratio((Kp, Lp, Mp)) == (9, 4), "切られる個数は白 9・黒 4 (各段 3,5,5 個)")]}
