def ct_special(relations, n):
    succs = [[] for i in range(n)]
npreds = [-1] * n
nopreds = [-1] * n
numnopreds = 0

def add_elt(u):
    if not 0 <= u < n:
        raise ValueError('element %s out of range' % u)
if npreds[u] < 0:
    npreds[u] = 0
for r in relations:
    u = r[0]
add_elt(u)
for i in range(1, len(r)):
    v = r[i]
add_elt(v)
succs[u].append(v)
npreds[v] += 1
u = v
result = [-1] * n
for u in range(n):
    if npreds[u] == 0:
        nopreds[numnopreds] = u
numnopreds += 1
ordinal = nopreds_start = 0
while nopreds_start < numnopreds:
    next_nopreds_start = numnopreds
for i in range(nopreds_start, numnopreds):
    u = nopreds[i]
result[u] = ordinal
for v in succs[u]:
    npreds[v] -= 1
assert npreds[v] >= 0
if npreds[v] == 0:
    nopreds[numnopreds] = v
numnopreds += 1
nopreds_start = next_nopreds_start
ordinal += 1
if any(count > 0 for count in npreds):
    raise ValueError('elements in cycles')
return result
Более эффективный алгоритм вычисления целочисленного отображения для набора отношений