Under construction

Still being built. Things may change

Import Spaghetti

Interview

Time limit2sMemory limit512 MB

Summary
Find a shortest cycle in a directed dependency graph and print it in lexicographically smallest rotation order, or report that none exists.
Level

Medium6 of 10

Topics
Graph, BFS, String, Implementation
Solved
No attempts yet

Problem

You just graduated from programming school and landed a Python job. On your first day you find out that you inherited a mess. The previous maintainer picked the spaghetti design pattern and recently left the country. You try to make sense of the code and immediately discover that different files depend on each other cyclically. Nobody has tried to test the code, or even to run it.

You sit down and think it over, and you decide that the first thing to do is to remove the cycles from the dependency graph. So you start by finding a shortest dependency cycle.

Input

The first line contains the number of files nn (1≤n≤5001 \le n \le 500). The second line contains nn distinct file names. Each name is a string of 1 to 8 lower case letters from 'a' to 'z'.

Then follow nn sections, one per file, in the order the names were given on the second line. Each section starts with a line holding the name of the file and an integer kk, followed by kk lines that each start with import. An import line writes import and then lists the names it depends on, separated by , .

No file imports the same file more than once, and every imported file appears on the second line. A file may import itself, which is a cycle of length 1.

Output

If the code base has no cyclic dependency, print SHIP IT. Otherwise print, on one line, the names of the files on a shortest cycle in the order of the cycle, separated by single spaces.

There may be several shortest cycles, and the same cycle can be written starting from any of its files. Print the lexicographically smallest of those sequences. Compare two sequences name by name in dictionary order; the first position where they differ decides.

Examples3

  1. Example 1

    Input
    4
    a b c d
    a 1
    import d, b, c
    b 2
    import d
    import c
    c 1
    import c
    d 0
    
    Expected output
    c
    
  2. Example 2

    Input
    5
    classa classb myfilec execd libe
    classa 2
    import classb
    import myfilec, libe
    classb 1
    import execd
    myfilec 1
    import libe
    execd 1
    import libe
    libe 0
    
    Expected output
    SHIP IT
    
  3. Example 3

    Input
    5
    classa classb myfilec execd libe
    classa 2
    import classb
    import myfilec, libe
    classb 1
    import execd
    myfilec 1
    import libe
    execd 1
    import libe, classa
    libe 0
    
    Expected output
    classa classb execd