CF437C [Accepted] + topological sort