# Slow reference: explicit reachable graph from the all-fresh state, then: is there a reachable cycle through an idle step?
import sys, random, subprocess
sys.setrecursionlimit(1000000)
def can_idle_forever(a):
    n = len(a); start = tuple(x - 1 for x in a)
    succ = {}; stack = [start]
    while stack:
        s = stack.pop()
        if s in succ: continue
        out = []
        for j in range(-1, n):                     # -1 = idle
            t = tuple((a[i] - 1) if i == j else s[i] - 1 for i in range(n))
            if min(t) >= 0: out.append((t, j == -1))
        succ[s] = out; stack.extend(t for t, _ in out)
    # Tarjan SCC (iterative)
    idx, low, comp, on, st, c, k = {}, {}, {}, set(), [], 0, 0
    for root in succ:
        if root in idx: continue
        work = [(root, iter(succ[root]))]; idx[root] = low[root] = k; k += 1; st.append(root); on.add(root)
        while work:
            v, it = work[-1]
            for w, _ in it:
                if w not in idx:
                    idx[w] = low[w] = k; k += 1; st.append(w); on.add(w); work.append((w, iter(succ[w]))); break
                elif w in on: low[v] = min(low[v], idx[w])
            else:
                work.pop()
                if work: low[work[-1][0]] = min(low[work[-1][0]], low[v])
                if low[v] == idx[v]:
                    while True:
                        w = st.pop(); on.discard(w); comp[w] = c
                        if w == v: break
                    c += 1
    return any(idle and comp[s] == comp[t] for s in succ for t, idle in succ[s])
random.seed(7); bad = 0; pos = 0; N = 300
for _ in range(N):
    n = random.randint(2, 5); a = sorted(random.randint(2, 9) for _ in range(n))
    if sum(1 / x for x in a) > 1: continue
    r = can_idle_forever(a)
    out = subprocess.run(["./check"] + [str(x) for x in a], capture_output=True, text=True).stdout
    b = "CAN idle" in out; pos += r
    if r != b: bad += 1; print("MISMATCH", a, r, b)
print("mismatches:", bad, "instances that can idle:", pos)
