problems / 146

Deadlock in the Print Shop

easy graphs dfs topological-sort stack 1000 ms · 256 MB

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.

Any correct answer is accepted.

Example 1

Input

5
1 2
1 4
0
2 5 3
1 2

Output

3
2 4 5

Example 2

Input

4
2 2 3
1 4
1 4
0

Output

NO DEADLOCK

Hints · reveal one at a time if you're stuck

Hint 1

Draw an arrow from each job to every job it waits for. A deadlock is then a particular shape in this graph, so what would you look for?

Hint 2

A depth-first search that marks jobs as unvisited, on the current path, or finished finds a cycle when an arrow leads back to a job still on the current path. Use an explicit stack, since the chain can be 2·10^5 long, and keep parent links so you can read the cycle back out.

report an issue Prefer your own editor? sooks prep 146 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.