"""
병원 간호사 10명 14일 3교대 근무표 자동 생성기 (Python 3.9 표준 라이브러리 전용)
"""

from __future__ import annotations

import itertools
import random
import time
from typing import Dict, List, Optional, Tuple

NURSES: List[str] = [f"N{i:02d}" for i in range(1, 11)]
SENIORS = set(NURSES[:5])   # N01 ~ N05
JUNIORS = set(NURSES[5:])   # N06 ~ N10

NUM_DAYS = 14
WEEKEND_DAYS = {5, 6, 12, 13}

# 사전 휴가 (O 고정)
FIXED_OFF: Dict[str, set] = {
    "N01": {2, 3},
    "N03": {10},
    "N05": {5, 6},
    "N08": {0, 1},
    "N10": {12, 13},
}

SHIFTS = ("D", "E", "N", "O")


def _allowed_shifts(
    nurse: str,
    day: int,
    prev_shift: Optional[str],
    consec_work: int,
    consec_n: int,
    total_work: int,
    total_n: int,
    total_wknd: int,
) -> List[str]:
    """해당 날짜에 특정 간호사가 배정받을 수 있는 근무 목록을 반환한다."""
    if day in FIXED_OFF.get(nurse, ()):
        return ["O"]

    # 연속 5일 근무했으면 6일째는 반드시 휴무
    if consec_work >= 5:
        return ["O"]

    rem_days = NUM_DAYS - day
    # 남은 날을 모두 일해도 최소 7일을 못 채우는 경우 방지
    can_off = (total_work + (rem_days - 1)) >= 7
    # 이미 10일 일했으면 무조건 휴무
    if total_work >= 10:
        return ["O"] if can_off else []

    candidates: List[str] = []
    # 근무 가능 여부 (전환 제약)
    for s in ("D", "E", "N"):
        if prev_shift == "N" and s in ("D", "E"):
            continue
        if prev_shift == "E" and s == "D":
            continue
        if s == "N" and consec_n >= 2:
            continue
        # 야간 쏠림 방지 상한 (총 28개 / 10명 = 평균 2.8 -> 최대 4회로 제한하면 max-min<=2 달성 용이)
        if s == "N" and total_n >= 4:
            continue
        # 주말 근무 쏠림 방지 상한 (총 24개 / 10명 = 평균 2.4 -> 최대 3회로 제한)
        if day in WEEKEND_DAYS and total_wknd >= 3:
            continue
        candidates.append(s)

    if can_off:
        candidates.append("O")
    return candidates


