#C7291. Quest Order Determination

    ID: 51146 Type: Default 1000ms 256MiB

Quest Order Determination

Quest Order Determination

You are given a set of quests along with a list of prerequisite relationships. Each prerequisite is specified as a pair of quest names (A, B) which means that quest A must be completed before quest B. Your task is to determine an order in which all quests can be completed.

If there exists a cycle (i.e. the prerequisites contain a contradiction), output impossible. Otherwise, output one valid ordering; when there are multiple valid orderings, output the lexicographically smallest ordering (when compared as a sequence of strings).

The problem can be represented using the concept of topological sorting on directed acyclic graphs. In mathematical notation, given a directed acyclic graph \(G=(V,E)\), find a permutation \(\pi\) of \(V\) such that for every directed edge \((u,v) \in E\), \(\pi^{-1}(u) < \pi^{-1}(v)\).

inputFormat

The input is read from standard input (stdin) and has the following format:

N
A1 B1
A2 B2
... 
AN BN

Where the first line contains a non-negative integer N representing the number of prerequisite pairs. Each of the following N lines contains two strings separated by whitespace representing a prerequisite relation: the first quest must be completed before the second quest.

outputFormat

If a valid ordering exists, output the quests in order, one per line, following the lexicographically smallest valid topological order. Otherwise, if no valid ordering is possible due to a cycle, output a single line containing impossible.

## sample
4
clean_house cook_meal
buy_groceries cook_meal
buy_groceries clean_house
cook_meal play_game
buy_groceries

clean_house cook_meal play_game

</p>