Better topological sort implementation.