"""Independent check (numpy, no code shared with pin.c / hole2.c).
Decide schedulability of the pinwheel instance  A + (M)  exactly, where the last task has period M.
State of the A-tasks: t_i = days since task i was last performed (0..a_i-1).  For the M-task we keep,
per A-state s, the threshold h(s) = largest c (days since the M-task was last performed) such that the
combined state (s, c) still has an infinite valid continuation (-1 if none).  h is the greatest fixed
point of
   h(s) = max( max_j [h(serve_j(s)) - 1],   M-1 if h(noA(s)) >= 0 )
iterated downward from h = M-1.  Instance is schedulable iff h(start) >= 0.
"""
import sys, time
import numpy as np
from fractions import Fraction
A = [int(x) for x in sys.argv[1].split(",")]; M = int(sys.argv[2])
n = len(A)
full = sorted(A + [M]); k = full[0]
D = sum(Fraction(1, a) for a in full); Bd = 1 - Fraction(k - 1, k * (k + 1))
print("instance", full, "a1 =", k); print("density", D, "=", float(D)); print("bound 1-(a1-1)/(a1(a1+1)) =", Bd, "=", float(Bd)); print("density <= bound:", D <= Bd, flush=True)
w = [1] * n
for i in range(n - 2, -1, -1): w[i] = w[i + 1] * A[i + 1]
size = w[0] * A[0]
w = np.array(w, dtype=np.int64); Aarr = np.array(A, dtype=np.int64)
def digits(codes):
    return (codes[:, None] // w[None, :]) % Aarr[None, :]
def successors(codes):
    """yield (move, mask_valid, succ_codes) ; move == n means no A-task performed that day"""
    dg = digits(codes)
    late = dg + 1 >= Aarr[None, :]          # task would exceed its period unless performed now
    nlate = late.sum(axis=1)
    inc = (dg + 1) @ w                       # all counters +1
    for j in range(n + 1):
        if j == n:
            ok = nlate == 0; sc = inc
        else:
            ok = (nlate - late[:, j]) == 0
            sc = inc - (dg[:, j] + 1) * w[j]
        yield j, ok, sc
t0 = time.time()
seen = np.zeros(size, dtype=bool); seen[0] = True
front = np.array([0], dtype=np.int64); allc = [front]
while front.size:
    nxt = []
    for j, ok, sc in successors(front):
        nxt.append(sc[ok])
    nxt = np.unique(np.concatenate(nxt)); nxt = nxt[~seen[nxt]]; seen[nxt] = True
    front = nxt; allc.append(nxt)
states = np.sort(np.concatenate(allc)); print("reachable A-states:", states.size, "time", round(time.time() - t0, 1), flush=True)
alive = seen.copy(); cur = states
while True:
    keep = np.zeros(cur.size, dtype=bool)
    for j, ok, sc in successors(cur):
        idx = np.where(ok)[0]; keep[idx] |= alive[sc[idx]]
    dead = cur[~keep]
    if dead.size == 0: break
    alive[dead] = False; cur = cur[keep]
L = cur; print("A-states with an infinite continuation:", L.size, "start among them:", bool(alive[0]), "time", round(time.time() - t0, 1), flush=True)
del seen
S = np.full((n + 1, L.size), -1, dtype=np.int32)
for j, ok, sc in successors(L):
    good = ok.copy(); good[ok] = alive[sc[ok]]
    S[j, good] = np.searchsorted(L, sc[good]).astype(np.int32)
    assert np.array_equal(L[S[j, good]], sc[good])
start = int(np.searchsorted(L, 0)); assert L[start] == 0
h = np.full(L.size + 1, M - 1, dtype=np.int32); h[-1] = -1   # index -1 -> sentinel "no successor"
sweep = 0
while True:
    sweep += 1
    new = np.full(L.size, -1, dtype=np.int32)
    for j in range(n):
        np.maximum(new, h[S[j]] - 1, out=new)
    np.maximum(new, -1, out=new)
    new[h[S[n]] >= 0] = M - 1
    changed = int((new != h[:-1]).sum())
    h[:-1] = new
    if sweep % 200 == 0 or changed == 0 or h[start] < 0:
        print("sweep", sweep, "changed", changed, "h(start)", int(h[start]), "max h", int(new.max()), "states with h>=0:", int((new >= 0).sum()), "time", round(time.time() - t0, 1), flush=True)
    if h[start] < 0 or changed == 0: break
print("RESULT:", "SCHEDULABLE" if h[start] >= 0 else "UNSCHEDULABLE", full)
