Book (Codeforces 1572A)
Tags: DP, binary search

You are given a book with $$$n$$$ chapters.Each chapter has a specified list of other chapters that need to be understood in order to understand this chapter. To understand a chapter, you must read it after you understand every chapter on its required list.Currently you don't understand any of the chapters. You are going to read the book from the beginning till the end repeatedly until you understand the whole book. Note that if you read a chapter at a moment when you don't understand some of the required chapters, you don't understand this chapter.Determine how many times you will read the book to understand every chapter, or determine that you will never understand every chapter no matter how many times you read the book.

Input: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2\cdot10^4$$$).The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — number of chapters.Then $$$n$$$ lines follow. The $$$i$$$-th line begins with an integer $$$k_i$$$ ($$$0 \le k_i \le n-1$$$) — number of chapters required to understand the $$$i$$$-th chapter. Then $$$k_i$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i, k_i}$$$ ($$$1 \le a_{i, j} \le n, a_{i, j} \ne i, a_{i, j} \ne a_{i, l}$$$ for $$$j \ne l$$$) follow — the chapters required to understand the $$$i$$$-th chapter.It is guaranteed that the sum of $$$n$$$ and sum of $$$k_i$$$ over all testcases do not exceed $$$2\cdot10^5$$$.

Output: For each test case, if the entire book can be understood, print how many times you will read it, otherwise print $$$-1$$$.

Note: In the first example, we will understand chapters $$$\{2, 4\}$$$ in the first reading and chapters $$$\{1, 3\}$$$ in the second reading of the book.In the second example, every chapter requires the understanding of some other chapter, so it is impossible to understand the book.In the third example, every chapter requires only chapters that appear earlier in the book, so we can understand everything in one go.In the fourth example, we will understand chapters $$$\{2, 3, 4\}$$$ in the first reading and chapter $$$1$$$ in the second reading of the book.In the fifth example, we will understand one chapter in every reading from $$$5$$$ to $$$1$$$.

Sample Inputs:
5
4
1 2
0
2 1 4
1 2
5
1 5
1 1
1 2
1 3
1 4
5
0
0
2 1 2
1 2
2 2 1
4
2 2 3
0
0
2 3 2
5
1 2
1 3
1 4
1 5
0

Sample Outputs:
2
-1
1
2
5

Solution (Python):
import sys
line_num = 0
consumed = 0
line_no = 0
input_lines = []
res = []
out = []

def solution(arr, n):
    graph = {}
    in_degree = [0] * (n + 1)
    for (u, v) in arr:
        if u not in graph:
            graph[u] = []
        graph[u].append(v)
        in_degree[v] += 1
    q = []
    visited = set()
    times = [0] * (n + 1)
    for i in range(1, n + 1):
        if in_degree[i] == 0:
            q.append(i)
            visited.add(i)
        times[i] = 1
    while q:
        cur = q.pop()
        for next_node in graph.get(cur, []):
            in_degree[next_node] -= 1
            if cur < next_node:
                times[next_node] = max(times[cur], times[next_node])
            else:
                times[next_node] = max(times[next_node], times[cur] + 1)
            if in_degree[next_node] == 0:
                q.append(next_node)
                visited.add(next_node)
    if len(visited) == n:
        return max(times)
    else:
        return -1
for line in sys.stdin:
    input_lines.append(line.rstrip())
    if len(input_lines) == 2:
        line_num = int(input_lines[1])
    if len(input_lines) > 2:
        consumed += 1
        input_lines.pop()
        tmp = list(map(int, line.split()))
        line_no += 1
        if len(tmp) > 1:
            for j in range(1, len(tmp)):
                res.append((tmp[j], line_no))
        if consumed == line_num:
            ans = solution(res, line_num)
            out.append(ans if ans == -1 else ans)
            input_lines = input_lines[:1]
            consumed = 0
            line_no = 0
            res = []
output_str = '\n'.join(map(str, out))
print(output_str)

Solution (Python):
from heapq import *
t = int(input())
for _ in range(t):
    n = int(input())
    b = [[] for i in range(n + 1)]
    d = [0 for i in range(n + 1)]
    for i in range(1, n + 1):
        l = list(map(int, input().split()))
        d[i] = l[0]
        for j in l[1:]:
            b[j].append(i)
    count = 0
    cursum = sum(d)
    if cursum == 0:
        print(1)
    else:
        possible = True
        canread = []
        for i in range(1, n + 1):
            if d[i] == 0:
                heappush(canread, i)
        while True:
            if len(canread) == 0:
                break
            count += 1
            nextread = []
            while len(canread) > 0:
                x = heappop(canread)
                for c in b[x]:
                    d[c] -= 1
                    if d[c] == 0:
                        if c > x:
                            heappush(canread, c)
                        else:
                            heappush(nextread, c)
            canread = nextread
        print(count if sum(d) == 0 else -1)

Solution (Python):
import sys, heapq
for _ in range(int(sys.stdin.readline())):
    n = int(sys.stdin.readline())
    d = [[] for i in range(n)]
    h = []
    l = []
    for i in range(n):
        y = [int(i) for i in sys.stdin.readline().split()]
        l.append(y[0])
        if y[0] == 0:
            heapq.heappush(h, i)
        for j in range(1, y[0] + 1):
            d[y[j] - 1].append(i)
    c = t = 0
    while h:
        i = heapq.heappop(h)
        t += 1
        c = i // n
        i = i % n
        for j in d[i]:
            l[j] -= 1
            if l[j] == 0:
                heapq.heappush(h, j + c * n if j > i else j + n + c * n)
    sys.stdout.write('%d\n' % (c + 1 if t == n else -1))