Choose your own path
InterviewTime limit2sMemory limit512 MB
Given a directed graph of story pages starting at page 1, check whether every page is reachable, then report the shortest distance to any ending page.
- Level
Medium4 of 10
- Topics
- Graph, BFS, DFS, Shortest path
- Solved
- No attempts yet
Problem
There is a genre of fiction called choose your own adventure books. These books let the reader make choices for the characters, and those choices change the outcome of the story.
For example, after reading the first page of a book, the reader may be asked a choice such as "Do you pick up the rock?" If the reader answers "yes", the book directs them to continue on page 47, and if they choose "no", it directs them to continue on page 18. On each of those pages they face further choices, and so on through the book. Some pages have no choices at all, so they are the "ending" pages of that version of the story. A book may have many such ending pages. Some endings are good (for example, the hero finds treasure) and others are not (for example, the hero finds a leftover sandwich from 2001).
You are the editor of one of these books, and you must examine two things about it:
- Make sure every page can be reached. There is no reason to pay to print a page no one can ever read.
- Find the shortest path, so readers know the least amount of time they need to finish one version of the story.
Given a description of the book, examine these two things.
Input
The first line of input contains N (1 ≤ N ≤ 10000), the number of pages in the book. Each of the next N lines contains an integer Mi (1 ≤ i ≤ N; 0 ≤ Mi ≤ N), which is the number of different options from page i, followed by Mi space-separated integers in the range from 1 to N, each giving a page to go to next from page i. Also, M1 + M2 + ... + MN is at most 10000.
If Mi = 0, then page i is an ending page: there are no choices from that page. There will be at least one ending page in the book.
The book always begins on page 1.
Output
The output will be two lines. The first line will contain Y if all pages are reachable, and N otherwise.
The last line will contain a non-negative integer K, which is the shortest path a reader can take while reading this book. There will always be a finite shortest path.