Read the checking program (73 lines of Python)
"""Check disjoint directed transplant cycles and altruist chains and sum arc weights."""
import json
from pathlib import Path
import sys
MAX_BYTES = 4096
def verify(instance, data):
if len(data) > MAX_BYTES:
raise ValueError('The submission exceeds the byte limit.')
donors = instance['altruists']
vertices = donors + instance['pairs']
max_cycle, max_chain = instance['cycle_cap'], instance['chain_cap']
lines = data.splitlines()
# Every exchange uses at least one recipient; this also bounds parsing work.
if not 1 <= len(lines) <= instance['pairs']:
raise ValueError('Submit one or more exchange rows.')
arcs = {(origin, target): weight for origin, target, weight in instance['arcs']}
seen = set()
total = 0
for line in lines:
tokens = line.split(b' ')
kind, *ids = tokens
if kind == b'C':
if not 2 <= len(ids) <= max_cycle:
raise ValueError('A cycle exceeds the allowed length or contains fewer than two pairs.')
elif kind == b'H':
if not 2 <= len(ids) <= max_chain + 1:
raise ValueError('A chain needs an altruist and recipients within the chain cap.')
else:
raise ValueError('Start each row with C for a cycle or H for a chain.')
if any(not token.isdigit() or len(token) > len(str(vertices - 1)) for token in ids):
raise ValueError('Use a single space between short decimal vertex IDs.')
route = list(map(int, ids))
if any(vertex >= vertices for vertex in route):
raise ValueError('A vertex ID is out of range.')
if kind == b'H':
if route[0] >= donors or any(vertex < donors for vertex in route[1:]):
raise ValueError('A chain must start at an altruist and continue through pairs only.')
elif any(vertex < donors for vertex in route):
raise ValueError('A cycle must contain only patient–donor pairs.')
for vertex in route:
if vertex in seen:
raise ValueError('A vertex occurs more than once.')
seen.add(vertex)
# A cycle includes the return arc. A chain ends at its last pair.
targets = route[1:] + (route[:1] if kind == b'C' else [])
for edge in zip(route, targets):
if edge not in arcs:
raise ValueError('An exchange uses a transplant arc absent from the graph.')
total += arcs[edge]
return total
def main():
with Path(__file__).with_name('instance.json').open(encoding='utf-8') as file:
instance = json.load(file)
try:
score = verify(instance, sys.stdin.buffer.read(MAX_BYTES + 1))
except ValueError as error:
result = {'valid': False, 'score': None, 'message': str(error)}
else:
result = {'valid': True, 'score': score, 'message': 'The exchanges are feasible.'}
print(json.dumps(result))
if __name__ == '__main__':
main()