def topological(nodes):
    order, enter, state = deque(), set(nodes), {}
    def dfs(node):
        state[node] = GRAY
        for parent in nodes.get(node, ()):
            color = state.get(parent, None)
            if color == GRAY:
                raise ValueError('cycle')
            if color == BLACK:
                continue
            enter.discard(parent)
            dfs(parent)
        order.appendleft(node)
        state[node] = BLACK
    while enter:
        dfs(enter.pop())
    return order