Given a finite, partially ordered set with the following two properties:

- Every element in the set has one of two types: “A” or “B”. The type does not define the total ordering of the set and is metadata.
- Every element in the set is a natural number and the poset can be ranked by the numbers themselves. This means that the sorted elements themselves provide one of the possible total orders of the poset, or in graph theory, one of the topological orderings of the DAG.

What is the most optimal algorithm to find the total ordering of the described poset that groups elements with the same type together?

The posets are represented by describing the type and dependencies of every element such that:

`0:{[], A}, 1:{[0], A}, 2:{[], B}, 3:{[2], A} 4:{[0], A}, 5:{[0,1,4], B}, 6:{[1,2], A}`

looks like this:

Where the blue dot represents the “B” type and every other element is of type “A”. The following are some of the valid total orderings:

`[0, 1, 2, 3, 4, 5, 6, 7]`

`[0, 2, 1, 4, 3, 6, 5, 7]`

`[0, 2, 1, 4, 3, 6, 7, 5]`

However, I have been trying to find the most optimal algorithm that will group elements based on their type, if it is possible, while preserving the total order. For the DAG/poset in the example, one of the possible solutions would be:

`[[0, 1, 4], [5, 2], [6, 3, 7]]`

Thank you!