I've got a partial solution based on a depth first topological sort, but it doesn't pass all tests either, so needs some work...