Import Spaghetti
InterviewTime limit2sMemory limit512 MB
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 (). The second line contains distinct file names. Each name is a string of 1 to 8 lower case letters from 'a' to 'z'.
Then follow 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 , followed by 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.