This page is still under construction.

Parts of this page are still being built. What you see may change.

Tournament Ranking

Interview

Time limit1sMemory limit128 MB

Summary
Given game results between teams, produce the lexicographically smallest topological order, or report that no valid ranking exists due to a cycle.
Level

Medium5 of 10

Topics
Graph, Topological sort, Greedy, Heap
Solved
No attempts yet

Problem

You are given a number of teams and the results of games played by pairs of these teams in a tournament. Depending on your favorite sport, the teams could be football teams, bowling teams, or basketball teams. Each team is identified by an upper case letter, and there are at most 26 teams.

Your mission is to rank the teams if possible. Using the results of the games played between the teams, you must produce a linearly ordered list that starts with the best team and progresses down to the worst one. We assume that if team A beats team B then A is always better than B, and if B in turn beats C then A is also better than C. Thus, given such results, the teams would be ranked A B C. Note that a legal ranking is not always possible: if C also beats A, then the teams cannot be ranked.

Your job is to produce a legal ranking or to determine that no such ranking exists. When the order of two teams cannot be determined from the results, the team whose letter comes earlier in the alphabet must be listed first (so A is listed before B); as a result you output the lexicographically smallest valid ranking. For example, B C A D is preferred over C A B D.

Input

The first line contains the number of tournaments you are asked to rank. For each tournament, the first line contains the number of teams and the number of games played. You may assume that the teams are named consecutively starting from A. Each of the following lines describes one game and contains two upper case letters separated by a single space; the two letters indicate the winner and the loser of that game, in that order.

Output

For each tournament, list all teams on one line, with each team appearing exactly once in its correct position and a single space between adjacent letters. If no ranking is possible, print No legal ranking possible.

Examples3

  1. Example 1

    Input
    2
    4 4
    A B
    B D
    C D
    A C
    3 3
    A B
    B C
    C A
    
    Expected output
    A B C D
    No legal ranking possible
    
  2. Example 2

    Input
    1
    2 0
    
    Expected output
    A B
    
  3. Example 3

    Input
    1
    4 3
    B C
    C A
    A D
    
    Expected output
    B C A D