Read the checking program (184 lines of Python)
"""Check an IHTC 2024 hospital timetable and compute its exact weighted cost."""
import json
import sys
from collections import Counter, defaultdict
from pathlib import Path
MAX_BYTES = 256 * 1024
class InvalidSubmission(ValueError):
"""The submission does not describe a feasible timetable."""
def require(condition, message):
if not condition:
raise InvalidSubmission(message)
def unique_fields(pairs):
result = dict(pairs)
require(len(result) == len(pairs), "JSON object keys must be unique.")
return result
def small_int(token):
require(len(token) <= 3, "A day number must be a small integer.")
return int(token)
def reject_number(_token):
raise InvalidSubmission("Day numbers must be integers.")
def check_fields(value, fields):
require(type(value) is dict and value.keys() == fields, "An object has missing or unexpected fields.")
def check_list(value, limit):
require(type(value) is list and len(value) <= limit, "An assignment list has the wrong type or too many entries.")
def check_id(value, allowed):
require(type(value) is str and value in allowed, "An assignment contains an unknown identifier.")
def verify(instance, solution):
"""Return the integer cost or raise InvalidSubmission for an invalid schedule."""
days = instance["days"]
shifts = instance["shift_types"]
rooms = {row["id"]: row["capacity"] for row in instance["rooms"]}
theaters = {row["id"]: row["availability"] for row in instance["operating_theaters"]}
surgeons = {row["id"]: row["max_surgery_time"] for row in instance["surgeons"]}
nurses = {row["id"]: row for row in instance["nurses"]}
patients = {row["id"]: row for row in instance["patients"]}
age_rank = {label: i for i, label in enumerate(instance["age_groups"])}
limits = {
(nid, shift["day"], shift["shift"]): shift["max_load"]
for nid, nurse in nurses.items() for shift in nurse["working_shifts"]
}
check_fields(solution, {"patients", "nurses"})
check_list(solution["patients"], len(patients))
check_list(solution["nurses"], len(nurses))
# Include occupants already in hospital at the start of day zero.
stays = [(row, row["room_id"], 0) for row in instance["occupants"]]
seen_patients, scheduled = set(), set()
theater_minutes, surgeon_minutes = Counter(), Counter()
surgeon_theaters = defaultdict(set)
costs = Counter()
for entry in solution["patients"]:
if type(entry) is dict and entry.get("admission_day") == "none":
check_fields(entry, {"id", "admission_day"})
else:
check_fields(entry, {"id", "admission_day", "room", "operating_theater"})
pid, day = entry["id"], entry["admission_day"]
check_id(pid, patients)
require(pid not in seen_patients, "A patient appears more than once.")
seen_patients.add(pid)
if day == "none":
continue
patient = patients[pid]
room, theater = entry["room"], entry["operating_theater"]
check_id(room, rooms)
check_id(theater, theaters)
release = patient["surgery_release_day"]
due = patient["surgery_due_day"] if patient["mandatory"] else days - 1
require(type(day) is int and release <= day <= min(due, days - 1),
"An admission day is outside the patient's allowed window.")
require(room not in patient["incompatible_room_ids"], "A patient is assigned an incompatible room.")
scheduled.add(pid)
stays.append((patient, room, day))
surgeon = patient["surgeon_id"]
duration = patient["surgery_duration"]
theater_minutes[theater, day] += duration
surgeon_minutes[surgeon, day] += duration
surgeon_theaters[surgeon, day].add(theater)
costs["patient_delay"] += day - release
for pid in patients.keys() - scheduled:
require(not patients[pid]["mandatory"], "A mandatory patient is missing.")
costs["unscheduled_optional"] += 1
for (theater, day), minutes in theater_minutes.items():
require(minutes <= theaters[theater][day], "An operating theater exceeds its daily time limit.")
for (surgeon, day), minutes in surgeon_minutes.items():
require(minutes <= surgeons[surgeon][day], "A surgeon exceeds the daily time limit.")
costs["open_operating_theater"] = len(theater_minutes)
costs["surgeon_transfer"] = sum(len(used) - 1 for used in surgeon_theaters.values())
coverage, seen_nurses = {}, set()
for nurse in solution["nurses"]:
check_fields(nurse, {"id", "assignments"})
nid = nurse["id"]
check_id(nid, nurses)
require(nid not in seen_nurses, "A nurse appears more than once.")
seen_nurses.add(nid)
check_list(nurse["assignments"], days * len(shifts))
for assignment in nurse["assignments"]:
check_fields(assignment, {"day", "shift", "rooms"})
day, shift = assignment["day"], assignment["shift"]
require(type(day) is int and 0 <= day < days, "A nurse assignment day is outside the horizon.")
check_id(shift, shifts)
check_list(assignment["rooms"], len(rooms))
for room in assignment["rooms"]:
check_id(room, rooms)
require((nid, day, shift) in limits, "A nurse is assigned outside the fixed roster.")
key = (room, day, shift)
require(key not in coverage, "A room has more than one assignment in a shift.")
coverage[key] = nid
# Walk each stay only through the horizon. Skill and load profiles start
# at admission, or at day zero for an existing occupant.
room_days = defaultdict(list)
loads = Counter()
for person, room, start in stays:
assigned_nurses = set()
for day in range(start, min(days, start + person["length_of_stay"])):
room_days[room, day].append(person)
for offset, shift in enumerate(shifts):
nid = coverage.get((room, day, shift))
require(nid is not None, "An occupied room is missing a nurse for a shift.")
assigned_nurses.add(nid)
index = (day - start) * len(shifts) + offset
deficit = person["skill_level_required"][index] - nurses[nid]["skill_level"]
costs["room_nurse_skill"] += max(0, deficit)
loads[nid, day, shift] += person["workload_produced"][index]
costs["continuity_of_care"] += len(assigned_nurses)
for (room, _day), occupants in room_days.items():
require(len(occupants) <= rooms[room], "A room exceeds its bed capacity.")
require(len({row["gender"] for row in occupants}) == 1, "A room mixes the benchmark gender categories.")
ages = [age_rank[row["age_group"]] for row in occupants]
costs["room_mixed_age"] += max(ages) - min(ages)
costs["nurse_eccessive_workload"] = sum(max(0, load - limits[key]) for key, load in loads.items())
return sum(weight * costs[key] for key, weight in instance["weights"].items())
def main():
try:
data = sys.stdin.buffer.read(MAX_BYTES + 1)
require(len(data) <= MAX_BYTES, "The submission exceeds the byte limit.")
try:
solution = json.loads(
data.decode("utf-8"), object_pairs_hook=unique_fields,
parse_int=small_int, parse_float=reject_number, parse_constant=reject_number,
)
except (UnicodeError, json.JSONDecodeError, RecursionError):
raise InvalidSubmission("Submit a UTF-8 JSON timetable.") from None
with Path(__file__).with_name("instance.json").open(encoding="utf-8") as file:
instance = json.load(file)
score = verify(instance, solution)
except InvalidSubmission as error:
result = {"valid": False, "score": None, "message": str(error)}
else:
result = {"valid": True, "score": score, "message": "The timetable is feasible."}
print(json.dumps(result))
if __name__ == "__main__":
main()