import heapq


def topo_sort(graph):
    # graph: {node: [dependencies]}
    # return nodes in deterministic dependency-first alphabetical order
    nodes = set(graph)
    for deps in graph.values():
        nodes.update(deps)

    in_degree = {node: len(graph.get(node, [])) for node in nodes}
    dependents = {node: [] for node in nodes}
    for node, deps in graph.items():
        for dep in deps:
            dependents[dep].append(node)

    heap = [node for node, deg in in_degree.items() if deg == 0]
    heapq.heapify(heap)
    result = []
    while heap:
        node = heapq.heappop(heap)
        result.append(node)
        for nxt in dependents[node]:
            in_degree[nxt] -= 1
            if in_degree[nxt] == 0:
                heapq.heappush(heap, nxt)

    if len(result) != len(nodes):
        raise ValueError("graph contains a cycle")
    return result