def _solve_with_seed(seed: int, time_limit: float) -> Optional[Dict[str, List[str]]]:
    rng = random.Random(seed)
    start_time = time.perf_counter()

    schedule: List[List[str]] = [[""] * NUM_DAYS for _ in range(10)]
    prev_shift: List[Optional[str]] = [None] * 10
    consec_work: List[int] = [0] * 10
    consec_n: List[int] = [0] * 10
    total_work: List[int] = [0] * 10
    total_n: List[int] = [0] * 10
    total_wknd: List[int] = [0] * 10

    # 각 간호사의 남은 주말 가능 일수 미리 계산 (휴가 제외)
    rem_wknd_avail: List[List[int]] = [[0] * (NUM_DAYS + 1) for _ in range(10)]
    for idx, n in enumerate(NURSES):
        cnt = 0
        for d in range(NUM_DAYS - 1, -1, -1):
            if d in WEEKEND_DAYS and d not in FIXED_OFF.get(n, ()):
                cnt += 1
            rem_wknd_avail[idx][d] = cnt

    nodes = 0

    def backtrack(day: int) -> bool:
        nonlocal nodes
        nodes += 1
        if nodes % 200 == 0 and (time.perf_counter() - start_time) > time_limit:
            return False

        if day == NUM_DAYS:
            # 최종 공정성 검증
            if not (all(7 <= w <= 10 for w in total_work)):
                return False
            if max(total_n) - min(total_n) > 2:
                return False
            if max(total_wknd) - min(total_wknd) > 2:
                return False
            return True

        # 공정성 조기 가지치기 (Pruning)
        # 현재까지 최대 N이 4면 최소 N이 남은 날 동안 2 이상 도달 가능해야 함
        # 주말 근무: 남은 주말 가능 일수로도 max_wknd - 2에 도달 못 하면 실패
        rem_n_slots = (NUM_DAYS - day) * 2
        if max(total_n) - min(total_n) > 2 + rem_n_slots:
            return False
        max_w = max(total_wknd)
        for idx in range(10):
            if total_wknd[idx] + rem_wknd_avail[idx][day] < max_w - 2:
                return False

        # 오늘 각 간호사별 가능한 근무 파악
        allowed: List[List[str]] = []
        d_cands, e_cands, n_cands = [], [], []
        for idx, nurse in enumerate(NURSES):
            al = _allowed_shifts(
                nurse,
                day,
                prev_shift[idx],
                consec_work[idx],
                consec_n[idx],
                total_work[idx],
                total_n[idx],
                total_wknd[idx],
            )
            if not al:
                return False
            allowed.append(al)
            if "D" in al:
                d_cands.append(idx)
            if "E" in al:
                e_cands.append(idx)
            if "N" in al:
                n_cands.append(idx)

        if len(d_cands) < 2 or len(e_cands) < 2 or len(n_cands) < 2:
            return False

        # 시니어(0..4) 최소 1명씩 각 조에 들어갈 수 있는지 빠른 체크
        if not any(i < 5 for i in d_cands):
            return False
        if not any(i < 5 for i in e_cands):
            return False
        if not any(i < 5 for i in n_cands):
            return False

        # 가능한 (D 2명, E 2명, N 2명) 조합 생성 및 휴리스틱 점수 정렬
        # 점수 낮을수록 균형 잡힌 배정 (근무일수 적은 사람, N 적은 사람, 주말근무 적은 사람 우선)
        is_wknd = day in WEEKEND_DAYS

        def work_score(idx: int, shift: str) -> float:
            # 누적 근무가 적은 사람에게 가산점(낮은 비용)
            sc = total_work[idx] * 2.5
            if shift == "N":
                sc += total_n[idx] * 5.0
            if is_wknd:
                sc += total_wknd[idx] * 4.5
            # 내일 이후 유연성 보존: D는 전환 제약이 없으므로 E/N보다 살짝 선호하거나 균형
            # 연속 근무가 길수록 쉬게 유도
            sc += consec_work[idx] * 1.2
            sc += rng.uniform(0.0, 0.35)
            return sc

        d_pairs = [
            p for p in itertools.combinations(d_cands, 2)
            if (p[0] < 5 or p[1] < 5)
        ]
        e_pairs = [
            p for p in itertools.combinations(e_cands, 2)
            if (p[0] < 5 or p[1] < 5)
        ]
        n_pairs = [
            p for p in itertools.combinations(n_cands, 2)
            if (p[0] < 5 or p[1] < 5)
        ]

        d_pairs.sort(key=lambda p: work_score(p[0], "D") + work_score(p[1], "D"))
        e_pairs.sort(key=lambda p: work_score(p[0], "E") + work_score(p[1], "E"))
        n_pairs.sort(key=lambda p: work_score(p[0], "N") + work_score(p[1], "N"))

        # 분기 폭발 방지를 위해 상위 후보 조합 탐색
        day_assignments: List[Tuple[float, Tuple[int, int], Tuple[int, int], Tuple[int, int]]] = []
        for np in n_pairs[:12]:
            used_n = set(np)
            for ep in e_pairs[:15]:
                if ep[0] in used_n or ep[1] in used_n:
                    continue
                used_ne = used_n | set(ep)
                for dp in d_pairs[:15]:
                    if dp[0] in used_ne or dp[1] in used_ne:
                        continue
                    used_all = used_ne | set(dp)
                    # 나머지 4명이 모두 'O'가 가능해야 함
                    if all("O" in allowed[i] for i in range(10) if i not in used_all):
                        cost = (
                            work_score(dp[0], "D") + work_score(dp[1], "D")
                            + work_score(ep[0], "E") + work_score(ep[1], "E")
                            + work_score(np[0], "N") + work_score(np[1], "N")
                        )
                        day_assignments.append((cost, dp, ep, np))

        day_assignments.sort(key=lambda x: x[0])

        for _, dp, ep, np in day_assignments[:18]:
            # 상태 백업
            snap_prev = prev_shift[:]
            snap_cw = consec_work[:]
            snap_cn = consec_n[:]
            snap_tw = total_work[:]
            snap_tn = total_n[:]
            snap_twk = total_wknd[:]

            assigned = {}
            for i in dp:
                assigned[i] = "D"
            for i in ep:
                assigned[i] = "E"
            for i in np:
                assigned[i] = "N"

            for i in range(10):
                s = assigned.get(i, "O")
                schedule[i][day] = s
                prev_shift[i] = s
                if s == "O":
                    consec_work[i] = 0
                    consec_n[i] = 0
                else:
                    consec_work[i] += 1
                    total_work[i] += 1
                    if is_wknd:
                        total_wknd[i] += 1
                    if s == "N":
                        consec_n[i] += 1
                        total_n[i] += 1
                    else:
                        consec_n[i] = 0

            if backtrack(day + 1):
                return True

            # 상태 복원
            prev_shift[:] = snap_prev
            consec_work[:] = snap_cw
            consec_n[:] = snap_cn
            total_work[:] = snap_tw
            total_n[:] = snap_tn
            total_wknd[:] = snap_twk

        return False

    if backtrack(0):
        return {NURSES[i]: schedule[i] for i in range(10)}
    return None


def solve(timeout: float = 4.5) -> Dict[str, List[str]]:
    """14일 3교대 근무표를 생성하여 딕셔너리로 반환한다."""
    deadline = time.perf_counter() + timeout
    seed = 42
    while time.perf_counter() < deadline:
        remaining = deadline - time.perf_counter()
        slice_limit = min(0.4, remaining)
        if slice_limit <= 0.01:
            break
        res = _solve_with_seed(seed, slice_limit)
        if res is not None:
            return res
        seed += 1
    raise RuntimeError("제한 시간 내에 모든 제약을 만족하는 근무표를 찾지 못했습니다.")


def format_schedule(schedule: Dict[str, List[str]]) -> str:
    """근무표를 보기 좋은 표 문자열로 포맷한다."""
    header = "간호사 | " + " ".join(f"D{d:02d}" for d in range(NUM_DAYS)) + " | 근무  야간  주말"
    lines = [header, "-" * len(header)]
    for nurse in NURSES:
        row = schedule[nurse]
        work_cnt = sum(1 for s in row if s != "O")
        n_cnt = sum(1 for s in row if s == "N")
        wknd_cnt = sum(1 for d in WEEKEND_DAYS if row[d] != "O")
        role = "(S)" if nurse in SENIORS else "(J)"
        cells = "  ".join(row)
        lines.append(f"{nurse}{role}|  {cells} |  {work_cnt:2d}    {n_cnt:2d}    {wknd_cnt:2d}")
    return "\n".join(lines)


if __name__ == "__main__":
    t0 = time.perf_counter()
    result = solve()
    elapsed = time.perf_counter() - t0
    print(f"[14일 3교대 근무표 생성 완료 - 소요시간: {elapsed:.4f}s]")
    print(format_schedule(result))
