Deadlock in the Print Shop
Bob runs a busy print shop with n print jobs, numbered from 1 to n. Each job has grabbed some
of the shop's printers and will not let go until it finishes, but before it can finish it needs
printers that other jobs are holding. So every job keeps a list of jobs it is waiting for: job
i cannot finish until every job on its list has finished.
Jobs never wait for themselves, and a job appears at most once on any list. A job with an empty list can finish right away; once all jobs on a list have finished, the job owning the list can finish too.
The shop is stuck in a deadlock if there are k ≥ 2 distinct jobs J_1, J_2, …, J_k such
that J_1 waits for J_2, J_2 waits for J_3, …, J_(k-1) waits for J_k, and J_k waits
for J_1. None of these jobs can ever finish.
Help Bob: find any deadlock, or tell him there is none.
Input
The first line contains one integer n (1 ≤ n ≤ 2·10^5), the number of jobs.
Each of the next n lines describes one job; the i-th of them describes job i. It starts with
an integer c_i (0 ≤ c_i ≤ n − 1), the number of jobs that job i waits for, followed by c_i
distinct integers between 1 and n, none equal to i: the jobs it waits for.
The total of all c_i does not exceed 2·10^5.
Output
If there is no deadlock, print NO DEADLOCK.
Otherwise print two lines. The first contains k, the number of jobs in the deadlock. The second
contains k distinct job numbers J_1 J_2 … J_k such that each J_t waits for J_(t+1) for
1 ≤ t < k, and J_k waits for J_1.
If there are several deadlocks, print any of them, starting from any of its jobs.
Notes
In the first example, job 2 waits for job 4, job 4 waits for job 5 and job 5 waits for job 2.
Printing 4 5 2 or 5 2 4 would also be accepted, but 2 5 4 would not: job 2 does not wait for
job 5. Job 1 is stuck as well, but it is not part of the deadlock itself.
In the second example, every job can eventually finish: first job 4, then jobs 2 and 3, then job 1.